xref: /freebsd-src/contrib/llvm-project/clang/lib/Sema/SemaChecking.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5384                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5385                IsOpenCL;
5386   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5387              Op == AtomicExpr::AO__atomic_store_n ||
5388              Op == AtomicExpr::AO__atomic_exchange_n ||
5389              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5390   bool IsAddSub = false;
5391 
5392   switch (Op) {
5393   case AtomicExpr::AO__c11_atomic_init:
5394   case AtomicExpr::AO__opencl_atomic_init:
5395     Form = Init;
5396     break;
5397 
5398   case AtomicExpr::AO__c11_atomic_load:
5399   case AtomicExpr::AO__opencl_atomic_load:
5400   case AtomicExpr::AO__atomic_load_n:
5401     Form = Load;
5402     break;
5403 
5404   case AtomicExpr::AO__atomic_load:
5405     Form = LoadCopy;
5406     break;
5407 
5408   case AtomicExpr::AO__c11_atomic_store:
5409   case AtomicExpr::AO__opencl_atomic_store:
5410   case AtomicExpr::AO__atomic_store:
5411   case AtomicExpr::AO__atomic_store_n:
5412     Form = Copy;
5413     break;
5414 
5415   case AtomicExpr::AO__c11_atomic_fetch_add:
5416   case AtomicExpr::AO__c11_atomic_fetch_sub:
5417   case AtomicExpr::AO__opencl_atomic_fetch_add:
5418   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5419   case AtomicExpr::AO__atomic_fetch_add:
5420   case AtomicExpr::AO__atomic_fetch_sub:
5421   case AtomicExpr::AO__atomic_add_fetch:
5422   case AtomicExpr::AO__atomic_sub_fetch:
5423     IsAddSub = true;
5424     Form = Arithmetic;
5425     break;
5426   case AtomicExpr::AO__c11_atomic_fetch_and:
5427   case AtomicExpr::AO__c11_atomic_fetch_or:
5428   case AtomicExpr::AO__c11_atomic_fetch_xor:
5429   case AtomicExpr::AO__c11_atomic_fetch_nand:
5430   case AtomicExpr::AO__opencl_atomic_fetch_and:
5431   case AtomicExpr::AO__opencl_atomic_fetch_or:
5432   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5433   case AtomicExpr::AO__atomic_fetch_and:
5434   case AtomicExpr::AO__atomic_fetch_or:
5435   case AtomicExpr::AO__atomic_fetch_xor:
5436   case AtomicExpr::AO__atomic_fetch_nand:
5437   case AtomicExpr::AO__atomic_and_fetch:
5438   case AtomicExpr::AO__atomic_or_fetch:
5439   case AtomicExpr::AO__atomic_xor_fetch:
5440   case AtomicExpr::AO__atomic_nand_fetch:
5441     Form = Arithmetic;
5442     break;
5443   case AtomicExpr::AO__c11_atomic_fetch_min:
5444   case AtomicExpr::AO__c11_atomic_fetch_max:
5445   case AtomicExpr::AO__opencl_atomic_fetch_min:
5446   case AtomicExpr::AO__opencl_atomic_fetch_max:
5447   case AtomicExpr::AO__atomic_min_fetch:
5448   case AtomicExpr::AO__atomic_max_fetch:
5449   case AtomicExpr::AO__atomic_fetch_min:
5450   case AtomicExpr::AO__atomic_fetch_max:
5451     Form = Arithmetic;
5452     break;
5453 
5454   case AtomicExpr::AO__c11_atomic_exchange:
5455   case AtomicExpr::AO__opencl_atomic_exchange:
5456   case AtomicExpr::AO__atomic_exchange_n:
5457     Form = Xchg;
5458     break;
5459 
5460   case AtomicExpr::AO__atomic_exchange:
5461     Form = GNUXchg;
5462     break;
5463 
5464   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5465   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5466   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5467   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5468     Form = C11CmpXchg;
5469     break;
5470 
5471   case AtomicExpr::AO__atomic_compare_exchange:
5472   case AtomicExpr::AO__atomic_compare_exchange_n:
5473     Form = GNUCmpXchg;
5474     break;
5475   }
5476 
5477   unsigned AdjustedNumArgs = NumArgs[Form];
5478   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5479     ++AdjustedNumArgs;
5480   // Check we have the right number of arguments.
5481   if (Args.size() < AdjustedNumArgs) {
5482     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5483         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5484         << ExprRange;
5485     return ExprError();
5486   } else if (Args.size() > AdjustedNumArgs) {
5487     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5488          diag::err_typecheck_call_too_many_args)
5489         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5490         << ExprRange;
5491     return ExprError();
5492   }
5493 
5494   // Inspect the first argument of the atomic operation.
5495   Expr *Ptr = Args[0];
5496   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5497   if (ConvertedPtr.isInvalid())
5498     return ExprError();
5499 
5500   Ptr = ConvertedPtr.get();
5501   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5502   if (!pointerType) {
5503     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5504         << Ptr->getType() << Ptr->getSourceRange();
5505     return ExprError();
5506   }
5507 
5508   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5509   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5510   QualType ValType = AtomTy; // 'C'
5511   if (IsC11) {
5512     if (!AtomTy->isAtomicType()) {
5513       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5514           << Ptr->getType() << Ptr->getSourceRange();
5515       return ExprError();
5516     }
5517     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5518         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5519       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5520           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5521           << Ptr->getSourceRange();
5522       return ExprError();
5523     }
5524     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5525   } else if (Form != Load && Form != LoadCopy) {
5526     if (ValType.isConstQualified()) {
5527       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5528           << Ptr->getType() << Ptr->getSourceRange();
5529       return ExprError();
5530     }
5531   }
5532 
5533   // For an arithmetic operation, the implied arithmetic must be well-formed.
5534   if (Form == Arithmetic) {
5535     // GCC does not enforce these rules for GNU atomics, but we do, because if
5536     // we didn't it would be very confusing. FIXME:  For whom? How so?
5537     auto IsAllowedValueType = [&](QualType ValType) {
5538       if (ValType->isIntegerType())
5539         return true;
5540       if (ValType->isPointerType())
5541         return true;
5542       if (!ValType->isFloatingType())
5543         return false;
5544       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5545       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5546           &Context.getTargetInfo().getLongDoubleFormat() ==
5547               &llvm::APFloat::x87DoubleExtended())
5548         return false;
5549       return true;
5550     };
5551     if (IsAddSub && !IsAllowedValueType(ValType)) {
5552       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5553           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5554       return ExprError();
5555     }
5556     if (!IsAddSub && !ValType->isIntegerType()) {
5557       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5558           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5559       return ExprError();
5560     }
5561     if (IsC11 && ValType->isPointerType() &&
5562         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5563                             diag::err_incomplete_type)) {
5564       return ExprError();
5565     }
5566   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5567     // For __atomic_*_n operations, the value type must be a scalar integral or
5568     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5569     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5570         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5571     return ExprError();
5572   }
5573 
5574   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5575       !AtomTy->isScalarType()) {
5576     // For GNU atomics, require a trivially-copyable type. This is not part of
5577     // the GNU atomics specification, but we enforce it, because if we didn't it
5578     // would be very confusing. FIXME:  For whom? How so?
5579     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5580         << Ptr->getType() << Ptr->getSourceRange();
5581     return ExprError();
5582   }
5583 
5584   switch (ValType.getObjCLifetime()) {
5585   case Qualifiers::OCL_None:
5586   case Qualifiers::OCL_ExplicitNone:
5587     // okay
5588     break;
5589 
5590   case Qualifiers::OCL_Weak:
5591   case Qualifiers::OCL_Strong:
5592   case Qualifiers::OCL_Autoreleasing:
5593     // FIXME: Can this happen? By this point, ValType should be known
5594     // to be trivially copyable.
5595     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5596         << ValType << Ptr->getSourceRange();
5597     return ExprError();
5598   }
5599 
5600   // All atomic operations have an overload which takes a pointer to a volatile
5601   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5602   // into the result or the other operands. Similarly atomic_load takes a
5603   // pointer to a const 'A'.
5604   ValType.removeLocalVolatile();
5605   ValType.removeLocalConst();
5606   QualType ResultType = ValType;
5607   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5608       Form == Init)
5609     ResultType = Context.VoidTy;
5610   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5611     ResultType = Context.BoolTy;
5612 
5613   // The type of a parameter passed 'by value'. In the GNU atomics, such
5614   // arguments are actually passed as pointers.
5615   QualType ByValType = ValType; // 'CP'
5616   bool IsPassedByAddress = false;
5617   if (!IsC11 && !IsN) {
5618     ByValType = Ptr->getType();
5619     IsPassedByAddress = true;
5620   }
5621 
5622   SmallVector<Expr *, 5> APIOrderedArgs;
5623   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5624     APIOrderedArgs.push_back(Args[0]);
5625     switch (Form) {
5626     case Init:
5627     case Load:
5628       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5629       break;
5630     case LoadCopy:
5631     case Copy:
5632     case Arithmetic:
5633     case Xchg:
5634       APIOrderedArgs.push_back(Args[2]); // Val1
5635       APIOrderedArgs.push_back(Args[1]); // Order
5636       break;
5637     case GNUXchg:
5638       APIOrderedArgs.push_back(Args[2]); // Val1
5639       APIOrderedArgs.push_back(Args[3]); // Val2
5640       APIOrderedArgs.push_back(Args[1]); // Order
5641       break;
5642     case C11CmpXchg:
5643       APIOrderedArgs.push_back(Args[2]); // Val1
5644       APIOrderedArgs.push_back(Args[4]); // Val2
5645       APIOrderedArgs.push_back(Args[1]); // Order
5646       APIOrderedArgs.push_back(Args[3]); // OrderFail
5647       break;
5648     case GNUCmpXchg:
5649       APIOrderedArgs.push_back(Args[2]); // Val1
5650       APIOrderedArgs.push_back(Args[4]); // Val2
5651       APIOrderedArgs.push_back(Args[5]); // Weak
5652       APIOrderedArgs.push_back(Args[1]); // Order
5653       APIOrderedArgs.push_back(Args[3]); // OrderFail
5654       break;
5655     }
5656   } else
5657     APIOrderedArgs.append(Args.begin(), Args.end());
5658 
5659   // The first argument's non-CV pointer type is used to deduce the type of
5660   // subsequent arguments, except for:
5661   //  - weak flag (always converted to bool)
5662   //  - memory order (always converted to int)
5663   //  - scope  (always converted to int)
5664   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5665     QualType Ty;
5666     if (i < NumVals[Form] + 1) {
5667       switch (i) {
5668       case 0:
5669         // The first argument is always a pointer. It has a fixed type.
5670         // It is always dereferenced, a nullptr is undefined.
5671         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5672         // Nothing else to do: we already know all we want about this pointer.
5673         continue;
5674       case 1:
5675         // The second argument is the non-atomic operand. For arithmetic, this
5676         // is always passed by value, and for a compare_exchange it is always
5677         // passed by address. For the rest, GNU uses by-address and C11 uses
5678         // by-value.
5679         assert(Form != Load);
5680         if (Form == Arithmetic && ValType->isPointerType())
5681           Ty = Context.getPointerDiffType();
5682         else if (Form == Init || Form == Arithmetic)
5683           Ty = ValType;
5684         else if (Form == Copy || Form == Xchg) {
5685           if (IsPassedByAddress) {
5686             // The value pointer is always dereferenced, a nullptr is undefined.
5687             CheckNonNullArgument(*this, APIOrderedArgs[i],
5688                                  ExprRange.getBegin());
5689           }
5690           Ty = ByValType;
5691         } else {
5692           Expr *ValArg = APIOrderedArgs[i];
5693           // The value pointer is always dereferenced, a nullptr is undefined.
5694           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5695           LangAS AS = LangAS::Default;
5696           // Keep address space of non-atomic pointer type.
5697           if (const PointerType *PtrTy =
5698                   ValArg->getType()->getAs<PointerType>()) {
5699             AS = PtrTy->getPointeeType().getAddressSpace();
5700           }
5701           Ty = Context.getPointerType(
5702               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5703         }
5704         break;
5705       case 2:
5706         // The third argument to compare_exchange / GNU exchange is the desired
5707         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5708         if (IsPassedByAddress)
5709           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5710         Ty = ByValType;
5711         break;
5712       case 3:
5713         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5714         Ty = Context.BoolTy;
5715         break;
5716       }
5717     } else {
5718       // The order(s) and scope are always converted to int.
5719       Ty = Context.IntTy;
5720     }
5721 
5722     InitializedEntity Entity =
5723         InitializedEntity::InitializeParameter(Context, Ty, false);
5724     ExprResult Arg = APIOrderedArgs[i];
5725     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5726     if (Arg.isInvalid())
5727       return true;
5728     APIOrderedArgs[i] = Arg.get();
5729   }
5730 
5731   // Permute the arguments into a 'consistent' order.
5732   SmallVector<Expr*, 5> SubExprs;
5733   SubExprs.push_back(Ptr);
5734   switch (Form) {
5735   case Init:
5736     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5737     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5738     break;
5739   case Load:
5740     SubExprs.push_back(APIOrderedArgs[1]); // Order
5741     break;
5742   case LoadCopy:
5743   case Copy:
5744   case Arithmetic:
5745   case Xchg:
5746     SubExprs.push_back(APIOrderedArgs[2]); // Order
5747     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5748     break;
5749   case GNUXchg:
5750     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5751     SubExprs.push_back(APIOrderedArgs[3]); // Order
5752     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5753     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5754     break;
5755   case C11CmpXchg:
5756     SubExprs.push_back(APIOrderedArgs[3]); // Order
5757     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5758     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5759     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5760     break;
5761   case GNUCmpXchg:
5762     SubExprs.push_back(APIOrderedArgs[4]); // Order
5763     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5764     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5765     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5766     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5767     break;
5768   }
5769 
5770   if (SubExprs.size() >= 2 && Form != Init) {
5771     if (Optional<llvm::APSInt> Result =
5772             SubExprs[1]->getIntegerConstantExpr(Context))
5773       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5774         Diag(SubExprs[1]->getBeginLoc(),
5775              diag::warn_atomic_op_has_invalid_memory_order)
5776             << SubExprs[1]->getSourceRange();
5777   }
5778 
5779   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5780     auto *Scope = Args[Args.size() - 1];
5781     if (Optional<llvm::APSInt> Result =
5782             Scope->getIntegerConstantExpr(Context)) {
5783       if (!ScopeModel->isValid(Result->getZExtValue()))
5784         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5785             << Scope->getSourceRange();
5786     }
5787     SubExprs.push_back(Scope);
5788   }
5789 
5790   AtomicExpr *AE = new (Context)
5791       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5792 
5793   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5794        Op == AtomicExpr::AO__c11_atomic_store ||
5795        Op == AtomicExpr::AO__opencl_atomic_load ||
5796        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5797       Context.AtomicUsesUnsupportedLibcall(AE))
5798     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5799         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5800              Op == AtomicExpr::AO__opencl_atomic_load)
5801                 ? 0
5802                 : 1);
5803 
5804   if (ValType->isExtIntType()) {
5805     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5806     return ExprError();
5807   }
5808 
5809   return AE;
5810 }
5811 
5812 /// checkBuiltinArgument - Given a call to a builtin function, perform
5813 /// normal type-checking on the given argument, updating the call in
5814 /// place.  This is useful when a builtin function requires custom
5815 /// type-checking for some of its arguments but not necessarily all of
5816 /// them.
5817 ///
5818 /// Returns true on error.
5819 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5820   FunctionDecl *Fn = E->getDirectCallee();
5821   assert(Fn && "builtin call without direct callee!");
5822 
5823   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5824   InitializedEntity Entity =
5825     InitializedEntity::InitializeParameter(S.Context, Param);
5826 
5827   ExprResult Arg = E->getArg(0);
5828   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5829   if (Arg.isInvalid())
5830     return true;
5831 
5832   E->setArg(ArgIndex, Arg.get());
5833   return false;
5834 }
5835 
5836 /// We have a call to a function like __sync_fetch_and_add, which is an
5837 /// overloaded function based on the pointer type of its first argument.
5838 /// The main BuildCallExpr routines have already promoted the types of
5839 /// arguments because all of these calls are prototyped as void(...).
5840 ///
5841 /// This function goes through and does final semantic checking for these
5842 /// builtins, as well as generating any warnings.
5843 ExprResult
5844 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5845   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5846   Expr *Callee = TheCall->getCallee();
5847   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5848   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5849 
5850   // Ensure that we have at least one argument to do type inference from.
5851   if (TheCall->getNumArgs() < 1) {
5852     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5853         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5854     return ExprError();
5855   }
5856 
5857   // Inspect the first argument of the atomic builtin.  This should always be
5858   // a pointer type, whose element is an integral scalar or pointer type.
5859   // Because it is a pointer type, we don't have to worry about any implicit
5860   // casts here.
5861   // FIXME: We don't allow floating point scalars as input.
5862   Expr *FirstArg = TheCall->getArg(0);
5863   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5864   if (FirstArgResult.isInvalid())
5865     return ExprError();
5866   FirstArg = FirstArgResult.get();
5867   TheCall->setArg(0, FirstArg);
5868 
5869   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5870   if (!pointerType) {
5871     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5872         << FirstArg->getType() << FirstArg->getSourceRange();
5873     return ExprError();
5874   }
5875 
5876   QualType ValType = pointerType->getPointeeType();
5877   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5878       !ValType->isBlockPointerType()) {
5879     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5880         << FirstArg->getType() << FirstArg->getSourceRange();
5881     return ExprError();
5882   }
5883 
5884   if (ValType.isConstQualified()) {
5885     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5886         << FirstArg->getType() << FirstArg->getSourceRange();
5887     return ExprError();
5888   }
5889 
5890   switch (ValType.getObjCLifetime()) {
5891   case Qualifiers::OCL_None:
5892   case Qualifiers::OCL_ExplicitNone:
5893     // okay
5894     break;
5895 
5896   case Qualifiers::OCL_Weak:
5897   case Qualifiers::OCL_Strong:
5898   case Qualifiers::OCL_Autoreleasing:
5899     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5900         << ValType << FirstArg->getSourceRange();
5901     return ExprError();
5902   }
5903 
5904   // Strip any qualifiers off ValType.
5905   ValType = ValType.getUnqualifiedType();
5906 
5907   // The majority of builtins return a value, but a few have special return
5908   // types, so allow them to override appropriately below.
5909   QualType ResultType = ValType;
5910 
5911   // We need to figure out which concrete builtin this maps onto.  For example,
5912   // __sync_fetch_and_add with a 2 byte object turns into
5913   // __sync_fetch_and_add_2.
5914 #define BUILTIN_ROW(x) \
5915   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5916     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5917 
5918   static const unsigned BuiltinIndices[][5] = {
5919     BUILTIN_ROW(__sync_fetch_and_add),
5920     BUILTIN_ROW(__sync_fetch_and_sub),
5921     BUILTIN_ROW(__sync_fetch_and_or),
5922     BUILTIN_ROW(__sync_fetch_and_and),
5923     BUILTIN_ROW(__sync_fetch_and_xor),
5924     BUILTIN_ROW(__sync_fetch_and_nand),
5925 
5926     BUILTIN_ROW(__sync_add_and_fetch),
5927     BUILTIN_ROW(__sync_sub_and_fetch),
5928     BUILTIN_ROW(__sync_and_and_fetch),
5929     BUILTIN_ROW(__sync_or_and_fetch),
5930     BUILTIN_ROW(__sync_xor_and_fetch),
5931     BUILTIN_ROW(__sync_nand_and_fetch),
5932 
5933     BUILTIN_ROW(__sync_val_compare_and_swap),
5934     BUILTIN_ROW(__sync_bool_compare_and_swap),
5935     BUILTIN_ROW(__sync_lock_test_and_set),
5936     BUILTIN_ROW(__sync_lock_release),
5937     BUILTIN_ROW(__sync_swap)
5938   };
5939 #undef BUILTIN_ROW
5940 
5941   // Determine the index of the size.
5942   unsigned SizeIndex;
5943   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5944   case 1: SizeIndex = 0; break;
5945   case 2: SizeIndex = 1; break;
5946   case 4: SizeIndex = 2; break;
5947   case 8: SizeIndex = 3; break;
5948   case 16: SizeIndex = 4; break;
5949   default:
5950     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5951         << FirstArg->getType() << FirstArg->getSourceRange();
5952     return ExprError();
5953   }
5954 
5955   // Each of these builtins has one pointer argument, followed by some number of
5956   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5957   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5958   // as the number of fixed args.
5959   unsigned BuiltinID = FDecl->getBuiltinID();
5960   unsigned BuiltinIndex, NumFixed = 1;
5961   bool WarnAboutSemanticsChange = false;
5962   switch (BuiltinID) {
5963   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5964   case Builtin::BI__sync_fetch_and_add:
5965   case Builtin::BI__sync_fetch_and_add_1:
5966   case Builtin::BI__sync_fetch_and_add_2:
5967   case Builtin::BI__sync_fetch_and_add_4:
5968   case Builtin::BI__sync_fetch_and_add_8:
5969   case Builtin::BI__sync_fetch_and_add_16:
5970     BuiltinIndex = 0;
5971     break;
5972 
5973   case Builtin::BI__sync_fetch_and_sub:
5974   case Builtin::BI__sync_fetch_and_sub_1:
5975   case Builtin::BI__sync_fetch_and_sub_2:
5976   case Builtin::BI__sync_fetch_and_sub_4:
5977   case Builtin::BI__sync_fetch_and_sub_8:
5978   case Builtin::BI__sync_fetch_and_sub_16:
5979     BuiltinIndex = 1;
5980     break;
5981 
5982   case Builtin::BI__sync_fetch_and_or:
5983   case Builtin::BI__sync_fetch_and_or_1:
5984   case Builtin::BI__sync_fetch_and_or_2:
5985   case Builtin::BI__sync_fetch_and_or_4:
5986   case Builtin::BI__sync_fetch_and_or_8:
5987   case Builtin::BI__sync_fetch_and_or_16:
5988     BuiltinIndex = 2;
5989     break;
5990 
5991   case Builtin::BI__sync_fetch_and_and:
5992   case Builtin::BI__sync_fetch_and_and_1:
5993   case Builtin::BI__sync_fetch_and_and_2:
5994   case Builtin::BI__sync_fetch_and_and_4:
5995   case Builtin::BI__sync_fetch_and_and_8:
5996   case Builtin::BI__sync_fetch_and_and_16:
5997     BuiltinIndex = 3;
5998     break;
5999 
6000   case Builtin::BI__sync_fetch_and_xor:
6001   case Builtin::BI__sync_fetch_and_xor_1:
6002   case Builtin::BI__sync_fetch_and_xor_2:
6003   case Builtin::BI__sync_fetch_and_xor_4:
6004   case Builtin::BI__sync_fetch_and_xor_8:
6005   case Builtin::BI__sync_fetch_and_xor_16:
6006     BuiltinIndex = 4;
6007     break;
6008 
6009   case Builtin::BI__sync_fetch_and_nand:
6010   case Builtin::BI__sync_fetch_and_nand_1:
6011   case Builtin::BI__sync_fetch_and_nand_2:
6012   case Builtin::BI__sync_fetch_and_nand_4:
6013   case Builtin::BI__sync_fetch_and_nand_8:
6014   case Builtin::BI__sync_fetch_and_nand_16:
6015     BuiltinIndex = 5;
6016     WarnAboutSemanticsChange = true;
6017     break;
6018 
6019   case Builtin::BI__sync_add_and_fetch:
6020   case Builtin::BI__sync_add_and_fetch_1:
6021   case Builtin::BI__sync_add_and_fetch_2:
6022   case Builtin::BI__sync_add_and_fetch_4:
6023   case Builtin::BI__sync_add_and_fetch_8:
6024   case Builtin::BI__sync_add_and_fetch_16:
6025     BuiltinIndex = 6;
6026     break;
6027 
6028   case Builtin::BI__sync_sub_and_fetch:
6029   case Builtin::BI__sync_sub_and_fetch_1:
6030   case Builtin::BI__sync_sub_and_fetch_2:
6031   case Builtin::BI__sync_sub_and_fetch_4:
6032   case Builtin::BI__sync_sub_and_fetch_8:
6033   case Builtin::BI__sync_sub_and_fetch_16:
6034     BuiltinIndex = 7;
6035     break;
6036 
6037   case Builtin::BI__sync_and_and_fetch:
6038   case Builtin::BI__sync_and_and_fetch_1:
6039   case Builtin::BI__sync_and_and_fetch_2:
6040   case Builtin::BI__sync_and_and_fetch_4:
6041   case Builtin::BI__sync_and_and_fetch_8:
6042   case Builtin::BI__sync_and_and_fetch_16:
6043     BuiltinIndex = 8;
6044     break;
6045 
6046   case Builtin::BI__sync_or_and_fetch:
6047   case Builtin::BI__sync_or_and_fetch_1:
6048   case Builtin::BI__sync_or_and_fetch_2:
6049   case Builtin::BI__sync_or_and_fetch_4:
6050   case Builtin::BI__sync_or_and_fetch_8:
6051   case Builtin::BI__sync_or_and_fetch_16:
6052     BuiltinIndex = 9;
6053     break;
6054 
6055   case Builtin::BI__sync_xor_and_fetch:
6056   case Builtin::BI__sync_xor_and_fetch_1:
6057   case Builtin::BI__sync_xor_and_fetch_2:
6058   case Builtin::BI__sync_xor_and_fetch_4:
6059   case Builtin::BI__sync_xor_and_fetch_8:
6060   case Builtin::BI__sync_xor_and_fetch_16:
6061     BuiltinIndex = 10;
6062     break;
6063 
6064   case Builtin::BI__sync_nand_and_fetch:
6065   case Builtin::BI__sync_nand_and_fetch_1:
6066   case Builtin::BI__sync_nand_and_fetch_2:
6067   case Builtin::BI__sync_nand_and_fetch_4:
6068   case Builtin::BI__sync_nand_and_fetch_8:
6069   case Builtin::BI__sync_nand_and_fetch_16:
6070     BuiltinIndex = 11;
6071     WarnAboutSemanticsChange = true;
6072     break;
6073 
6074   case Builtin::BI__sync_val_compare_and_swap:
6075   case Builtin::BI__sync_val_compare_and_swap_1:
6076   case Builtin::BI__sync_val_compare_and_swap_2:
6077   case Builtin::BI__sync_val_compare_and_swap_4:
6078   case Builtin::BI__sync_val_compare_and_swap_8:
6079   case Builtin::BI__sync_val_compare_and_swap_16:
6080     BuiltinIndex = 12;
6081     NumFixed = 2;
6082     break;
6083 
6084   case Builtin::BI__sync_bool_compare_and_swap:
6085   case Builtin::BI__sync_bool_compare_and_swap_1:
6086   case Builtin::BI__sync_bool_compare_and_swap_2:
6087   case Builtin::BI__sync_bool_compare_and_swap_4:
6088   case Builtin::BI__sync_bool_compare_and_swap_8:
6089   case Builtin::BI__sync_bool_compare_and_swap_16:
6090     BuiltinIndex = 13;
6091     NumFixed = 2;
6092     ResultType = Context.BoolTy;
6093     break;
6094 
6095   case Builtin::BI__sync_lock_test_and_set:
6096   case Builtin::BI__sync_lock_test_and_set_1:
6097   case Builtin::BI__sync_lock_test_and_set_2:
6098   case Builtin::BI__sync_lock_test_and_set_4:
6099   case Builtin::BI__sync_lock_test_and_set_8:
6100   case Builtin::BI__sync_lock_test_and_set_16:
6101     BuiltinIndex = 14;
6102     break;
6103 
6104   case Builtin::BI__sync_lock_release:
6105   case Builtin::BI__sync_lock_release_1:
6106   case Builtin::BI__sync_lock_release_2:
6107   case Builtin::BI__sync_lock_release_4:
6108   case Builtin::BI__sync_lock_release_8:
6109   case Builtin::BI__sync_lock_release_16:
6110     BuiltinIndex = 15;
6111     NumFixed = 0;
6112     ResultType = Context.VoidTy;
6113     break;
6114 
6115   case Builtin::BI__sync_swap:
6116   case Builtin::BI__sync_swap_1:
6117   case Builtin::BI__sync_swap_2:
6118   case Builtin::BI__sync_swap_4:
6119   case Builtin::BI__sync_swap_8:
6120   case Builtin::BI__sync_swap_16:
6121     BuiltinIndex = 16;
6122     break;
6123   }
6124 
6125   // Now that we know how many fixed arguments we expect, first check that we
6126   // have at least that many.
6127   if (TheCall->getNumArgs() < 1+NumFixed) {
6128     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6129         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6130         << Callee->getSourceRange();
6131     return ExprError();
6132   }
6133 
6134   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6135       << Callee->getSourceRange();
6136 
6137   if (WarnAboutSemanticsChange) {
6138     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6139         << Callee->getSourceRange();
6140   }
6141 
6142   // Get the decl for the concrete builtin from this, we can tell what the
6143   // concrete integer type we should convert to is.
6144   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6145   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6146   FunctionDecl *NewBuiltinDecl;
6147   if (NewBuiltinID == BuiltinID)
6148     NewBuiltinDecl = FDecl;
6149   else {
6150     // Perform builtin lookup to avoid redeclaring it.
6151     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6152     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6153     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6154     assert(Res.getFoundDecl());
6155     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6156     if (!NewBuiltinDecl)
6157       return ExprError();
6158   }
6159 
6160   // The first argument --- the pointer --- has a fixed type; we
6161   // deduce the types of the rest of the arguments accordingly.  Walk
6162   // the remaining arguments, converting them to the deduced value type.
6163   for (unsigned i = 0; i != NumFixed; ++i) {
6164     ExprResult Arg = TheCall->getArg(i+1);
6165 
6166     // GCC does an implicit conversion to the pointer or integer ValType.  This
6167     // can fail in some cases (1i -> int**), check for this error case now.
6168     // Initialize the argument.
6169     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6170                                                    ValType, /*consume*/ false);
6171     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6172     if (Arg.isInvalid())
6173       return ExprError();
6174 
6175     // Okay, we have something that *can* be converted to the right type.  Check
6176     // to see if there is a potentially weird extension going on here.  This can
6177     // happen when you do an atomic operation on something like an char* and
6178     // pass in 42.  The 42 gets converted to char.  This is even more strange
6179     // for things like 45.123 -> char, etc.
6180     // FIXME: Do this check.
6181     TheCall->setArg(i+1, Arg.get());
6182   }
6183 
6184   // Create a new DeclRefExpr to refer to the new decl.
6185   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6186       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6187       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6188       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6189 
6190   // Set the callee in the CallExpr.
6191   // FIXME: This loses syntactic information.
6192   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6193   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6194                                               CK_BuiltinFnToFnPtr);
6195   TheCall->setCallee(PromotedCall.get());
6196 
6197   // Change the result type of the call to match the original value type. This
6198   // is arbitrary, but the codegen for these builtins ins design to handle it
6199   // gracefully.
6200   TheCall->setType(ResultType);
6201 
6202   // Prohibit use of _ExtInt with atomic builtins.
6203   // The arguments would have already been converted to the first argument's
6204   // type, so only need to check the first argument.
6205   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6206   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6207     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6208     return ExprError();
6209   }
6210 
6211   return TheCallResult;
6212 }
6213 
6214 /// SemaBuiltinNontemporalOverloaded - We have a call to
6215 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6216 /// overloaded function based on the pointer type of its last argument.
6217 ///
6218 /// This function goes through and does final semantic checking for these
6219 /// builtins.
6220 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6221   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6222   DeclRefExpr *DRE =
6223       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6224   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6225   unsigned BuiltinID = FDecl->getBuiltinID();
6226   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6227           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6228          "Unexpected nontemporal load/store builtin!");
6229   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6230   unsigned numArgs = isStore ? 2 : 1;
6231 
6232   // Ensure that we have the proper number of arguments.
6233   if (checkArgCount(*this, TheCall, numArgs))
6234     return ExprError();
6235 
6236   // Inspect the last argument of the nontemporal builtin.  This should always
6237   // be a pointer type, from which we imply the type of the memory access.
6238   // Because it is a pointer type, we don't have to worry about any implicit
6239   // casts here.
6240   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6241   ExprResult PointerArgResult =
6242       DefaultFunctionArrayLvalueConversion(PointerArg);
6243 
6244   if (PointerArgResult.isInvalid())
6245     return ExprError();
6246   PointerArg = PointerArgResult.get();
6247   TheCall->setArg(numArgs - 1, PointerArg);
6248 
6249   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6250   if (!pointerType) {
6251     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6252         << PointerArg->getType() << PointerArg->getSourceRange();
6253     return ExprError();
6254   }
6255 
6256   QualType ValType = pointerType->getPointeeType();
6257 
6258   // Strip any qualifiers off ValType.
6259   ValType = ValType.getUnqualifiedType();
6260   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6261       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6262       !ValType->isVectorType()) {
6263     Diag(DRE->getBeginLoc(),
6264          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6265         << PointerArg->getType() << PointerArg->getSourceRange();
6266     return ExprError();
6267   }
6268 
6269   if (!isStore) {
6270     TheCall->setType(ValType);
6271     return TheCallResult;
6272   }
6273 
6274   ExprResult ValArg = TheCall->getArg(0);
6275   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6276       Context, ValType, /*consume*/ false);
6277   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6278   if (ValArg.isInvalid())
6279     return ExprError();
6280 
6281   TheCall->setArg(0, ValArg.get());
6282   TheCall->setType(Context.VoidTy);
6283   return TheCallResult;
6284 }
6285 
6286 /// CheckObjCString - Checks that the argument to the builtin
6287 /// CFString constructor is correct
6288 /// Note: It might also make sense to do the UTF-16 conversion here (would
6289 /// simplify the backend).
6290 bool Sema::CheckObjCString(Expr *Arg) {
6291   Arg = Arg->IgnoreParenCasts();
6292   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6293 
6294   if (!Literal || !Literal->isAscii()) {
6295     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6296         << Arg->getSourceRange();
6297     return true;
6298   }
6299 
6300   if (Literal->containsNonAsciiOrNull()) {
6301     StringRef String = Literal->getString();
6302     unsigned NumBytes = String.size();
6303     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6304     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6305     llvm::UTF16 *ToPtr = &ToBuf[0];
6306 
6307     llvm::ConversionResult Result =
6308         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6309                                  ToPtr + NumBytes, llvm::strictConversion);
6310     // Check for conversion failure.
6311     if (Result != llvm::conversionOK)
6312       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6313           << Arg->getSourceRange();
6314   }
6315   return false;
6316 }
6317 
6318 /// CheckObjCString - Checks that the format string argument to the os_log()
6319 /// and os_trace() functions is correct, and converts it to const char *.
6320 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6321   Arg = Arg->IgnoreParenCasts();
6322   auto *Literal = dyn_cast<StringLiteral>(Arg);
6323   if (!Literal) {
6324     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6325       Literal = ObjcLiteral->getString();
6326     }
6327   }
6328 
6329   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6330     return ExprError(
6331         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6332         << Arg->getSourceRange());
6333   }
6334 
6335   ExprResult Result(Literal);
6336   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6337   InitializedEntity Entity =
6338       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6339   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6340   return Result;
6341 }
6342 
6343 /// Check that the user is calling the appropriate va_start builtin for the
6344 /// target and calling convention.
6345 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6346   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6347   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6348   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6349                     TT.getArch() == llvm::Triple::aarch64_32);
6350   bool IsWindows = TT.isOSWindows();
6351   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6352   if (IsX64 || IsAArch64) {
6353     CallingConv CC = CC_C;
6354     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6355       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6356     if (IsMSVAStart) {
6357       // Don't allow this in System V ABI functions.
6358       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6359         return S.Diag(Fn->getBeginLoc(),
6360                       diag::err_ms_va_start_used_in_sysv_function);
6361     } else {
6362       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6363       // On x64 Windows, don't allow this in System V ABI functions.
6364       // (Yes, that means there's no corresponding way to support variadic
6365       // System V ABI functions on Windows.)
6366       if ((IsWindows && CC == CC_X86_64SysV) ||
6367           (!IsWindows && CC == CC_Win64))
6368         return S.Diag(Fn->getBeginLoc(),
6369                       diag::err_va_start_used_in_wrong_abi_function)
6370                << !IsWindows;
6371     }
6372     return false;
6373   }
6374 
6375   if (IsMSVAStart)
6376     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6377   return false;
6378 }
6379 
6380 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6381                                              ParmVarDecl **LastParam = nullptr) {
6382   // Determine whether the current function, block, or obj-c method is variadic
6383   // and get its parameter list.
6384   bool IsVariadic = false;
6385   ArrayRef<ParmVarDecl *> Params;
6386   DeclContext *Caller = S.CurContext;
6387   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6388     IsVariadic = Block->isVariadic();
6389     Params = Block->parameters();
6390   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6391     IsVariadic = FD->isVariadic();
6392     Params = FD->parameters();
6393   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6394     IsVariadic = MD->isVariadic();
6395     // FIXME: This isn't correct for methods (results in bogus warning).
6396     Params = MD->parameters();
6397   } else if (isa<CapturedDecl>(Caller)) {
6398     // We don't support va_start in a CapturedDecl.
6399     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6400     return true;
6401   } else {
6402     // This must be some other declcontext that parses exprs.
6403     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6404     return true;
6405   }
6406 
6407   if (!IsVariadic) {
6408     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6409     return true;
6410   }
6411 
6412   if (LastParam)
6413     *LastParam = Params.empty() ? nullptr : Params.back();
6414 
6415   return false;
6416 }
6417 
6418 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6419 /// for validity.  Emit an error and return true on failure; return false
6420 /// on success.
6421 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6422   Expr *Fn = TheCall->getCallee();
6423 
6424   if (checkVAStartABI(*this, BuiltinID, Fn))
6425     return true;
6426 
6427   if (checkArgCount(*this, TheCall, 2))
6428     return true;
6429 
6430   // Type-check the first argument normally.
6431   if (checkBuiltinArgument(*this, TheCall, 0))
6432     return true;
6433 
6434   // Check that the current function is variadic, and get its last parameter.
6435   ParmVarDecl *LastParam;
6436   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6437     return true;
6438 
6439   // Verify that the second argument to the builtin is the last argument of the
6440   // current function or method.
6441   bool SecondArgIsLastNamedArgument = false;
6442   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6443 
6444   // These are valid if SecondArgIsLastNamedArgument is false after the next
6445   // block.
6446   QualType Type;
6447   SourceLocation ParamLoc;
6448   bool IsCRegister = false;
6449 
6450   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6451     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6452       SecondArgIsLastNamedArgument = PV == LastParam;
6453 
6454       Type = PV->getType();
6455       ParamLoc = PV->getLocation();
6456       IsCRegister =
6457           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6458     }
6459   }
6460 
6461   if (!SecondArgIsLastNamedArgument)
6462     Diag(TheCall->getArg(1)->getBeginLoc(),
6463          diag::warn_second_arg_of_va_start_not_last_named_param);
6464   else if (IsCRegister || Type->isReferenceType() ||
6465            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6466              // Promotable integers are UB, but enumerations need a bit of
6467              // extra checking to see what their promotable type actually is.
6468              if (!Type->isPromotableIntegerType())
6469                return false;
6470              if (!Type->isEnumeralType())
6471                return true;
6472              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6473              return !(ED &&
6474                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6475            }()) {
6476     unsigned Reason = 0;
6477     if (Type->isReferenceType())  Reason = 1;
6478     else if (IsCRegister)         Reason = 2;
6479     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6480     Diag(ParamLoc, diag::note_parameter_type) << Type;
6481   }
6482 
6483   TheCall->setType(Context.VoidTy);
6484   return false;
6485 }
6486 
6487 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6488   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6489     const LangOptions &LO = getLangOpts();
6490 
6491     if (LO.CPlusPlus)
6492       return Arg->getType()
6493                  .getCanonicalType()
6494                  .getTypePtr()
6495                  ->getPointeeType()
6496                  .withoutLocalFastQualifiers() == Context.CharTy;
6497 
6498     // In C, allow aliasing through `char *`, this is required for AArch64 at
6499     // least.
6500     return true;
6501   };
6502 
6503   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6504   //                 const char *named_addr);
6505 
6506   Expr *Func = Call->getCallee();
6507 
6508   if (Call->getNumArgs() < 3)
6509     return Diag(Call->getEndLoc(),
6510                 diag::err_typecheck_call_too_few_args_at_least)
6511            << 0 /*function call*/ << 3 << Call->getNumArgs();
6512 
6513   // Type-check the first argument normally.
6514   if (checkBuiltinArgument(*this, Call, 0))
6515     return true;
6516 
6517   // Check that the current function is variadic.
6518   if (checkVAStartIsInVariadicFunction(*this, Func))
6519     return true;
6520 
6521   // __va_start on Windows does not validate the parameter qualifiers
6522 
6523   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6524   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6525 
6526   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6527   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6528 
6529   const QualType &ConstCharPtrTy =
6530       Context.getPointerType(Context.CharTy.withConst());
6531   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6532     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6533         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6534         << 0                                      /* qualifier difference */
6535         << 3                                      /* parameter mismatch */
6536         << 2 << Arg1->getType() << ConstCharPtrTy;
6537 
6538   const QualType SizeTy = Context.getSizeType();
6539   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6540     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6541         << Arg2->getType() << SizeTy << 1 /* different class */
6542         << 0                              /* qualifier difference */
6543         << 3                              /* parameter mismatch */
6544         << 3 << Arg2->getType() << SizeTy;
6545 
6546   return false;
6547 }
6548 
6549 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6550 /// friends.  This is declared to take (...), so we have to check everything.
6551 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6552   if (checkArgCount(*this, TheCall, 2))
6553     return true;
6554 
6555   ExprResult OrigArg0 = TheCall->getArg(0);
6556   ExprResult OrigArg1 = TheCall->getArg(1);
6557 
6558   // Do standard promotions between the two arguments, returning their common
6559   // type.
6560   QualType Res = UsualArithmeticConversions(
6561       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6562   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6563     return true;
6564 
6565   // Make sure any conversions are pushed back into the call; this is
6566   // type safe since unordered compare builtins are declared as "_Bool
6567   // foo(...)".
6568   TheCall->setArg(0, OrigArg0.get());
6569   TheCall->setArg(1, OrigArg1.get());
6570 
6571   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6572     return false;
6573 
6574   // If the common type isn't a real floating type, then the arguments were
6575   // invalid for this operation.
6576   if (Res.isNull() || !Res->isRealFloatingType())
6577     return Diag(OrigArg0.get()->getBeginLoc(),
6578                 diag::err_typecheck_call_invalid_ordered_compare)
6579            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6580            << SourceRange(OrigArg0.get()->getBeginLoc(),
6581                           OrigArg1.get()->getEndLoc());
6582 
6583   return false;
6584 }
6585 
6586 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6587 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6588 /// to check everything. We expect the last argument to be a floating point
6589 /// value.
6590 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6591   if (checkArgCount(*this, TheCall, NumArgs))
6592     return true;
6593 
6594   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6595   // on all preceding parameters just being int.  Try all of those.
6596   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6597     Expr *Arg = TheCall->getArg(i);
6598 
6599     if (Arg->isTypeDependent())
6600       return false;
6601 
6602     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6603 
6604     if (Res.isInvalid())
6605       return true;
6606     TheCall->setArg(i, Res.get());
6607   }
6608 
6609   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6610 
6611   if (OrigArg->isTypeDependent())
6612     return false;
6613 
6614   // Usual Unary Conversions will convert half to float, which we want for
6615   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6616   // type how it is, but do normal L->Rvalue conversions.
6617   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6618     OrigArg = UsualUnaryConversions(OrigArg).get();
6619   else
6620     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6621   TheCall->setArg(NumArgs - 1, OrigArg);
6622 
6623   // This operation requires a non-_Complex floating-point number.
6624   if (!OrigArg->getType()->isRealFloatingType())
6625     return Diag(OrigArg->getBeginLoc(),
6626                 diag::err_typecheck_call_invalid_unary_fp)
6627            << OrigArg->getType() << OrigArg->getSourceRange();
6628 
6629   return false;
6630 }
6631 
6632 /// Perform semantic analysis for a call to __builtin_complex.
6633 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6634   if (checkArgCount(*this, TheCall, 2))
6635     return true;
6636 
6637   bool Dependent = false;
6638   for (unsigned I = 0; I != 2; ++I) {
6639     Expr *Arg = TheCall->getArg(I);
6640     QualType T = Arg->getType();
6641     if (T->isDependentType()) {
6642       Dependent = true;
6643       continue;
6644     }
6645 
6646     // Despite supporting _Complex int, GCC requires a real floating point type
6647     // for the operands of __builtin_complex.
6648     if (!T->isRealFloatingType()) {
6649       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6650              << Arg->getType() << Arg->getSourceRange();
6651     }
6652 
6653     ExprResult Converted = DefaultLvalueConversion(Arg);
6654     if (Converted.isInvalid())
6655       return true;
6656     TheCall->setArg(I, Converted.get());
6657   }
6658 
6659   if (Dependent) {
6660     TheCall->setType(Context.DependentTy);
6661     return false;
6662   }
6663 
6664   Expr *Real = TheCall->getArg(0);
6665   Expr *Imag = TheCall->getArg(1);
6666   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6667     return Diag(Real->getBeginLoc(),
6668                 diag::err_typecheck_call_different_arg_types)
6669            << Real->getType() << Imag->getType()
6670            << Real->getSourceRange() << Imag->getSourceRange();
6671   }
6672 
6673   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6674   // don't allow this builtin to form those types either.
6675   // FIXME: Should we allow these types?
6676   if (Real->getType()->isFloat16Type())
6677     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6678            << "_Float16";
6679   if (Real->getType()->isHalfType())
6680     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6681            << "half";
6682 
6683   TheCall->setType(Context.getComplexType(Real->getType()));
6684   return false;
6685 }
6686 
6687 // Customized Sema Checking for VSX builtins that have the following signature:
6688 // vector [...] builtinName(vector [...], vector [...], const int);
6689 // Which takes the same type of vectors (any legal vector type) for the first
6690 // two arguments and takes compile time constant for the third argument.
6691 // Example builtins are :
6692 // vector double vec_xxpermdi(vector double, vector double, int);
6693 // vector short vec_xxsldwi(vector short, vector short, int);
6694 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6695   unsigned ExpectedNumArgs = 3;
6696   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6697     return true;
6698 
6699   // Check the third argument is a compile time constant
6700   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6701     return Diag(TheCall->getBeginLoc(),
6702                 diag::err_vsx_builtin_nonconstant_argument)
6703            << 3 /* argument index */ << TheCall->getDirectCallee()
6704            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6705                           TheCall->getArg(2)->getEndLoc());
6706 
6707   QualType Arg1Ty = TheCall->getArg(0)->getType();
6708   QualType Arg2Ty = TheCall->getArg(1)->getType();
6709 
6710   // Check the type of argument 1 and argument 2 are vectors.
6711   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6712   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6713       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6714     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6715            << TheCall->getDirectCallee()
6716            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6717                           TheCall->getArg(1)->getEndLoc());
6718   }
6719 
6720   // Check the first two arguments are the same type.
6721   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6722     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6723            << TheCall->getDirectCallee()
6724            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6725                           TheCall->getArg(1)->getEndLoc());
6726   }
6727 
6728   // When default clang type checking is turned off and the customized type
6729   // checking is used, the returning type of the function must be explicitly
6730   // set. Otherwise it is _Bool by default.
6731   TheCall->setType(Arg1Ty);
6732 
6733   return false;
6734 }
6735 
6736 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6737 // This is declared to take (...), so we have to check everything.
6738 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6739   if (TheCall->getNumArgs() < 2)
6740     return ExprError(Diag(TheCall->getEndLoc(),
6741                           diag::err_typecheck_call_too_few_args_at_least)
6742                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6743                      << TheCall->getSourceRange());
6744 
6745   // Determine which of the following types of shufflevector we're checking:
6746   // 1) unary, vector mask: (lhs, mask)
6747   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6748   QualType resType = TheCall->getArg(0)->getType();
6749   unsigned numElements = 0;
6750 
6751   if (!TheCall->getArg(0)->isTypeDependent() &&
6752       !TheCall->getArg(1)->isTypeDependent()) {
6753     QualType LHSType = TheCall->getArg(0)->getType();
6754     QualType RHSType = TheCall->getArg(1)->getType();
6755 
6756     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6757       return ExprError(
6758           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6759           << TheCall->getDirectCallee()
6760           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6761                          TheCall->getArg(1)->getEndLoc()));
6762 
6763     numElements = LHSType->castAs<VectorType>()->getNumElements();
6764     unsigned numResElements = TheCall->getNumArgs() - 2;
6765 
6766     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6767     // with mask.  If so, verify that RHS is an integer vector type with the
6768     // same number of elts as lhs.
6769     if (TheCall->getNumArgs() == 2) {
6770       if (!RHSType->hasIntegerRepresentation() ||
6771           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6772         return ExprError(Diag(TheCall->getBeginLoc(),
6773                               diag::err_vec_builtin_incompatible_vector)
6774                          << TheCall->getDirectCallee()
6775                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6776                                         TheCall->getArg(1)->getEndLoc()));
6777     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6778       return ExprError(Diag(TheCall->getBeginLoc(),
6779                             diag::err_vec_builtin_incompatible_vector)
6780                        << TheCall->getDirectCallee()
6781                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6782                                       TheCall->getArg(1)->getEndLoc()));
6783     } else if (numElements != numResElements) {
6784       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6785       resType = Context.getVectorType(eltType, numResElements,
6786                                       VectorType::GenericVector);
6787     }
6788   }
6789 
6790   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6791     if (TheCall->getArg(i)->isTypeDependent() ||
6792         TheCall->getArg(i)->isValueDependent())
6793       continue;
6794 
6795     Optional<llvm::APSInt> Result;
6796     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6797       return ExprError(Diag(TheCall->getBeginLoc(),
6798                             diag::err_shufflevector_nonconstant_argument)
6799                        << TheCall->getArg(i)->getSourceRange());
6800 
6801     // Allow -1 which will be translated to undef in the IR.
6802     if (Result->isSigned() && Result->isAllOnes())
6803       continue;
6804 
6805     if (Result->getActiveBits() > 64 ||
6806         Result->getZExtValue() >= numElements * 2)
6807       return ExprError(Diag(TheCall->getBeginLoc(),
6808                             diag::err_shufflevector_argument_too_large)
6809                        << TheCall->getArg(i)->getSourceRange());
6810   }
6811 
6812   SmallVector<Expr*, 32> exprs;
6813 
6814   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6815     exprs.push_back(TheCall->getArg(i));
6816     TheCall->setArg(i, nullptr);
6817   }
6818 
6819   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6820                                          TheCall->getCallee()->getBeginLoc(),
6821                                          TheCall->getRParenLoc());
6822 }
6823 
6824 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6825 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6826                                        SourceLocation BuiltinLoc,
6827                                        SourceLocation RParenLoc) {
6828   ExprValueKind VK = VK_PRValue;
6829   ExprObjectKind OK = OK_Ordinary;
6830   QualType DstTy = TInfo->getType();
6831   QualType SrcTy = E->getType();
6832 
6833   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6834     return ExprError(Diag(BuiltinLoc,
6835                           diag::err_convertvector_non_vector)
6836                      << E->getSourceRange());
6837   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6838     return ExprError(Diag(BuiltinLoc,
6839                           diag::err_convertvector_non_vector_type));
6840 
6841   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6842     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6843     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6844     if (SrcElts != DstElts)
6845       return ExprError(Diag(BuiltinLoc,
6846                             diag::err_convertvector_incompatible_vector)
6847                        << E->getSourceRange());
6848   }
6849 
6850   return new (Context)
6851       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6852 }
6853 
6854 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6855 // This is declared to take (const void*, ...) and can take two
6856 // optional constant int args.
6857 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6858   unsigned NumArgs = TheCall->getNumArgs();
6859 
6860   if (NumArgs > 3)
6861     return Diag(TheCall->getEndLoc(),
6862                 diag::err_typecheck_call_too_many_args_at_most)
6863            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6864 
6865   // Argument 0 is checked for us and the remaining arguments must be
6866   // constant integers.
6867   for (unsigned i = 1; i != NumArgs; ++i)
6868     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6869       return true;
6870 
6871   return false;
6872 }
6873 
6874 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6875 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6876   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6877     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6878            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6879   if (checkArgCount(*this, TheCall, 1))
6880     return true;
6881   Expr *Arg = TheCall->getArg(0);
6882   if (Arg->isInstantiationDependent())
6883     return false;
6884 
6885   QualType ArgTy = Arg->getType();
6886   if (!ArgTy->hasFloatingRepresentation())
6887     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6888            << ArgTy;
6889   if (Arg->isLValue()) {
6890     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6891     TheCall->setArg(0, FirstArg.get());
6892   }
6893   TheCall->setType(TheCall->getArg(0)->getType());
6894   return false;
6895 }
6896 
6897 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6898 // __assume does not evaluate its arguments, and should warn if its argument
6899 // has side effects.
6900 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6901   Expr *Arg = TheCall->getArg(0);
6902   if (Arg->isInstantiationDependent()) return false;
6903 
6904   if (Arg->HasSideEffects(Context))
6905     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6906         << Arg->getSourceRange()
6907         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6908 
6909   return false;
6910 }
6911 
6912 /// Handle __builtin_alloca_with_align. This is declared
6913 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6914 /// than 8.
6915 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6916   // The alignment must be a constant integer.
6917   Expr *Arg = TheCall->getArg(1);
6918 
6919   // We can't check the value of a dependent argument.
6920   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6921     if (const auto *UE =
6922             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6923       if (UE->getKind() == UETT_AlignOf ||
6924           UE->getKind() == UETT_PreferredAlignOf)
6925         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6926             << Arg->getSourceRange();
6927 
6928     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6929 
6930     if (!Result.isPowerOf2())
6931       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6932              << Arg->getSourceRange();
6933 
6934     if (Result < Context.getCharWidth())
6935       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6936              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6937 
6938     if (Result > std::numeric_limits<int32_t>::max())
6939       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6940              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6941   }
6942 
6943   return false;
6944 }
6945 
6946 /// Handle __builtin_assume_aligned. This is declared
6947 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6948 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6949   unsigned NumArgs = TheCall->getNumArgs();
6950 
6951   if (NumArgs > 3)
6952     return Diag(TheCall->getEndLoc(),
6953                 diag::err_typecheck_call_too_many_args_at_most)
6954            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6955 
6956   // The alignment must be a constant integer.
6957   Expr *Arg = TheCall->getArg(1);
6958 
6959   // We can't check the value of a dependent argument.
6960   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6961     llvm::APSInt Result;
6962     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6963       return true;
6964 
6965     if (!Result.isPowerOf2())
6966       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6967              << Arg->getSourceRange();
6968 
6969     if (Result > Sema::MaximumAlignment)
6970       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6971           << Arg->getSourceRange() << Sema::MaximumAlignment;
6972   }
6973 
6974   if (NumArgs > 2) {
6975     ExprResult Arg(TheCall->getArg(2));
6976     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6977       Context.getSizeType(), false);
6978     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6979     if (Arg.isInvalid()) return true;
6980     TheCall->setArg(2, Arg.get());
6981   }
6982 
6983   return false;
6984 }
6985 
6986 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6987   unsigned BuiltinID =
6988       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6989   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6990 
6991   unsigned NumArgs = TheCall->getNumArgs();
6992   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6993   if (NumArgs < NumRequiredArgs) {
6994     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6995            << 0 /* function call */ << NumRequiredArgs << NumArgs
6996            << TheCall->getSourceRange();
6997   }
6998   if (NumArgs >= NumRequiredArgs + 0x100) {
6999     return Diag(TheCall->getEndLoc(),
7000                 diag::err_typecheck_call_too_many_args_at_most)
7001            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
7002            << TheCall->getSourceRange();
7003   }
7004   unsigned i = 0;
7005 
7006   // For formatting call, check buffer arg.
7007   if (!IsSizeCall) {
7008     ExprResult Arg(TheCall->getArg(i));
7009     InitializedEntity Entity = InitializedEntity::InitializeParameter(
7010         Context, Context.VoidPtrTy, false);
7011     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
7012     if (Arg.isInvalid())
7013       return true;
7014     TheCall->setArg(i, Arg.get());
7015     i++;
7016   }
7017 
7018   // Check string literal arg.
7019   unsigned FormatIdx = i;
7020   {
7021     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
7022     if (Arg.isInvalid())
7023       return true;
7024     TheCall->setArg(i, Arg.get());
7025     i++;
7026   }
7027 
7028   // Make sure variadic args are scalar.
7029   unsigned FirstDataArg = i;
7030   while (i < NumArgs) {
7031     ExprResult Arg = DefaultVariadicArgumentPromotion(
7032         TheCall->getArg(i), VariadicFunction, nullptr);
7033     if (Arg.isInvalid())
7034       return true;
7035     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
7036     if (ArgSize.getQuantity() >= 0x100) {
7037       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
7038              << i << (int)ArgSize.getQuantity() << 0xff
7039              << TheCall->getSourceRange();
7040     }
7041     TheCall->setArg(i, Arg.get());
7042     i++;
7043   }
7044 
7045   // Check formatting specifiers. NOTE: We're only doing this for the non-size
7046   // call to avoid duplicate diagnostics.
7047   if (!IsSizeCall) {
7048     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
7049     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
7050     bool Success = CheckFormatArguments(
7051         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
7052         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
7053         CheckedVarArgs);
7054     if (!Success)
7055       return true;
7056   }
7057 
7058   if (IsSizeCall) {
7059     TheCall->setType(Context.getSizeType());
7060   } else {
7061     TheCall->setType(Context.VoidPtrTy);
7062   }
7063   return false;
7064 }
7065 
7066 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7067 /// TheCall is a constant expression.
7068 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7069                                   llvm::APSInt &Result) {
7070   Expr *Arg = TheCall->getArg(ArgNum);
7071   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7072   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7073 
7074   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7075 
7076   Optional<llvm::APSInt> R;
7077   if (!(R = Arg->getIntegerConstantExpr(Context)))
7078     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7079            << FDecl->getDeclName() << Arg->getSourceRange();
7080   Result = *R;
7081   return false;
7082 }
7083 
7084 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7085 /// TheCall is a constant expression in the range [Low, High].
7086 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7087                                        int Low, int High, bool RangeIsError) {
7088   if (isConstantEvaluated())
7089     return false;
7090   llvm::APSInt Result;
7091 
7092   // We can't check the value of a dependent argument.
7093   Expr *Arg = TheCall->getArg(ArgNum);
7094   if (Arg->isTypeDependent() || Arg->isValueDependent())
7095     return false;
7096 
7097   // Check constant-ness first.
7098   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7099     return true;
7100 
7101   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7102     if (RangeIsError)
7103       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7104              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7105     else
7106       // Defer the warning until we know if the code will be emitted so that
7107       // dead code can ignore this.
7108       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7109                           PDiag(diag::warn_argument_invalid_range)
7110                               << toString(Result, 10) << Low << High
7111                               << Arg->getSourceRange());
7112   }
7113 
7114   return false;
7115 }
7116 
7117 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7118 /// TheCall is a constant expression is a multiple of Num..
7119 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7120                                           unsigned Num) {
7121   llvm::APSInt Result;
7122 
7123   // We can't check the value of a dependent argument.
7124   Expr *Arg = TheCall->getArg(ArgNum);
7125   if (Arg->isTypeDependent() || Arg->isValueDependent())
7126     return false;
7127 
7128   // Check constant-ness first.
7129   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7130     return true;
7131 
7132   if (Result.getSExtValue() % Num != 0)
7133     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7134            << Num << Arg->getSourceRange();
7135 
7136   return false;
7137 }
7138 
7139 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7140 /// constant expression representing a power of 2.
7141 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7142   llvm::APSInt Result;
7143 
7144   // We can't check the value of a dependent argument.
7145   Expr *Arg = TheCall->getArg(ArgNum);
7146   if (Arg->isTypeDependent() || Arg->isValueDependent())
7147     return false;
7148 
7149   // Check constant-ness first.
7150   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7151     return true;
7152 
7153   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7154   // and only if x is a power of 2.
7155   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7156     return false;
7157 
7158   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7159          << Arg->getSourceRange();
7160 }
7161 
7162 static bool IsShiftedByte(llvm::APSInt Value) {
7163   if (Value.isNegative())
7164     return false;
7165 
7166   // Check if it's a shifted byte, by shifting it down
7167   while (true) {
7168     // If the value fits in the bottom byte, the check passes.
7169     if (Value < 0x100)
7170       return true;
7171 
7172     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7173     // fails.
7174     if ((Value & 0xFF) != 0)
7175       return false;
7176 
7177     // If the bottom 8 bits are all 0, but something above that is nonzero,
7178     // then shifting the value right by 8 bits won't affect whether it's a
7179     // shifted byte or not. So do that, and go round again.
7180     Value >>= 8;
7181   }
7182 }
7183 
7184 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7185 /// a constant expression representing an arbitrary byte value shifted left by
7186 /// a multiple of 8 bits.
7187 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7188                                              unsigned ArgBits) {
7189   llvm::APSInt Result;
7190 
7191   // We can't check the value of a dependent argument.
7192   Expr *Arg = TheCall->getArg(ArgNum);
7193   if (Arg->isTypeDependent() || Arg->isValueDependent())
7194     return false;
7195 
7196   // Check constant-ness first.
7197   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7198     return true;
7199 
7200   // Truncate to the given size.
7201   Result = Result.getLoBits(ArgBits);
7202   Result.setIsUnsigned(true);
7203 
7204   if (IsShiftedByte(Result))
7205     return false;
7206 
7207   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7208          << Arg->getSourceRange();
7209 }
7210 
7211 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7212 /// TheCall is a constant expression representing either a shifted byte value,
7213 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7214 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7215 /// Arm MVE intrinsics.
7216 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7217                                                    int ArgNum,
7218                                                    unsigned ArgBits) {
7219   llvm::APSInt Result;
7220 
7221   // We can't check the value of a dependent argument.
7222   Expr *Arg = TheCall->getArg(ArgNum);
7223   if (Arg->isTypeDependent() || Arg->isValueDependent())
7224     return false;
7225 
7226   // Check constant-ness first.
7227   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7228     return true;
7229 
7230   // Truncate to the given size.
7231   Result = Result.getLoBits(ArgBits);
7232   Result.setIsUnsigned(true);
7233 
7234   // Check to see if it's in either of the required forms.
7235   if (IsShiftedByte(Result) ||
7236       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7237     return false;
7238 
7239   return Diag(TheCall->getBeginLoc(),
7240               diag::err_argument_not_shifted_byte_or_xxff)
7241          << Arg->getSourceRange();
7242 }
7243 
7244 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7245 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7246   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7247     if (checkArgCount(*this, TheCall, 2))
7248       return true;
7249     Expr *Arg0 = TheCall->getArg(0);
7250     Expr *Arg1 = TheCall->getArg(1);
7251 
7252     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7253     if (FirstArg.isInvalid())
7254       return true;
7255     QualType FirstArgType = FirstArg.get()->getType();
7256     if (!FirstArgType->isAnyPointerType())
7257       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7258                << "first" << FirstArgType << Arg0->getSourceRange();
7259     TheCall->setArg(0, FirstArg.get());
7260 
7261     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7262     if (SecArg.isInvalid())
7263       return true;
7264     QualType SecArgType = SecArg.get()->getType();
7265     if (!SecArgType->isIntegerType())
7266       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7267                << "second" << SecArgType << Arg1->getSourceRange();
7268 
7269     // Derive the return type from the pointer argument.
7270     TheCall->setType(FirstArgType);
7271     return false;
7272   }
7273 
7274   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7275     if (checkArgCount(*this, TheCall, 2))
7276       return true;
7277 
7278     Expr *Arg0 = TheCall->getArg(0);
7279     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7280     if (FirstArg.isInvalid())
7281       return true;
7282     QualType FirstArgType = FirstArg.get()->getType();
7283     if (!FirstArgType->isAnyPointerType())
7284       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7285                << "first" << FirstArgType << Arg0->getSourceRange();
7286     TheCall->setArg(0, FirstArg.get());
7287 
7288     // Derive the return type from the pointer argument.
7289     TheCall->setType(FirstArgType);
7290 
7291     // Second arg must be an constant in range [0,15]
7292     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7293   }
7294 
7295   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7296     if (checkArgCount(*this, TheCall, 2))
7297       return true;
7298     Expr *Arg0 = TheCall->getArg(0);
7299     Expr *Arg1 = TheCall->getArg(1);
7300 
7301     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7302     if (FirstArg.isInvalid())
7303       return true;
7304     QualType FirstArgType = FirstArg.get()->getType();
7305     if (!FirstArgType->isAnyPointerType())
7306       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7307                << "first" << FirstArgType << Arg0->getSourceRange();
7308 
7309     QualType SecArgType = Arg1->getType();
7310     if (!SecArgType->isIntegerType())
7311       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7312                << "second" << SecArgType << Arg1->getSourceRange();
7313     TheCall->setType(Context.IntTy);
7314     return false;
7315   }
7316 
7317   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7318       BuiltinID == AArch64::BI__builtin_arm_stg) {
7319     if (checkArgCount(*this, TheCall, 1))
7320       return true;
7321     Expr *Arg0 = TheCall->getArg(0);
7322     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7323     if (FirstArg.isInvalid())
7324       return true;
7325 
7326     QualType FirstArgType = FirstArg.get()->getType();
7327     if (!FirstArgType->isAnyPointerType())
7328       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7329                << "first" << FirstArgType << Arg0->getSourceRange();
7330     TheCall->setArg(0, FirstArg.get());
7331 
7332     // Derive the return type from the pointer argument.
7333     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7334       TheCall->setType(FirstArgType);
7335     return false;
7336   }
7337 
7338   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7339     Expr *ArgA = TheCall->getArg(0);
7340     Expr *ArgB = TheCall->getArg(1);
7341 
7342     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7343     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7344 
7345     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7346       return true;
7347 
7348     QualType ArgTypeA = ArgExprA.get()->getType();
7349     QualType ArgTypeB = ArgExprB.get()->getType();
7350 
7351     auto isNull = [&] (Expr *E) -> bool {
7352       return E->isNullPointerConstant(
7353                         Context, Expr::NPC_ValueDependentIsNotNull); };
7354 
7355     // argument should be either a pointer or null
7356     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7357       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7358         << "first" << ArgTypeA << ArgA->getSourceRange();
7359 
7360     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7361       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7362         << "second" << ArgTypeB << ArgB->getSourceRange();
7363 
7364     // Ensure Pointee types are compatible
7365     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7366         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7367       QualType pointeeA = ArgTypeA->getPointeeType();
7368       QualType pointeeB = ArgTypeB->getPointeeType();
7369       if (!Context.typesAreCompatible(
7370              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7371              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7372         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7373           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7374           << ArgB->getSourceRange();
7375       }
7376     }
7377 
7378     // at least one argument should be pointer type
7379     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7380       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7381         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7382 
7383     if (isNull(ArgA)) // adopt type of the other pointer
7384       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7385 
7386     if (isNull(ArgB))
7387       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7388 
7389     TheCall->setArg(0, ArgExprA.get());
7390     TheCall->setArg(1, ArgExprB.get());
7391     TheCall->setType(Context.LongLongTy);
7392     return false;
7393   }
7394   assert(false && "Unhandled ARM MTE intrinsic");
7395   return true;
7396 }
7397 
7398 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7399 /// TheCall is an ARM/AArch64 special register string literal.
7400 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7401                                     int ArgNum, unsigned ExpectedFieldNum,
7402                                     bool AllowName) {
7403   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7404                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7405                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7406                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7407                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7408                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7409   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7410                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7411                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7412                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7413                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7414                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7415   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7416 
7417   // We can't check the value of a dependent argument.
7418   Expr *Arg = TheCall->getArg(ArgNum);
7419   if (Arg->isTypeDependent() || Arg->isValueDependent())
7420     return false;
7421 
7422   // Check if the argument is a string literal.
7423   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7424     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7425            << Arg->getSourceRange();
7426 
7427   // Check the type of special register given.
7428   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7429   SmallVector<StringRef, 6> Fields;
7430   Reg.split(Fields, ":");
7431 
7432   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7433     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7434            << Arg->getSourceRange();
7435 
7436   // If the string is the name of a register then we cannot check that it is
7437   // valid here but if the string is of one the forms described in ACLE then we
7438   // can check that the supplied fields are integers and within the valid
7439   // ranges.
7440   if (Fields.size() > 1) {
7441     bool FiveFields = Fields.size() == 5;
7442 
7443     bool ValidString = true;
7444     if (IsARMBuiltin) {
7445       ValidString &= Fields[0].startswith_insensitive("cp") ||
7446                      Fields[0].startswith_insensitive("p");
7447       if (ValidString)
7448         Fields[0] = Fields[0].drop_front(
7449             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7450 
7451       ValidString &= Fields[2].startswith_insensitive("c");
7452       if (ValidString)
7453         Fields[2] = Fields[2].drop_front(1);
7454 
7455       if (FiveFields) {
7456         ValidString &= Fields[3].startswith_insensitive("c");
7457         if (ValidString)
7458           Fields[3] = Fields[3].drop_front(1);
7459       }
7460     }
7461 
7462     SmallVector<int, 5> Ranges;
7463     if (FiveFields)
7464       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7465     else
7466       Ranges.append({15, 7, 15});
7467 
7468     for (unsigned i=0; i<Fields.size(); ++i) {
7469       int IntField;
7470       ValidString &= !Fields[i].getAsInteger(10, IntField);
7471       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7472     }
7473 
7474     if (!ValidString)
7475       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7476              << Arg->getSourceRange();
7477   } else if (IsAArch64Builtin && Fields.size() == 1) {
7478     // If the register name is one of those that appear in the condition below
7479     // and the special register builtin being used is one of the write builtins,
7480     // then we require that the argument provided for writing to the register
7481     // is an integer constant expression. This is because it will be lowered to
7482     // an MSR (immediate) instruction, so we need to know the immediate at
7483     // compile time.
7484     if (TheCall->getNumArgs() != 2)
7485       return false;
7486 
7487     std::string RegLower = Reg.lower();
7488     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7489         RegLower != "pan" && RegLower != "uao")
7490       return false;
7491 
7492     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7493   }
7494 
7495   return false;
7496 }
7497 
7498 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7499 /// Emit an error and return true on failure; return false on success.
7500 /// TypeStr is a string containing the type descriptor of the value returned by
7501 /// the builtin and the descriptors of the expected type of the arguments.
7502 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7503                                  const char *TypeStr) {
7504 
7505   assert((TypeStr[0] != '\0') &&
7506          "Invalid types in PPC MMA builtin declaration");
7507 
7508   switch (BuiltinID) {
7509   default:
7510     // This function is called in CheckPPCBuiltinFunctionCall where the
7511     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7512     // we are isolating the pair vector memop builtins that can be used with mma
7513     // off so the default case is every builtin that requires mma and paired
7514     // vector memops.
7515     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7516                          diag::err_ppc_builtin_only_on_arch, "10") ||
7517         SemaFeatureCheck(*this, TheCall, "mma",
7518                          diag::err_ppc_builtin_only_on_arch, "10"))
7519       return true;
7520     break;
7521   case PPC::BI__builtin_vsx_lxvp:
7522   case PPC::BI__builtin_vsx_stxvp:
7523   case PPC::BI__builtin_vsx_assemble_pair:
7524   case PPC::BI__builtin_vsx_disassemble_pair:
7525     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7526                          diag::err_ppc_builtin_only_on_arch, "10"))
7527       return true;
7528     break;
7529   }
7530 
7531   unsigned Mask = 0;
7532   unsigned ArgNum = 0;
7533 
7534   // The first type in TypeStr is the type of the value returned by the
7535   // builtin. So we first read that type and change the type of TheCall.
7536   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7537   TheCall->setType(type);
7538 
7539   while (*TypeStr != '\0') {
7540     Mask = 0;
7541     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7542     if (ArgNum >= TheCall->getNumArgs()) {
7543       ArgNum++;
7544       break;
7545     }
7546 
7547     Expr *Arg = TheCall->getArg(ArgNum);
7548     QualType PassedType = Arg->getType();
7549     QualType StrippedRVType = PassedType.getCanonicalType();
7550 
7551     // Strip Restrict/Volatile qualifiers.
7552     if (StrippedRVType.isRestrictQualified() ||
7553         StrippedRVType.isVolatileQualified())
7554       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7555 
7556     // The only case where the argument type and expected type are allowed to
7557     // mismatch is if the argument type is a non-void pointer (or array) and
7558     // expected type is a void pointer.
7559     if (StrippedRVType != ExpectedType)
7560       if (!(ExpectedType->isVoidPointerType() &&
7561             (StrippedRVType->isPointerType() || StrippedRVType->isArrayType())))
7562         return Diag(Arg->getBeginLoc(),
7563                     diag::err_typecheck_convert_incompatible)
7564                << PassedType << ExpectedType << 1 << 0 << 0;
7565 
7566     // If the value of the Mask is not 0, we have a constraint in the size of
7567     // the integer argument so here we ensure the argument is a constant that
7568     // is in the valid range.
7569     if (Mask != 0 &&
7570         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7571       return true;
7572 
7573     ArgNum++;
7574   }
7575 
7576   // In case we exited early from the previous loop, there are other types to
7577   // read from TypeStr. So we need to read them all to ensure we have the right
7578   // number of arguments in TheCall and if it is not the case, to display a
7579   // better error message.
7580   while (*TypeStr != '\0') {
7581     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7582     ArgNum++;
7583   }
7584   if (checkArgCount(*this, TheCall, ArgNum))
7585     return true;
7586 
7587   return false;
7588 }
7589 
7590 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7591 /// This checks that the target supports __builtin_longjmp and
7592 /// that val is a constant 1.
7593 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7594   if (!Context.getTargetInfo().hasSjLjLowering())
7595     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7596            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7597 
7598   Expr *Arg = TheCall->getArg(1);
7599   llvm::APSInt Result;
7600 
7601   // TODO: This is less than ideal. Overload this to take a value.
7602   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7603     return true;
7604 
7605   if (Result != 1)
7606     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7607            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7608 
7609   return false;
7610 }
7611 
7612 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7613 /// This checks that the target supports __builtin_setjmp.
7614 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7615   if (!Context.getTargetInfo().hasSjLjLowering())
7616     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7617            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7618   return false;
7619 }
7620 
7621 namespace {
7622 
7623 class UncoveredArgHandler {
7624   enum { Unknown = -1, AllCovered = -2 };
7625 
7626   signed FirstUncoveredArg = Unknown;
7627   SmallVector<const Expr *, 4> DiagnosticExprs;
7628 
7629 public:
7630   UncoveredArgHandler() = default;
7631 
7632   bool hasUncoveredArg() const {
7633     return (FirstUncoveredArg >= 0);
7634   }
7635 
7636   unsigned getUncoveredArg() const {
7637     assert(hasUncoveredArg() && "no uncovered argument");
7638     return FirstUncoveredArg;
7639   }
7640 
7641   void setAllCovered() {
7642     // A string has been found with all arguments covered, so clear out
7643     // the diagnostics.
7644     DiagnosticExprs.clear();
7645     FirstUncoveredArg = AllCovered;
7646   }
7647 
7648   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7649     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7650 
7651     // Don't update if a previous string covers all arguments.
7652     if (FirstUncoveredArg == AllCovered)
7653       return;
7654 
7655     // UncoveredArgHandler tracks the highest uncovered argument index
7656     // and with it all the strings that match this index.
7657     if (NewFirstUncoveredArg == FirstUncoveredArg)
7658       DiagnosticExprs.push_back(StrExpr);
7659     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7660       DiagnosticExprs.clear();
7661       DiagnosticExprs.push_back(StrExpr);
7662       FirstUncoveredArg = NewFirstUncoveredArg;
7663     }
7664   }
7665 
7666   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7667 };
7668 
7669 enum StringLiteralCheckType {
7670   SLCT_NotALiteral,
7671   SLCT_UncheckedLiteral,
7672   SLCT_CheckedLiteral
7673 };
7674 
7675 } // namespace
7676 
7677 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7678                                      BinaryOperatorKind BinOpKind,
7679                                      bool AddendIsRight) {
7680   unsigned BitWidth = Offset.getBitWidth();
7681   unsigned AddendBitWidth = Addend.getBitWidth();
7682   // There might be negative interim results.
7683   if (Addend.isUnsigned()) {
7684     Addend = Addend.zext(++AddendBitWidth);
7685     Addend.setIsSigned(true);
7686   }
7687   // Adjust the bit width of the APSInts.
7688   if (AddendBitWidth > BitWidth) {
7689     Offset = Offset.sext(AddendBitWidth);
7690     BitWidth = AddendBitWidth;
7691   } else if (BitWidth > AddendBitWidth) {
7692     Addend = Addend.sext(BitWidth);
7693   }
7694 
7695   bool Ov = false;
7696   llvm::APSInt ResOffset = Offset;
7697   if (BinOpKind == BO_Add)
7698     ResOffset = Offset.sadd_ov(Addend, Ov);
7699   else {
7700     assert(AddendIsRight && BinOpKind == BO_Sub &&
7701            "operator must be add or sub with addend on the right");
7702     ResOffset = Offset.ssub_ov(Addend, Ov);
7703   }
7704 
7705   // We add an offset to a pointer here so we should support an offset as big as
7706   // possible.
7707   if (Ov) {
7708     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7709            "index (intermediate) result too big");
7710     Offset = Offset.sext(2 * BitWidth);
7711     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7712     return;
7713   }
7714 
7715   Offset = ResOffset;
7716 }
7717 
7718 namespace {
7719 
7720 // This is a wrapper class around StringLiteral to support offsetted string
7721 // literals as format strings. It takes the offset into account when returning
7722 // the string and its length or the source locations to display notes correctly.
7723 class FormatStringLiteral {
7724   const StringLiteral *FExpr;
7725   int64_t Offset;
7726 
7727  public:
7728   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7729       : FExpr(fexpr), Offset(Offset) {}
7730 
7731   StringRef getString() const {
7732     return FExpr->getString().drop_front(Offset);
7733   }
7734 
7735   unsigned getByteLength() const {
7736     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7737   }
7738 
7739   unsigned getLength() const { return FExpr->getLength() - Offset; }
7740   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7741 
7742   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7743 
7744   QualType getType() const { return FExpr->getType(); }
7745 
7746   bool isAscii() const { return FExpr->isAscii(); }
7747   bool isWide() const { return FExpr->isWide(); }
7748   bool isUTF8() const { return FExpr->isUTF8(); }
7749   bool isUTF16() const { return FExpr->isUTF16(); }
7750   bool isUTF32() const { return FExpr->isUTF32(); }
7751   bool isPascal() const { return FExpr->isPascal(); }
7752 
7753   SourceLocation getLocationOfByte(
7754       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7755       const TargetInfo &Target, unsigned *StartToken = nullptr,
7756       unsigned *StartTokenByteOffset = nullptr) const {
7757     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7758                                     StartToken, StartTokenByteOffset);
7759   }
7760 
7761   SourceLocation getBeginLoc() const LLVM_READONLY {
7762     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7763   }
7764 
7765   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7766 };
7767 
7768 }  // namespace
7769 
7770 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7771                               const Expr *OrigFormatExpr,
7772                               ArrayRef<const Expr *> Args,
7773                               bool HasVAListArg, unsigned format_idx,
7774                               unsigned firstDataArg,
7775                               Sema::FormatStringType Type,
7776                               bool inFunctionCall,
7777                               Sema::VariadicCallType CallType,
7778                               llvm::SmallBitVector &CheckedVarArgs,
7779                               UncoveredArgHandler &UncoveredArg,
7780                               bool IgnoreStringsWithoutSpecifiers);
7781 
7782 // Determine if an expression is a string literal or constant string.
7783 // If this function returns false on the arguments to a function expecting a
7784 // format string, we will usually need to emit a warning.
7785 // True string literals are then checked by CheckFormatString.
7786 static StringLiteralCheckType
7787 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7788                       bool HasVAListArg, unsigned format_idx,
7789                       unsigned firstDataArg, Sema::FormatStringType Type,
7790                       Sema::VariadicCallType CallType, bool InFunctionCall,
7791                       llvm::SmallBitVector &CheckedVarArgs,
7792                       UncoveredArgHandler &UncoveredArg,
7793                       llvm::APSInt Offset,
7794                       bool IgnoreStringsWithoutSpecifiers = false) {
7795   if (S.isConstantEvaluated())
7796     return SLCT_NotALiteral;
7797  tryAgain:
7798   assert(Offset.isSigned() && "invalid offset");
7799 
7800   if (E->isTypeDependent() || E->isValueDependent())
7801     return SLCT_NotALiteral;
7802 
7803   E = E->IgnoreParenCasts();
7804 
7805   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7806     // Technically -Wformat-nonliteral does not warn about this case.
7807     // The behavior of printf and friends in this case is implementation
7808     // dependent.  Ideally if the format string cannot be null then
7809     // it should have a 'nonnull' attribute in the function prototype.
7810     return SLCT_UncheckedLiteral;
7811 
7812   switch (E->getStmtClass()) {
7813   case Stmt::BinaryConditionalOperatorClass:
7814   case Stmt::ConditionalOperatorClass: {
7815     // The expression is a literal if both sub-expressions were, and it was
7816     // completely checked only if both sub-expressions were checked.
7817     const AbstractConditionalOperator *C =
7818         cast<AbstractConditionalOperator>(E);
7819 
7820     // Determine whether it is necessary to check both sub-expressions, for
7821     // example, because the condition expression is a constant that can be
7822     // evaluated at compile time.
7823     bool CheckLeft = true, CheckRight = true;
7824 
7825     bool Cond;
7826     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7827                                                  S.isConstantEvaluated())) {
7828       if (Cond)
7829         CheckRight = false;
7830       else
7831         CheckLeft = false;
7832     }
7833 
7834     // We need to maintain the offsets for the right and the left hand side
7835     // separately to check if every possible indexed expression is a valid
7836     // string literal. They might have different offsets for different string
7837     // literals in the end.
7838     StringLiteralCheckType Left;
7839     if (!CheckLeft)
7840       Left = SLCT_UncheckedLiteral;
7841     else {
7842       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7843                                    HasVAListArg, format_idx, firstDataArg,
7844                                    Type, CallType, InFunctionCall,
7845                                    CheckedVarArgs, UncoveredArg, Offset,
7846                                    IgnoreStringsWithoutSpecifiers);
7847       if (Left == SLCT_NotALiteral || !CheckRight) {
7848         return Left;
7849       }
7850     }
7851 
7852     StringLiteralCheckType Right = checkFormatStringExpr(
7853         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7854         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7855         IgnoreStringsWithoutSpecifiers);
7856 
7857     return (CheckLeft && Left < Right) ? Left : Right;
7858   }
7859 
7860   case Stmt::ImplicitCastExprClass:
7861     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7862     goto tryAgain;
7863 
7864   case Stmt::OpaqueValueExprClass:
7865     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7866       E = src;
7867       goto tryAgain;
7868     }
7869     return SLCT_NotALiteral;
7870 
7871   case Stmt::PredefinedExprClass:
7872     // While __func__, etc., are technically not string literals, they
7873     // cannot contain format specifiers and thus are not a security
7874     // liability.
7875     return SLCT_UncheckedLiteral;
7876 
7877   case Stmt::DeclRefExprClass: {
7878     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7879 
7880     // As an exception, do not flag errors for variables binding to
7881     // const string literals.
7882     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7883       bool isConstant = false;
7884       QualType T = DR->getType();
7885 
7886       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7887         isConstant = AT->getElementType().isConstant(S.Context);
7888       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7889         isConstant = T.isConstant(S.Context) &&
7890                      PT->getPointeeType().isConstant(S.Context);
7891       } else if (T->isObjCObjectPointerType()) {
7892         // In ObjC, there is usually no "const ObjectPointer" type,
7893         // so don't check if the pointee type is constant.
7894         isConstant = T.isConstant(S.Context);
7895       }
7896 
7897       if (isConstant) {
7898         if (const Expr *Init = VD->getAnyInitializer()) {
7899           // Look through initializers like const char c[] = { "foo" }
7900           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7901             if (InitList->isStringLiteralInit())
7902               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7903           }
7904           return checkFormatStringExpr(S, Init, Args,
7905                                        HasVAListArg, format_idx,
7906                                        firstDataArg, Type, CallType,
7907                                        /*InFunctionCall*/ false, CheckedVarArgs,
7908                                        UncoveredArg, Offset);
7909         }
7910       }
7911 
7912       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7913       // special check to see if the format string is a function parameter
7914       // of the function calling the printf function.  If the function
7915       // has an attribute indicating it is a printf-like function, then we
7916       // should suppress warnings concerning non-literals being used in a call
7917       // to a vprintf function.  For example:
7918       //
7919       // void
7920       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7921       //      va_list ap;
7922       //      va_start(ap, fmt);
7923       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7924       //      ...
7925       // }
7926       if (HasVAListArg) {
7927         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7928           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
7929             int PVIndex = PV->getFunctionScopeIndex() + 1;
7930             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7931               // adjust for implicit parameter
7932               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
7933                 if (MD->isInstance())
7934                   ++PVIndex;
7935               // We also check if the formats are compatible.
7936               // We can't pass a 'scanf' string to a 'printf' function.
7937               if (PVIndex == PVFormat->getFormatIdx() &&
7938                   Type == S.GetFormatStringType(PVFormat))
7939                 return SLCT_UncheckedLiteral;
7940             }
7941           }
7942         }
7943       }
7944     }
7945 
7946     return SLCT_NotALiteral;
7947   }
7948 
7949   case Stmt::CallExprClass:
7950   case Stmt::CXXMemberCallExprClass: {
7951     const CallExpr *CE = cast<CallExpr>(E);
7952     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7953       bool IsFirst = true;
7954       StringLiteralCheckType CommonResult;
7955       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7956         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7957         StringLiteralCheckType Result = checkFormatStringExpr(
7958             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7959             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7960             IgnoreStringsWithoutSpecifiers);
7961         if (IsFirst) {
7962           CommonResult = Result;
7963           IsFirst = false;
7964         }
7965       }
7966       if (!IsFirst)
7967         return CommonResult;
7968 
7969       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7970         unsigned BuiltinID = FD->getBuiltinID();
7971         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7972             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7973           const Expr *Arg = CE->getArg(0);
7974           return checkFormatStringExpr(S, Arg, Args,
7975                                        HasVAListArg, format_idx,
7976                                        firstDataArg, Type, CallType,
7977                                        InFunctionCall, CheckedVarArgs,
7978                                        UncoveredArg, Offset,
7979                                        IgnoreStringsWithoutSpecifiers);
7980         }
7981       }
7982     }
7983 
7984     return SLCT_NotALiteral;
7985   }
7986   case Stmt::ObjCMessageExprClass: {
7987     const auto *ME = cast<ObjCMessageExpr>(E);
7988     if (const auto *MD = ME->getMethodDecl()) {
7989       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7990         // As a special case heuristic, if we're using the method -[NSBundle
7991         // localizedStringForKey:value:table:], ignore any key strings that lack
7992         // format specifiers. The idea is that if the key doesn't have any
7993         // format specifiers then its probably just a key to map to the
7994         // localized strings. If it does have format specifiers though, then its
7995         // likely that the text of the key is the format string in the
7996         // programmer's language, and should be checked.
7997         const ObjCInterfaceDecl *IFace;
7998         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7999             IFace->getIdentifier()->isStr("NSBundle") &&
8000             MD->getSelector().isKeywordSelector(
8001                 {"localizedStringForKey", "value", "table"})) {
8002           IgnoreStringsWithoutSpecifiers = true;
8003         }
8004 
8005         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
8006         return checkFormatStringExpr(
8007             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
8008             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
8009             IgnoreStringsWithoutSpecifiers);
8010       }
8011     }
8012 
8013     return SLCT_NotALiteral;
8014   }
8015   case Stmt::ObjCStringLiteralClass:
8016   case Stmt::StringLiteralClass: {
8017     const StringLiteral *StrE = nullptr;
8018 
8019     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
8020       StrE = ObjCFExpr->getString();
8021     else
8022       StrE = cast<StringLiteral>(E);
8023 
8024     if (StrE) {
8025       if (Offset.isNegative() || Offset > StrE->getLength()) {
8026         // TODO: It would be better to have an explicit warning for out of
8027         // bounds literals.
8028         return SLCT_NotALiteral;
8029       }
8030       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
8031       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
8032                         firstDataArg, Type, InFunctionCall, CallType,
8033                         CheckedVarArgs, UncoveredArg,
8034                         IgnoreStringsWithoutSpecifiers);
8035       return SLCT_CheckedLiteral;
8036     }
8037 
8038     return SLCT_NotALiteral;
8039   }
8040   case Stmt::BinaryOperatorClass: {
8041     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
8042 
8043     // A string literal + an int offset is still a string literal.
8044     if (BinOp->isAdditiveOp()) {
8045       Expr::EvalResult LResult, RResult;
8046 
8047       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
8048           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8049       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
8050           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
8051 
8052       if (LIsInt != RIsInt) {
8053         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
8054 
8055         if (LIsInt) {
8056           if (BinOpKind == BO_Add) {
8057             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
8058             E = BinOp->getRHS();
8059             goto tryAgain;
8060           }
8061         } else {
8062           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
8063           E = BinOp->getLHS();
8064           goto tryAgain;
8065         }
8066       }
8067     }
8068 
8069     return SLCT_NotALiteral;
8070   }
8071   case Stmt::UnaryOperatorClass: {
8072     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
8073     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
8074     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
8075       Expr::EvalResult IndexResult;
8076       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
8077                                        Expr::SE_NoSideEffects,
8078                                        S.isConstantEvaluated())) {
8079         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
8080                    /*RHS is int*/ true);
8081         E = ASE->getBase();
8082         goto tryAgain;
8083       }
8084     }
8085 
8086     return SLCT_NotALiteral;
8087   }
8088 
8089   default:
8090     return SLCT_NotALiteral;
8091   }
8092 }
8093 
8094 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8095   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8096       .Case("scanf", FST_Scanf)
8097       .Cases("printf", "printf0", FST_Printf)
8098       .Cases("NSString", "CFString", FST_NSString)
8099       .Case("strftime", FST_Strftime)
8100       .Case("strfmon", FST_Strfmon)
8101       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8102       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8103       .Case("os_trace", FST_OSLog)
8104       .Case("os_log", FST_OSLog)
8105       .Default(FST_Unknown);
8106 }
8107 
8108 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8109 /// functions) for correct use of format strings.
8110 /// Returns true if a format string has been fully checked.
8111 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8112                                 ArrayRef<const Expr *> Args,
8113                                 bool IsCXXMember,
8114                                 VariadicCallType CallType,
8115                                 SourceLocation Loc, SourceRange Range,
8116                                 llvm::SmallBitVector &CheckedVarArgs) {
8117   FormatStringInfo FSI;
8118   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8119     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8120                                 FSI.FirstDataArg, GetFormatStringType(Format),
8121                                 CallType, Loc, Range, CheckedVarArgs);
8122   return false;
8123 }
8124 
8125 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8126                                 bool HasVAListArg, unsigned format_idx,
8127                                 unsigned firstDataArg, FormatStringType Type,
8128                                 VariadicCallType CallType,
8129                                 SourceLocation Loc, SourceRange Range,
8130                                 llvm::SmallBitVector &CheckedVarArgs) {
8131   // CHECK: printf/scanf-like function is called with no format string.
8132   if (format_idx >= Args.size()) {
8133     Diag(Loc, diag::warn_missing_format_string) << Range;
8134     return false;
8135   }
8136 
8137   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8138 
8139   // CHECK: format string is not a string literal.
8140   //
8141   // Dynamically generated format strings are difficult to
8142   // automatically vet at compile time.  Requiring that format strings
8143   // are string literals: (1) permits the checking of format strings by
8144   // the compiler and thereby (2) can practically remove the source of
8145   // many format string exploits.
8146 
8147   // Format string can be either ObjC string (e.g. @"%d") or
8148   // C string (e.g. "%d")
8149   // ObjC string uses the same format specifiers as C string, so we can use
8150   // the same format string checking logic for both ObjC and C strings.
8151   UncoveredArgHandler UncoveredArg;
8152   StringLiteralCheckType CT =
8153       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8154                             format_idx, firstDataArg, Type, CallType,
8155                             /*IsFunctionCall*/ true, CheckedVarArgs,
8156                             UncoveredArg,
8157                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8158 
8159   // Generate a diagnostic where an uncovered argument is detected.
8160   if (UncoveredArg.hasUncoveredArg()) {
8161     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8162     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8163     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8164   }
8165 
8166   if (CT != SLCT_NotALiteral)
8167     // Literal format string found, check done!
8168     return CT == SLCT_CheckedLiteral;
8169 
8170   // Strftime is particular as it always uses a single 'time' argument,
8171   // so it is safe to pass a non-literal string.
8172   if (Type == FST_Strftime)
8173     return false;
8174 
8175   // Do not emit diag when the string param is a macro expansion and the
8176   // format is either NSString or CFString. This is a hack to prevent
8177   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8178   // which are usually used in place of NS and CF string literals.
8179   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8180   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8181     return false;
8182 
8183   // If there are no arguments specified, warn with -Wformat-security, otherwise
8184   // warn only with -Wformat-nonliteral.
8185   if (Args.size() == firstDataArg) {
8186     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8187       << OrigFormatExpr->getSourceRange();
8188     switch (Type) {
8189     default:
8190       break;
8191     case FST_Kprintf:
8192     case FST_FreeBSDKPrintf:
8193     case FST_Printf:
8194       Diag(FormatLoc, diag::note_format_security_fixit)
8195         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8196       break;
8197     case FST_NSString:
8198       Diag(FormatLoc, diag::note_format_security_fixit)
8199         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8200       break;
8201     }
8202   } else {
8203     Diag(FormatLoc, diag::warn_format_nonliteral)
8204       << OrigFormatExpr->getSourceRange();
8205   }
8206   return false;
8207 }
8208 
8209 namespace {
8210 
8211 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8212 protected:
8213   Sema &S;
8214   const FormatStringLiteral *FExpr;
8215   const Expr *OrigFormatExpr;
8216   const Sema::FormatStringType FSType;
8217   const unsigned FirstDataArg;
8218   const unsigned NumDataArgs;
8219   const char *Beg; // Start of format string.
8220   const bool HasVAListArg;
8221   ArrayRef<const Expr *> Args;
8222   unsigned FormatIdx;
8223   llvm::SmallBitVector CoveredArgs;
8224   bool usesPositionalArgs = false;
8225   bool atFirstArg = true;
8226   bool inFunctionCall;
8227   Sema::VariadicCallType CallType;
8228   llvm::SmallBitVector &CheckedVarArgs;
8229   UncoveredArgHandler &UncoveredArg;
8230 
8231 public:
8232   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8233                      const Expr *origFormatExpr,
8234                      const Sema::FormatStringType type, unsigned firstDataArg,
8235                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8236                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8237                      bool inFunctionCall, Sema::VariadicCallType callType,
8238                      llvm::SmallBitVector &CheckedVarArgs,
8239                      UncoveredArgHandler &UncoveredArg)
8240       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8241         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8242         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8243         inFunctionCall(inFunctionCall), CallType(callType),
8244         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8245     CoveredArgs.resize(numDataArgs);
8246     CoveredArgs.reset();
8247   }
8248 
8249   void DoneProcessing();
8250 
8251   void HandleIncompleteSpecifier(const char *startSpecifier,
8252                                  unsigned specifierLen) override;
8253 
8254   void HandleInvalidLengthModifier(
8255                            const analyze_format_string::FormatSpecifier &FS,
8256                            const analyze_format_string::ConversionSpecifier &CS,
8257                            const char *startSpecifier, unsigned specifierLen,
8258                            unsigned DiagID);
8259 
8260   void HandleNonStandardLengthModifier(
8261                     const analyze_format_string::FormatSpecifier &FS,
8262                     const char *startSpecifier, unsigned specifierLen);
8263 
8264   void HandleNonStandardConversionSpecifier(
8265                     const analyze_format_string::ConversionSpecifier &CS,
8266                     const char *startSpecifier, unsigned specifierLen);
8267 
8268   void HandlePosition(const char *startPos, unsigned posLen) override;
8269 
8270   void HandleInvalidPosition(const char *startSpecifier,
8271                              unsigned specifierLen,
8272                              analyze_format_string::PositionContext p) override;
8273 
8274   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8275 
8276   void HandleNullChar(const char *nullCharacter) override;
8277 
8278   template <typename Range>
8279   static void
8280   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8281                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8282                        bool IsStringLocation, Range StringRange,
8283                        ArrayRef<FixItHint> Fixit = None);
8284 
8285 protected:
8286   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8287                                         const char *startSpec,
8288                                         unsigned specifierLen,
8289                                         const char *csStart, unsigned csLen);
8290 
8291   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8292                                          const char *startSpec,
8293                                          unsigned specifierLen);
8294 
8295   SourceRange getFormatStringRange();
8296   CharSourceRange getSpecifierRange(const char *startSpecifier,
8297                                     unsigned specifierLen);
8298   SourceLocation getLocationOfByte(const char *x);
8299 
8300   const Expr *getDataArg(unsigned i) const;
8301 
8302   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8303                     const analyze_format_string::ConversionSpecifier &CS,
8304                     const char *startSpecifier, unsigned specifierLen,
8305                     unsigned argIndex);
8306 
8307   template <typename Range>
8308   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8309                             bool IsStringLocation, Range StringRange,
8310                             ArrayRef<FixItHint> Fixit = None);
8311 };
8312 
8313 } // namespace
8314 
8315 SourceRange CheckFormatHandler::getFormatStringRange() {
8316   return OrigFormatExpr->getSourceRange();
8317 }
8318 
8319 CharSourceRange CheckFormatHandler::
8320 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8321   SourceLocation Start = getLocationOfByte(startSpecifier);
8322   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8323 
8324   // Advance the end SourceLocation by one due to half-open ranges.
8325   End = End.getLocWithOffset(1);
8326 
8327   return CharSourceRange::getCharRange(Start, End);
8328 }
8329 
8330 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8331   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8332                                   S.getLangOpts(), S.Context.getTargetInfo());
8333 }
8334 
8335 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8336                                                    unsigned specifierLen){
8337   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8338                        getLocationOfByte(startSpecifier),
8339                        /*IsStringLocation*/true,
8340                        getSpecifierRange(startSpecifier, specifierLen));
8341 }
8342 
8343 void CheckFormatHandler::HandleInvalidLengthModifier(
8344     const analyze_format_string::FormatSpecifier &FS,
8345     const analyze_format_string::ConversionSpecifier &CS,
8346     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8347   using namespace analyze_format_string;
8348 
8349   const LengthModifier &LM = FS.getLengthModifier();
8350   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8351 
8352   // See if we know how to fix this length modifier.
8353   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8354   if (FixedLM) {
8355     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8356                          getLocationOfByte(LM.getStart()),
8357                          /*IsStringLocation*/true,
8358                          getSpecifierRange(startSpecifier, specifierLen));
8359 
8360     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8361       << FixedLM->toString()
8362       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8363 
8364   } else {
8365     FixItHint Hint;
8366     if (DiagID == diag::warn_format_nonsensical_length)
8367       Hint = FixItHint::CreateRemoval(LMRange);
8368 
8369     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8370                          getLocationOfByte(LM.getStart()),
8371                          /*IsStringLocation*/true,
8372                          getSpecifierRange(startSpecifier, specifierLen),
8373                          Hint);
8374   }
8375 }
8376 
8377 void CheckFormatHandler::HandleNonStandardLengthModifier(
8378     const analyze_format_string::FormatSpecifier &FS,
8379     const char *startSpecifier, unsigned specifierLen) {
8380   using namespace analyze_format_string;
8381 
8382   const LengthModifier &LM = FS.getLengthModifier();
8383   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8384 
8385   // See if we know how to fix this length modifier.
8386   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8387   if (FixedLM) {
8388     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8389                            << LM.toString() << 0,
8390                          getLocationOfByte(LM.getStart()),
8391                          /*IsStringLocation*/true,
8392                          getSpecifierRange(startSpecifier, specifierLen));
8393 
8394     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8395       << FixedLM->toString()
8396       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8397 
8398   } else {
8399     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8400                            << LM.toString() << 0,
8401                          getLocationOfByte(LM.getStart()),
8402                          /*IsStringLocation*/true,
8403                          getSpecifierRange(startSpecifier, specifierLen));
8404   }
8405 }
8406 
8407 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8408     const analyze_format_string::ConversionSpecifier &CS,
8409     const char *startSpecifier, unsigned specifierLen) {
8410   using namespace analyze_format_string;
8411 
8412   // See if we know how to fix this conversion specifier.
8413   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8414   if (FixedCS) {
8415     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8416                           << CS.toString() << /*conversion specifier*/1,
8417                          getLocationOfByte(CS.getStart()),
8418                          /*IsStringLocation*/true,
8419                          getSpecifierRange(startSpecifier, specifierLen));
8420 
8421     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8422     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8423       << FixedCS->toString()
8424       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8425   } else {
8426     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8427                           << CS.toString() << /*conversion specifier*/1,
8428                          getLocationOfByte(CS.getStart()),
8429                          /*IsStringLocation*/true,
8430                          getSpecifierRange(startSpecifier, specifierLen));
8431   }
8432 }
8433 
8434 void CheckFormatHandler::HandlePosition(const char *startPos,
8435                                         unsigned posLen) {
8436   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8437                                getLocationOfByte(startPos),
8438                                /*IsStringLocation*/true,
8439                                getSpecifierRange(startPos, posLen));
8440 }
8441 
8442 void
8443 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8444                                      analyze_format_string::PositionContext p) {
8445   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8446                          << (unsigned) p,
8447                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8448                        getSpecifierRange(startPos, posLen));
8449 }
8450 
8451 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8452                                             unsigned posLen) {
8453   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8454                                getLocationOfByte(startPos),
8455                                /*IsStringLocation*/true,
8456                                getSpecifierRange(startPos, posLen));
8457 }
8458 
8459 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8460   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8461     // The presence of a null character is likely an error.
8462     EmitFormatDiagnostic(
8463       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8464       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8465       getFormatStringRange());
8466   }
8467 }
8468 
8469 // Note that this may return NULL if there was an error parsing or building
8470 // one of the argument expressions.
8471 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8472   return Args[FirstDataArg + i];
8473 }
8474 
8475 void CheckFormatHandler::DoneProcessing() {
8476   // Does the number of data arguments exceed the number of
8477   // format conversions in the format string?
8478   if (!HasVAListArg) {
8479       // Find any arguments that weren't covered.
8480     CoveredArgs.flip();
8481     signed notCoveredArg = CoveredArgs.find_first();
8482     if (notCoveredArg >= 0) {
8483       assert((unsigned)notCoveredArg < NumDataArgs);
8484       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8485     } else {
8486       UncoveredArg.setAllCovered();
8487     }
8488   }
8489 }
8490 
8491 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8492                                    const Expr *ArgExpr) {
8493   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8494          "Invalid state");
8495 
8496   if (!ArgExpr)
8497     return;
8498 
8499   SourceLocation Loc = ArgExpr->getBeginLoc();
8500 
8501   if (S.getSourceManager().isInSystemMacro(Loc))
8502     return;
8503 
8504   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8505   for (auto E : DiagnosticExprs)
8506     PDiag << E->getSourceRange();
8507 
8508   CheckFormatHandler::EmitFormatDiagnostic(
8509                                   S, IsFunctionCall, DiagnosticExprs[0],
8510                                   PDiag, Loc, /*IsStringLocation*/false,
8511                                   DiagnosticExprs[0]->getSourceRange());
8512 }
8513 
8514 bool
8515 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8516                                                      SourceLocation Loc,
8517                                                      const char *startSpec,
8518                                                      unsigned specifierLen,
8519                                                      const char *csStart,
8520                                                      unsigned csLen) {
8521   bool keepGoing = true;
8522   if (argIndex < NumDataArgs) {
8523     // Consider the argument coverered, even though the specifier doesn't
8524     // make sense.
8525     CoveredArgs.set(argIndex);
8526   }
8527   else {
8528     // If argIndex exceeds the number of data arguments we
8529     // don't issue a warning because that is just a cascade of warnings (and
8530     // they may have intended '%%' anyway). We don't want to continue processing
8531     // the format string after this point, however, as we will like just get
8532     // gibberish when trying to match arguments.
8533     keepGoing = false;
8534   }
8535 
8536   StringRef Specifier(csStart, csLen);
8537 
8538   // If the specifier in non-printable, it could be the first byte of a UTF-8
8539   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8540   // hex value.
8541   std::string CodePointStr;
8542   if (!llvm::sys::locale::isPrint(*csStart)) {
8543     llvm::UTF32 CodePoint;
8544     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8545     const llvm::UTF8 *E =
8546         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8547     llvm::ConversionResult Result =
8548         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8549 
8550     if (Result != llvm::conversionOK) {
8551       unsigned char FirstChar = *csStart;
8552       CodePoint = (llvm::UTF32)FirstChar;
8553     }
8554 
8555     llvm::raw_string_ostream OS(CodePointStr);
8556     if (CodePoint < 256)
8557       OS << "\\x" << llvm::format("%02x", CodePoint);
8558     else if (CodePoint <= 0xFFFF)
8559       OS << "\\u" << llvm::format("%04x", CodePoint);
8560     else
8561       OS << "\\U" << llvm::format("%08x", CodePoint);
8562     OS.flush();
8563     Specifier = CodePointStr;
8564   }
8565 
8566   EmitFormatDiagnostic(
8567       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8568       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8569 
8570   return keepGoing;
8571 }
8572 
8573 void
8574 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8575                                                       const char *startSpec,
8576                                                       unsigned specifierLen) {
8577   EmitFormatDiagnostic(
8578     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8579     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8580 }
8581 
8582 bool
8583 CheckFormatHandler::CheckNumArgs(
8584   const analyze_format_string::FormatSpecifier &FS,
8585   const analyze_format_string::ConversionSpecifier &CS,
8586   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8587 
8588   if (argIndex >= NumDataArgs) {
8589     PartialDiagnostic PDiag = FS.usesPositionalArg()
8590       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8591            << (argIndex+1) << NumDataArgs)
8592       : S.PDiag(diag::warn_printf_insufficient_data_args);
8593     EmitFormatDiagnostic(
8594       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8595       getSpecifierRange(startSpecifier, specifierLen));
8596 
8597     // Since more arguments than conversion tokens are given, by extension
8598     // all arguments are covered, so mark this as so.
8599     UncoveredArg.setAllCovered();
8600     return false;
8601   }
8602   return true;
8603 }
8604 
8605 template<typename Range>
8606 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8607                                               SourceLocation Loc,
8608                                               bool IsStringLocation,
8609                                               Range StringRange,
8610                                               ArrayRef<FixItHint> FixIt) {
8611   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8612                        Loc, IsStringLocation, StringRange, FixIt);
8613 }
8614 
8615 /// If the format string is not within the function call, emit a note
8616 /// so that the function call and string are in diagnostic messages.
8617 ///
8618 /// \param InFunctionCall if true, the format string is within the function
8619 /// call and only one diagnostic message will be produced.  Otherwise, an
8620 /// extra note will be emitted pointing to location of the format string.
8621 ///
8622 /// \param ArgumentExpr the expression that is passed as the format string
8623 /// argument in the function call.  Used for getting locations when two
8624 /// diagnostics are emitted.
8625 ///
8626 /// \param PDiag the callee should already have provided any strings for the
8627 /// diagnostic message.  This function only adds locations and fixits
8628 /// to diagnostics.
8629 ///
8630 /// \param Loc primary location for diagnostic.  If two diagnostics are
8631 /// required, one will be at Loc and a new SourceLocation will be created for
8632 /// the other one.
8633 ///
8634 /// \param IsStringLocation if true, Loc points to the format string should be
8635 /// used for the note.  Otherwise, Loc points to the argument list and will
8636 /// be used with PDiag.
8637 ///
8638 /// \param StringRange some or all of the string to highlight.  This is
8639 /// templated so it can accept either a CharSourceRange or a SourceRange.
8640 ///
8641 /// \param FixIt optional fix it hint for the format string.
8642 template <typename Range>
8643 void CheckFormatHandler::EmitFormatDiagnostic(
8644     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8645     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8646     Range StringRange, ArrayRef<FixItHint> FixIt) {
8647   if (InFunctionCall) {
8648     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8649     D << StringRange;
8650     D << FixIt;
8651   } else {
8652     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8653       << ArgumentExpr->getSourceRange();
8654 
8655     const Sema::SemaDiagnosticBuilder &Note =
8656       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8657              diag::note_format_string_defined);
8658 
8659     Note << StringRange;
8660     Note << FixIt;
8661   }
8662 }
8663 
8664 //===--- CHECK: Printf format string checking ------------------------------===//
8665 
8666 namespace {
8667 
8668 class CheckPrintfHandler : public CheckFormatHandler {
8669 public:
8670   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8671                      const Expr *origFormatExpr,
8672                      const Sema::FormatStringType type, unsigned firstDataArg,
8673                      unsigned numDataArgs, bool isObjC, const char *beg,
8674                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8675                      unsigned formatIdx, bool inFunctionCall,
8676                      Sema::VariadicCallType CallType,
8677                      llvm::SmallBitVector &CheckedVarArgs,
8678                      UncoveredArgHandler &UncoveredArg)
8679       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8680                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8681                            inFunctionCall, CallType, CheckedVarArgs,
8682                            UncoveredArg) {}
8683 
8684   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8685 
8686   /// Returns true if '%@' specifiers are allowed in the format string.
8687   bool allowsObjCArg() const {
8688     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8689            FSType == Sema::FST_OSTrace;
8690   }
8691 
8692   bool HandleInvalidPrintfConversionSpecifier(
8693                                       const analyze_printf::PrintfSpecifier &FS,
8694                                       const char *startSpecifier,
8695                                       unsigned specifierLen) override;
8696 
8697   void handleInvalidMaskType(StringRef MaskType) override;
8698 
8699   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8700                              const char *startSpecifier,
8701                              unsigned specifierLen) override;
8702   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8703                        const char *StartSpecifier,
8704                        unsigned SpecifierLen,
8705                        const Expr *E);
8706 
8707   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8708                     const char *startSpecifier, unsigned specifierLen);
8709   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8710                            const analyze_printf::OptionalAmount &Amt,
8711                            unsigned type,
8712                            const char *startSpecifier, unsigned specifierLen);
8713   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8714                   const analyze_printf::OptionalFlag &flag,
8715                   const char *startSpecifier, unsigned specifierLen);
8716   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8717                          const analyze_printf::OptionalFlag &ignoredFlag,
8718                          const analyze_printf::OptionalFlag &flag,
8719                          const char *startSpecifier, unsigned specifierLen);
8720   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8721                            const Expr *E);
8722 
8723   void HandleEmptyObjCModifierFlag(const char *startFlag,
8724                                    unsigned flagLen) override;
8725 
8726   void HandleInvalidObjCModifierFlag(const char *startFlag,
8727                                             unsigned flagLen) override;
8728 
8729   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8730                                            const char *flagsEnd,
8731                                            const char *conversionPosition)
8732                                              override;
8733 };
8734 
8735 } // namespace
8736 
8737 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8738                                       const analyze_printf::PrintfSpecifier &FS,
8739                                       const char *startSpecifier,
8740                                       unsigned specifierLen) {
8741   const analyze_printf::PrintfConversionSpecifier &CS =
8742     FS.getConversionSpecifier();
8743 
8744   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8745                                           getLocationOfByte(CS.getStart()),
8746                                           startSpecifier, specifierLen,
8747                                           CS.getStart(), CS.getLength());
8748 }
8749 
8750 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8751   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8752 }
8753 
8754 bool CheckPrintfHandler::HandleAmount(
8755                                const analyze_format_string::OptionalAmount &Amt,
8756                                unsigned k, const char *startSpecifier,
8757                                unsigned specifierLen) {
8758   if (Amt.hasDataArgument()) {
8759     if (!HasVAListArg) {
8760       unsigned argIndex = Amt.getArgIndex();
8761       if (argIndex >= NumDataArgs) {
8762         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8763                                << k,
8764                              getLocationOfByte(Amt.getStart()),
8765                              /*IsStringLocation*/true,
8766                              getSpecifierRange(startSpecifier, specifierLen));
8767         // Don't do any more checking.  We will just emit
8768         // spurious errors.
8769         return false;
8770       }
8771 
8772       // Type check the data argument.  It should be an 'int'.
8773       // Although not in conformance with C99, we also allow the argument to be
8774       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8775       // doesn't emit a warning for that case.
8776       CoveredArgs.set(argIndex);
8777       const Expr *Arg = getDataArg(argIndex);
8778       if (!Arg)
8779         return false;
8780 
8781       QualType T = Arg->getType();
8782 
8783       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8784       assert(AT.isValid());
8785 
8786       if (!AT.matchesType(S.Context, T)) {
8787         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8788                                << k << AT.getRepresentativeTypeName(S.Context)
8789                                << T << Arg->getSourceRange(),
8790                              getLocationOfByte(Amt.getStart()),
8791                              /*IsStringLocation*/true,
8792                              getSpecifierRange(startSpecifier, specifierLen));
8793         // Don't do any more checking.  We will just emit
8794         // spurious errors.
8795         return false;
8796       }
8797     }
8798   }
8799   return true;
8800 }
8801 
8802 void CheckPrintfHandler::HandleInvalidAmount(
8803                                       const analyze_printf::PrintfSpecifier &FS,
8804                                       const analyze_printf::OptionalAmount &Amt,
8805                                       unsigned type,
8806                                       const char *startSpecifier,
8807                                       unsigned specifierLen) {
8808   const analyze_printf::PrintfConversionSpecifier &CS =
8809     FS.getConversionSpecifier();
8810 
8811   FixItHint fixit =
8812     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8813       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8814                                  Amt.getConstantLength()))
8815       : FixItHint();
8816 
8817   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8818                          << type << CS.toString(),
8819                        getLocationOfByte(Amt.getStart()),
8820                        /*IsStringLocation*/true,
8821                        getSpecifierRange(startSpecifier, specifierLen),
8822                        fixit);
8823 }
8824 
8825 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8826                                     const analyze_printf::OptionalFlag &flag,
8827                                     const char *startSpecifier,
8828                                     unsigned specifierLen) {
8829   // Warn about pointless flag with a fixit removal.
8830   const analyze_printf::PrintfConversionSpecifier &CS =
8831     FS.getConversionSpecifier();
8832   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8833                          << flag.toString() << CS.toString(),
8834                        getLocationOfByte(flag.getPosition()),
8835                        /*IsStringLocation*/true,
8836                        getSpecifierRange(startSpecifier, specifierLen),
8837                        FixItHint::CreateRemoval(
8838                          getSpecifierRange(flag.getPosition(), 1)));
8839 }
8840 
8841 void CheckPrintfHandler::HandleIgnoredFlag(
8842                                 const analyze_printf::PrintfSpecifier &FS,
8843                                 const analyze_printf::OptionalFlag &ignoredFlag,
8844                                 const analyze_printf::OptionalFlag &flag,
8845                                 const char *startSpecifier,
8846                                 unsigned specifierLen) {
8847   // Warn about ignored flag with a fixit removal.
8848   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8849                          << ignoredFlag.toString() << flag.toString(),
8850                        getLocationOfByte(ignoredFlag.getPosition()),
8851                        /*IsStringLocation*/true,
8852                        getSpecifierRange(startSpecifier, specifierLen),
8853                        FixItHint::CreateRemoval(
8854                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8855 }
8856 
8857 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8858                                                      unsigned flagLen) {
8859   // Warn about an empty flag.
8860   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8861                        getLocationOfByte(startFlag),
8862                        /*IsStringLocation*/true,
8863                        getSpecifierRange(startFlag, flagLen));
8864 }
8865 
8866 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8867                                                        unsigned flagLen) {
8868   // Warn about an invalid flag.
8869   auto Range = getSpecifierRange(startFlag, flagLen);
8870   StringRef flag(startFlag, flagLen);
8871   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8872                       getLocationOfByte(startFlag),
8873                       /*IsStringLocation*/true,
8874                       Range, FixItHint::CreateRemoval(Range));
8875 }
8876 
8877 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8878     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8879     // Warn about using '[...]' without a '@' conversion.
8880     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8881     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8882     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8883                          getLocationOfByte(conversionPosition),
8884                          /*IsStringLocation*/true,
8885                          Range, FixItHint::CreateRemoval(Range));
8886 }
8887 
8888 // Determines if the specified is a C++ class or struct containing
8889 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8890 // "c_str()").
8891 template<typename MemberKind>
8892 static llvm::SmallPtrSet<MemberKind*, 1>
8893 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8894   const RecordType *RT = Ty->getAs<RecordType>();
8895   llvm::SmallPtrSet<MemberKind*, 1> Results;
8896 
8897   if (!RT)
8898     return Results;
8899   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8900   if (!RD || !RD->getDefinition())
8901     return Results;
8902 
8903   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8904                  Sema::LookupMemberName);
8905   R.suppressDiagnostics();
8906 
8907   // We just need to include all members of the right kind turned up by the
8908   // filter, at this point.
8909   if (S.LookupQualifiedName(R, RT->getDecl()))
8910     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8911       NamedDecl *decl = (*I)->getUnderlyingDecl();
8912       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8913         Results.insert(FK);
8914     }
8915   return Results;
8916 }
8917 
8918 /// Check if we could call '.c_str()' on an object.
8919 ///
8920 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8921 /// allow the call, or if it would be ambiguous).
8922 bool Sema::hasCStrMethod(const Expr *E) {
8923   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8924 
8925   MethodSet Results =
8926       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8927   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8928        MI != ME; ++MI)
8929     if ((*MI)->getMinRequiredArguments() == 0)
8930       return true;
8931   return false;
8932 }
8933 
8934 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8935 // better diagnostic if so. AT is assumed to be valid.
8936 // Returns true when a c_str() conversion method is found.
8937 bool CheckPrintfHandler::checkForCStrMembers(
8938     const analyze_printf::ArgType &AT, const Expr *E) {
8939   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8940 
8941   MethodSet Results =
8942       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8943 
8944   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8945        MI != ME; ++MI) {
8946     const CXXMethodDecl *Method = *MI;
8947     if (Method->getMinRequiredArguments() == 0 &&
8948         AT.matchesType(S.Context, Method->getReturnType())) {
8949       // FIXME: Suggest parens if the expression needs them.
8950       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8951       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8952           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8953       return true;
8954     }
8955   }
8956 
8957   return false;
8958 }
8959 
8960 bool
8961 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8962                                             &FS,
8963                                           const char *startSpecifier,
8964                                           unsigned specifierLen) {
8965   using namespace analyze_format_string;
8966   using namespace analyze_printf;
8967 
8968   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8969 
8970   if (FS.consumesDataArgument()) {
8971     if (atFirstArg) {
8972         atFirstArg = false;
8973         usesPositionalArgs = FS.usesPositionalArg();
8974     }
8975     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8976       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8977                                         startSpecifier, specifierLen);
8978       return false;
8979     }
8980   }
8981 
8982   // First check if the field width, precision, and conversion specifier
8983   // have matching data arguments.
8984   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8985                     startSpecifier, specifierLen)) {
8986     return false;
8987   }
8988 
8989   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8990                     startSpecifier, specifierLen)) {
8991     return false;
8992   }
8993 
8994   if (!CS.consumesDataArgument()) {
8995     // FIXME: Technically specifying a precision or field width here
8996     // makes no sense.  Worth issuing a warning at some point.
8997     return true;
8998   }
8999 
9000   // Consume the argument.
9001   unsigned argIndex = FS.getArgIndex();
9002   if (argIndex < NumDataArgs) {
9003     // The check to see if the argIndex is valid will come later.
9004     // We set the bit here because we may exit early from this
9005     // function if we encounter some other error.
9006     CoveredArgs.set(argIndex);
9007   }
9008 
9009   // FreeBSD kernel extensions.
9010   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
9011       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
9012     // We need at least two arguments.
9013     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
9014       return false;
9015 
9016     // Claim the second argument.
9017     CoveredArgs.set(argIndex + 1);
9018 
9019     // Type check the first argument (int for %b, pointer for %D)
9020     const Expr *Ex = getDataArg(argIndex);
9021     const analyze_printf::ArgType &AT =
9022       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
9023         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
9024     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
9025       EmitFormatDiagnostic(
9026           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9027               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
9028               << false << Ex->getSourceRange(),
9029           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9030           getSpecifierRange(startSpecifier, specifierLen));
9031 
9032     // Type check the second argument (char * for both %b and %D)
9033     Ex = getDataArg(argIndex + 1);
9034     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
9035     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
9036       EmitFormatDiagnostic(
9037           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9038               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
9039               << false << Ex->getSourceRange(),
9040           Ex->getBeginLoc(), /*IsStringLocation*/ false,
9041           getSpecifierRange(startSpecifier, specifierLen));
9042 
9043      return true;
9044   }
9045 
9046   // Check for using an Objective-C specific conversion specifier
9047   // in a non-ObjC literal.
9048   if (!allowsObjCArg() && CS.isObjCArg()) {
9049     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9050                                                   specifierLen);
9051   }
9052 
9053   // %P can only be used with os_log.
9054   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
9055     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9056                                                   specifierLen);
9057   }
9058 
9059   // %n is not allowed with os_log.
9060   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
9061     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
9062                          getLocationOfByte(CS.getStart()),
9063                          /*IsStringLocation*/ false,
9064                          getSpecifierRange(startSpecifier, specifierLen));
9065 
9066     return true;
9067   }
9068 
9069   // Only scalars are allowed for os_trace.
9070   if (FSType == Sema::FST_OSTrace &&
9071       (CS.getKind() == ConversionSpecifier::PArg ||
9072        CS.getKind() == ConversionSpecifier::sArg ||
9073        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
9074     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
9075                                                   specifierLen);
9076   }
9077 
9078   // Check for use of public/private annotation outside of os_log().
9079   if (FSType != Sema::FST_OSLog) {
9080     if (FS.isPublic().isSet()) {
9081       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9082                                << "public",
9083                            getLocationOfByte(FS.isPublic().getPosition()),
9084                            /*IsStringLocation*/ false,
9085                            getSpecifierRange(startSpecifier, specifierLen));
9086     }
9087     if (FS.isPrivate().isSet()) {
9088       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
9089                                << "private",
9090                            getLocationOfByte(FS.isPrivate().getPosition()),
9091                            /*IsStringLocation*/ false,
9092                            getSpecifierRange(startSpecifier, specifierLen));
9093     }
9094   }
9095 
9096   // Check for invalid use of field width
9097   if (!FS.hasValidFieldWidth()) {
9098     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9099         startSpecifier, specifierLen);
9100   }
9101 
9102   // Check for invalid use of precision
9103   if (!FS.hasValidPrecision()) {
9104     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9105         startSpecifier, specifierLen);
9106   }
9107 
9108   // Precision is mandatory for %P specifier.
9109   if (CS.getKind() == ConversionSpecifier::PArg &&
9110       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9111     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9112                          getLocationOfByte(startSpecifier),
9113                          /*IsStringLocation*/ false,
9114                          getSpecifierRange(startSpecifier, specifierLen));
9115   }
9116 
9117   // Check each flag does not conflict with any other component.
9118   if (!FS.hasValidThousandsGroupingPrefix())
9119     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9120   if (!FS.hasValidLeadingZeros())
9121     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9122   if (!FS.hasValidPlusPrefix())
9123     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9124   if (!FS.hasValidSpacePrefix())
9125     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9126   if (!FS.hasValidAlternativeForm())
9127     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9128   if (!FS.hasValidLeftJustified())
9129     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9130 
9131   // Check that flags are not ignored by another flag
9132   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9133     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9134         startSpecifier, specifierLen);
9135   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9136     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9137             startSpecifier, specifierLen);
9138 
9139   // Check the length modifier is valid with the given conversion specifier.
9140   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9141                                  S.getLangOpts()))
9142     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9143                                 diag::warn_format_nonsensical_length);
9144   else if (!FS.hasStandardLengthModifier())
9145     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9146   else if (!FS.hasStandardLengthConversionCombination())
9147     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9148                                 diag::warn_format_non_standard_conversion_spec);
9149 
9150   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9151     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9152 
9153   // The remaining checks depend on the data arguments.
9154   if (HasVAListArg)
9155     return true;
9156 
9157   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9158     return false;
9159 
9160   const Expr *Arg = getDataArg(argIndex);
9161   if (!Arg)
9162     return true;
9163 
9164   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9165 }
9166 
9167 static bool requiresParensToAddCast(const Expr *E) {
9168   // FIXME: We should have a general way to reason about operator
9169   // precedence and whether parens are actually needed here.
9170   // Take care of a few common cases where they aren't.
9171   const Expr *Inside = E->IgnoreImpCasts();
9172   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9173     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9174 
9175   switch (Inside->getStmtClass()) {
9176   case Stmt::ArraySubscriptExprClass:
9177   case Stmt::CallExprClass:
9178   case Stmt::CharacterLiteralClass:
9179   case Stmt::CXXBoolLiteralExprClass:
9180   case Stmt::DeclRefExprClass:
9181   case Stmt::FloatingLiteralClass:
9182   case Stmt::IntegerLiteralClass:
9183   case Stmt::MemberExprClass:
9184   case Stmt::ObjCArrayLiteralClass:
9185   case Stmt::ObjCBoolLiteralExprClass:
9186   case Stmt::ObjCBoxedExprClass:
9187   case Stmt::ObjCDictionaryLiteralClass:
9188   case Stmt::ObjCEncodeExprClass:
9189   case Stmt::ObjCIvarRefExprClass:
9190   case Stmt::ObjCMessageExprClass:
9191   case Stmt::ObjCPropertyRefExprClass:
9192   case Stmt::ObjCStringLiteralClass:
9193   case Stmt::ObjCSubscriptRefExprClass:
9194   case Stmt::ParenExprClass:
9195   case Stmt::StringLiteralClass:
9196   case Stmt::UnaryOperatorClass:
9197     return false;
9198   default:
9199     return true;
9200   }
9201 }
9202 
9203 static std::pair<QualType, StringRef>
9204 shouldNotPrintDirectly(const ASTContext &Context,
9205                        QualType IntendedTy,
9206                        const Expr *E) {
9207   // Use a 'while' to peel off layers of typedefs.
9208   QualType TyTy = IntendedTy;
9209   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9210     StringRef Name = UserTy->getDecl()->getName();
9211     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9212       .Case("CFIndex", Context.getNSIntegerType())
9213       .Case("NSInteger", Context.getNSIntegerType())
9214       .Case("NSUInteger", Context.getNSUIntegerType())
9215       .Case("SInt32", Context.IntTy)
9216       .Case("UInt32", Context.UnsignedIntTy)
9217       .Default(QualType());
9218 
9219     if (!CastTy.isNull())
9220       return std::make_pair(CastTy, Name);
9221 
9222     TyTy = UserTy->desugar();
9223   }
9224 
9225   // Strip parens if necessary.
9226   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9227     return shouldNotPrintDirectly(Context,
9228                                   PE->getSubExpr()->getType(),
9229                                   PE->getSubExpr());
9230 
9231   // If this is a conditional expression, then its result type is constructed
9232   // via usual arithmetic conversions and thus there might be no necessary
9233   // typedef sugar there.  Recurse to operands to check for NSInteger &
9234   // Co. usage condition.
9235   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9236     QualType TrueTy, FalseTy;
9237     StringRef TrueName, FalseName;
9238 
9239     std::tie(TrueTy, TrueName) =
9240       shouldNotPrintDirectly(Context,
9241                              CO->getTrueExpr()->getType(),
9242                              CO->getTrueExpr());
9243     std::tie(FalseTy, FalseName) =
9244       shouldNotPrintDirectly(Context,
9245                              CO->getFalseExpr()->getType(),
9246                              CO->getFalseExpr());
9247 
9248     if (TrueTy == FalseTy)
9249       return std::make_pair(TrueTy, TrueName);
9250     else if (TrueTy.isNull())
9251       return std::make_pair(FalseTy, FalseName);
9252     else if (FalseTy.isNull())
9253       return std::make_pair(TrueTy, TrueName);
9254   }
9255 
9256   return std::make_pair(QualType(), StringRef());
9257 }
9258 
9259 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9260 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9261 /// type do not count.
9262 static bool
9263 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9264   QualType From = ICE->getSubExpr()->getType();
9265   QualType To = ICE->getType();
9266   // It's an integer promotion if the destination type is the promoted
9267   // source type.
9268   if (ICE->getCastKind() == CK_IntegralCast &&
9269       From->isPromotableIntegerType() &&
9270       S.Context.getPromotedIntegerType(From) == To)
9271     return true;
9272   // Look through vector types, since we do default argument promotion for
9273   // those in OpenCL.
9274   if (const auto *VecTy = From->getAs<ExtVectorType>())
9275     From = VecTy->getElementType();
9276   if (const auto *VecTy = To->getAs<ExtVectorType>())
9277     To = VecTy->getElementType();
9278   // It's a floating promotion if the source type is a lower rank.
9279   return ICE->getCastKind() == CK_FloatingCast &&
9280          S.Context.getFloatingTypeOrder(From, To) < 0;
9281 }
9282 
9283 bool
9284 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9285                                     const char *StartSpecifier,
9286                                     unsigned SpecifierLen,
9287                                     const Expr *E) {
9288   using namespace analyze_format_string;
9289   using namespace analyze_printf;
9290 
9291   // Now type check the data expression that matches the
9292   // format specifier.
9293   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9294   if (!AT.isValid())
9295     return true;
9296 
9297   QualType ExprTy = E->getType();
9298   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9299     ExprTy = TET->getUnderlyingExpr()->getType();
9300   }
9301 
9302   // Diagnose attempts to print a boolean value as a character. Unlike other
9303   // -Wformat diagnostics, this is fine from a type perspective, but it still
9304   // doesn't make sense.
9305   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9306       E->isKnownToHaveBooleanValue()) {
9307     const CharSourceRange &CSR =
9308         getSpecifierRange(StartSpecifier, SpecifierLen);
9309     SmallString<4> FSString;
9310     llvm::raw_svector_ostream os(FSString);
9311     FS.toString(os);
9312     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9313                              << FSString,
9314                          E->getExprLoc(), false, CSR);
9315     return true;
9316   }
9317 
9318   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9319   if (Match == analyze_printf::ArgType::Match)
9320     return true;
9321 
9322   // Look through argument promotions for our error message's reported type.
9323   // This includes the integral and floating promotions, but excludes array
9324   // and function pointer decay (seeing that an argument intended to be a
9325   // string has type 'char [6]' is probably more confusing than 'char *') and
9326   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9327   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9328     if (isArithmeticArgumentPromotion(S, ICE)) {
9329       E = ICE->getSubExpr();
9330       ExprTy = E->getType();
9331 
9332       // Check if we didn't match because of an implicit cast from a 'char'
9333       // or 'short' to an 'int'.  This is done because printf is a varargs
9334       // function.
9335       if (ICE->getType() == S.Context.IntTy ||
9336           ICE->getType() == S.Context.UnsignedIntTy) {
9337         // All further checking is done on the subexpression
9338         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9339             AT.matchesType(S.Context, ExprTy);
9340         if (ImplicitMatch == analyze_printf::ArgType::Match)
9341           return true;
9342         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9343             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9344           Match = ImplicitMatch;
9345       }
9346     }
9347   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9348     // Special case for 'a', which has type 'int' in C.
9349     // Note, however, that we do /not/ want to treat multibyte constants like
9350     // 'MooV' as characters! This form is deprecated but still exists. In
9351     // addition, don't treat expressions as of type 'char' if one byte length
9352     // modifier is provided.
9353     if (ExprTy == S.Context.IntTy &&
9354         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9355       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9356         ExprTy = S.Context.CharTy;
9357   }
9358 
9359   // Look through enums to their underlying type.
9360   bool IsEnum = false;
9361   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9362     ExprTy = EnumTy->getDecl()->getIntegerType();
9363     IsEnum = true;
9364   }
9365 
9366   // %C in an Objective-C context prints a unichar, not a wchar_t.
9367   // If the argument is an integer of some kind, believe the %C and suggest
9368   // a cast instead of changing the conversion specifier.
9369   QualType IntendedTy = ExprTy;
9370   if (isObjCContext() &&
9371       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9372     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9373         !ExprTy->isCharType()) {
9374       // 'unichar' is defined as a typedef of unsigned short, but we should
9375       // prefer using the typedef if it is visible.
9376       IntendedTy = S.Context.UnsignedShortTy;
9377 
9378       // While we are here, check if the value is an IntegerLiteral that happens
9379       // to be within the valid range.
9380       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9381         const llvm::APInt &V = IL->getValue();
9382         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9383           return true;
9384       }
9385 
9386       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9387                           Sema::LookupOrdinaryName);
9388       if (S.LookupName(Result, S.getCurScope())) {
9389         NamedDecl *ND = Result.getFoundDecl();
9390         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9391           if (TD->getUnderlyingType() == IntendedTy)
9392             IntendedTy = S.Context.getTypedefType(TD);
9393       }
9394     }
9395   }
9396 
9397   // Special-case some of Darwin's platform-independence types by suggesting
9398   // casts to primitive types that are known to be large enough.
9399   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9400   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9401     QualType CastTy;
9402     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9403     if (!CastTy.isNull()) {
9404       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9405       // (long in ASTContext). Only complain to pedants.
9406       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9407           (AT.isSizeT() || AT.isPtrdiffT()) &&
9408           AT.matchesType(S.Context, CastTy))
9409         Match = ArgType::NoMatchPedantic;
9410       IntendedTy = CastTy;
9411       ShouldNotPrintDirectly = true;
9412     }
9413   }
9414 
9415   // We may be able to offer a FixItHint if it is a supported type.
9416   PrintfSpecifier fixedFS = FS;
9417   bool Success =
9418       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9419 
9420   if (Success) {
9421     // Get the fix string from the fixed format specifier
9422     SmallString<16> buf;
9423     llvm::raw_svector_ostream os(buf);
9424     fixedFS.toString(os);
9425 
9426     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9427 
9428     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9429       unsigned Diag;
9430       switch (Match) {
9431       case ArgType::Match: llvm_unreachable("expected non-matching");
9432       case ArgType::NoMatchPedantic:
9433         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9434         break;
9435       case ArgType::NoMatchTypeConfusion:
9436         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9437         break;
9438       case ArgType::NoMatch:
9439         Diag = diag::warn_format_conversion_argument_type_mismatch;
9440         break;
9441       }
9442 
9443       // In this case, the specifier is wrong and should be changed to match
9444       // the argument.
9445       EmitFormatDiagnostic(S.PDiag(Diag)
9446                                << AT.getRepresentativeTypeName(S.Context)
9447                                << IntendedTy << IsEnum << E->getSourceRange(),
9448                            E->getBeginLoc(),
9449                            /*IsStringLocation*/ false, SpecRange,
9450                            FixItHint::CreateReplacement(SpecRange, os.str()));
9451     } else {
9452       // The canonical type for formatting this value is different from the
9453       // actual type of the expression. (This occurs, for example, with Darwin's
9454       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9455       // should be printed as 'long' for 64-bit compatibility.)
9456       // Rather than emitting a normal format/argument mismatch, we want to
9457       // add a cast to the recommended type (and correct the format string
9458       // if necessary).
9459       SmallString<16> CastBuf;
9460       llvm::raw_svector_ostream CastFix(CastBuf);
9461       CastFix << "(";
9462       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9463       CastFix << ")";
9464 
9465       SmallVector<FixItHint,4> Hints;
9466       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9467         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9468 
9469       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9470         // If there's already a cast present, just replace it.
9471         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9472         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9473 
9474       } else if (!requiresParensToAddCast(E)) {
9475         // If the expression has high enough precedence,
9476         // just write the C-style cast.
9477         Hints.push_back(
9478             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9479       } else {
9480         // Otherwise, add parens around the expression as well as the cast.
9481         CastFix << "(";
9482         Hints.push_back(
9483             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9484 
9485         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9486         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9487       }
9488 
9489       if (ShouldNotPrintDirectly) {
9490         // The expression has a type that should not be printed directly.
9491         // We extract the name from the typedef because we don't want to show
9492         // the underlying type in the diagnostic.
9493         StringRef Name;
9494         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9495           Name = TypedefTy->getDecl()->getName();
9496         else
9497           Name = CastTyName;
9498         unsigned Diag = Match == ArgType::NoMatchPedantic
9499                             ? diag::warn_format_argument_needs_cast_pedantic
9500                             : diag::warn_format_argument_needs_cast;
9501         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9502                                            << E->getSourceRange(),
9503                              E->getBeginLoc(), /*IsStringLocation=*/false,
9504                              SpecRange, Hints);
9505       } else {
9506         // In this case, the expression could be printed using a different
9507         // specifier, but we've decided that the specifier is probably correct
9508         // and we should cast instead. Just use the normal warning message.
9509         EmitFormatDiagnostic(
9510             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9511                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9512                 << E->getSourceRange(),
9513             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9514       }
9515     }
9516   } else {
9517     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9518                                                    SpecifierLen);
9519     // Since the warning for passing non-POD types to variadic functions
9520     // was deferred until now, we emit a warning for non-POD
9521     // arguments here.
9522     switch (S.isValidVarArgType(ExprTy)) {
9523     case Sema::VAK_Valid:
9524     case Sema::VAK_ValidInCXX11: {
9525       unsigned Diag;
9526       switch (Match) {
9527       case ArgType::Match: llvm_unreachable("expected non-matching");
9528       case ArgType::NoMatchPedantic:
9529         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9530         break;
9531       case ArgType::NoMatchTypeConfusion:
9532         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9533         break;
9534       case ArgType::NoMatch:
9535         Diag = diag::warn_format_conversion_argument_type_mismatch;
9536         break;
9537       }
9538 
9539       EmitFormatDiagnostic(
9540           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9541                         << IsEnum << CSR << E->getSourceRange(),
9542           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9543       break;
9544     }
9545     case Sema::VAK_Undefined:
9546     case Sema::VAK_MSVCUndefined:
9547       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9548                                << S.getLangOpts().CPlusPlus11 << ExprTy
9549                                << CallType
9550                                << AT.getRepresentativeTypeName(S.Context) << CSR
9551                                << E->getSourceRange(),
9552                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9553       checkForCStrMembers(AT, E);
9554       break;
9555 
9556     case Sema::VAK_Invalid:
9557       if (ExprTy->isObjCObjectType())
9558         EmitFormatDiagnostic(
9559             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9560                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9561                 << AT.getRepresentativeTypeName(S.Context) << CSR
9562                 << E->getSourceRange(),
9563             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9564       else
9565         // FIXME: If this is an initializer list, suggest removing the braces
9566         // or inserting a cast to the target type.
9567         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9568             << isa<InitListExpr>(E) << ExprTy << CallType
9569             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9570       break;
9571     }
9572 
9573     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9574            "format string specifier index out of range");
9575     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9576   }
9577 
9578   return true;
9579 }
9580 
9581 //===--- CHECK: Scanf format string checking ------------------------------===//
9582 
9583 namespace {
9584 
9585 class CheckScanfHandler : public CheckFormatHandler {
9586 public:
9587   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9588                     const Expr *origFormatExpr, Sema::FormatStringType type,
9589                     unsigned firstDataArg, unsigned numDataArgs,
9590                     const char *beg, bool hasVAListArg,
9591                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9592                     bool inFunctionCall, Sema::VariadicCallType CallType,
9593                     llvm::SmallBitVector &CheckedVarArgs,
9594                     UncoveredArgHandler &UncoveredArg)
9595       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9596                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9597                            inFunctionCall, CallType, CheckedVarArgs,
9598                            UncoveredArg) {}
9599 
9600   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9601                             const char *startSpecifier,
9602                             unsigned specifierLen) override;
9603 
9604   bool HandleInvalidScanfConversionSpecifier(
9605           const analyze_scanf::ScanfSpecifier &FS,
9606           const char *startSpecifier,
9607           unsigned specifierLen) override;
9608 
9609   void HandleIncompleteScanList(const char *start, const char *end) override;
9610 };
9611 
9612 } // namespace
9613 
9614 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9615                                                  const char *end) {
9616   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9617                        getLocationOfByte(end), /*IsStringLocation*/true,
9618                        getSpecifierRange(start, end - start));
9619 }
9620 
9621 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9622                                         const analyze_scanf::ScanfSpecifier &FS,
9623                                         const char *startSpecifier,
9624                                         unsigned specifierLen) {
9625   const analyze_scanf::ScanfConversionSpecifier &CS =
9626     FS.getConversionSpecifier();
9627 
9628   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9629                                           getLocationOfByte(CS.getStart()),
9630                                           startSpecifier, specifierLen,
9631                                           CS.getStart(), CS.getLength());
9632 }
9633 
9634 bool CheckScanfHandler::HandleScanfSpecifier(
9635                                        const analyze_scanf::ScanfSpecifier &FS,
9636                                        const char *startSpecifier,
9637                                        unsigned specifierLen) {
9638   using namespace analyze_scanf;
9639   using namespace analyze_format_string;
9640 
9641   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9642 
9643   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9644   // be used to decide if we are using positional arguments consistently.
9645   if (FS.consumesDataArgument()) {
9646     if (atFirstArg) {
9647       atFirstArg = false;
9648       usesPositionalArgs = FS.usesPositionalArg();
9649     }
9650     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9651       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9652                                         startSpecifier, specifierLen);
9653       return false;
9654     }
9655   }
9656 
9657   // Check if the field with is non-zero.
9658   const OptionalAmount &Amt = FS.getFieldWidth();
9659   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9660     if (Amt.getConstantAmount() == 0) {
9661       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9662                                                    Amt.getConstantLength());
9663       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9664                            getLocationOfByte(Amt.getStart()),
9665                            /*IsStringLocation*/true, R,
9666                            FixItHint::CreateRemoval(R));
9667     }
9668   }
9669 
9670   if (!FS.consumesDataArgument()) {
9671     // FIXME: Technically specifying a precision or field width here
9672     // makes no sense.  Worth issuing a warning at some point.
9673     return true;
9674   }
9675 
9676   // Consume the argument.
9677   unsigned argIndex = FS.getArgIndex();
9678   if (argIndex < NumDataArgs) {
9679       // The check to see if the argIndex is valid will come later.
9680       // We set the bit here because we may exit early from this
9681       // function if we encounter some other error.
9682     CoveredArgs.set(argIndex);
9683   }
9684 
9685   // Check the length modifier is valid with the given conversion specifier.
9686   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9687                                  S.getLangOpts()))
9688     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9689                                 diag::warn_format_nonsensical_length);
9690   else if (!FS.hasStandardLengthModifier())
9691     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9692   else if (!FS.hasStandardLengthConversionCombination())
9693     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9694                                 diag::warn_format_non_standard_conversion_spec);
9695 
9696   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9697     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9698 
9699   // The remaining checks depend on the data arguments.
9700   if (HasVAListArg)
9701     return true;
9702 
9703   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9704     return false;
9705 
9706   // Check that the argument type matches the format specifier.
9707   const Expr *Ex = getDataArg(argIndex);
9708   if (!Ex)
9709     return true;
9710 
9711   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9712 
9713   if (!AT.isValid()) {
9714     return true;
9715   }
9716 
9717   analyze_format_string::ArgType::MatchKind Match =
9718       AT.matchesType(S.Context, Ex->getType());
9719   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9720   if (Match == analyze_format_string::ArgType::Match)
9721     return true;
9722 
9723   ScanfSpecifier fixedFS = FS;
9724   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9725                                  S.getLangOpts(), S.Context);
9726 
9727   unsigned Diag =
9728       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9729                : diag::warn_format_conversion_argument_type_mismatch;
9730 
9731   if (Success) {
9732     // Get the fix string from the fixed format specifier.
9733     SmallString<128> buf;
9734     llvm::raw_svector_ostream os(buf);
9735     fixedFS.toString(os);
9736 
9737     EmitFormatDiagnostic(
9738         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9739                       << Ex->getType() << false << Ex->getSourceRange(),
9740         Ex->getBeginLoc(),
9741         /*IsStringLocation*/ false,
9742         getSpecifierRange(startSpecifier, specifierLen),
9743         FixItHint::CreateReplacement(
9744             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9745   } else {
9746     EmitFormatDiagnostic(S.PDiag(Diag)
9747                              << AT.getRepresentativeTypeName(S.Context)
9748                              << Ex->getType() << false << Ex->getSourceRange(),
9749                          Ex->getBeginLoc(),
9750                          /*IsStringLocation*/ false,
9751                          getSpecifierRange(startSpecifier, specifierLen));
9752   }
9753 
9754   return true;
9755 }
9756 
9757 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9758                               const Expr *OrigFormatExpr,
9759                               ArrayRef<const Expr *> Args,
9760                               bool HasVAListArg, unsigned format_idx,
9761                               unsigned firstDataArg,
9762                               Sema::FormatStringType Type,
9763                               bool inFunctionCall,
9764                               Sema::VariadicCallType CallType,
9765                               llvm::SmallBitVector &CheckedVarArgs,
9766                               UncoveredArgHandler &UncoveredArg,
9767                               bool IgnoreStringsWithoutSpecifiers) {
9768   // CHECK: is the format string a wide literal?
9769   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9770     CheckFormatHandler::EmitFormatDiagnostic(
9771         S, inFunctionCall, Args[format_idx],
9772         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9773         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9774     return;
9775   }
9776 
9777   // Str - The format string.  NOTE: this is NOT null-terminated!
9778   StringRef StrRef = FExpr->getString();
9779   const char *Str = StrRef.data();
9780   // Account for cases where the string literal is truncated in a declaration.
9781   const ConstantArrayType *T =
9782     S.Context.getAsConstantArrayType(FExpr->getType());
9783   assert(T && "String literal not of constant array type!");
9784   size_t TypeSize = T->getSize().getZExtValue();
9785   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9786   const unsigned numDataArgs = Args.size() - firstDataArg;
9787 
9788   if (IgnoreStringsWithoutSpecifiers &&
9789       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9790           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9791     return;
9792 
9793   // Emit a warning if the string literal is truncated and does not contain an
9794   // embedded null character.
9795   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9796     CheckFormatHandler::EmitFormatDiagnostic(
9797         S, inFunctionCall, Args[format_idx],
9798         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9799         FExpr->getBeginLoc(),
9800         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9801     return;
9802   }
9803 
9804   // CHECK: empty format string?
9805   if (StrLen == 0 && numDataArgs > 0) {
9806     CheckFormatHandler::EmitFormatDiagnostic(
9807         S, inFunctionCall, Args[format_idx],
9808         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9809         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9810     return;
9811   }
9812 
9813   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9814       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9815       Type == Sema::FST_OSTrace) {
9816     CheckPrintfHandler H(
9817         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9818         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9819         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9820         CheckedVarArgs, UncoveredArg);
9821 
9822     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9823                                                   S.getLangOpts(),
9824                                                   S.Context.getTargetInfo(),
9825                                             Type == Sema::FST_FreeBSDKPrintf))
9826       H.DoneProcessing();
9827   } else if (Type == Sema::FST_Scanf) {
9828     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9829                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9830                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9831 
9832     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9833                                                  S.getLangOpts(),
9834                                                  S.Context.getTargetInfo()))
9835       H.DoneProcessing();
9836   } // TODO: handle other formats
9837 }
9838 
9839 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9840   // Str - The format string.  NOTE: this is NOT null-terminated!
9841   StringRef StrRef = FExpr->getString();
9842   const char *Str = StrRef.data();
9843   // Account for cases where the string literal is truncated in a declaration.
9844   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9845   assert(T && "String literal not of constant array type!");
9846   size_t TypeSize = T->getSize().getZExtValue();
9847   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9848   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9849                                                          getLangOpts(),
9850                                                          Context.getTargetInfo());
9851 }
9852 
9853 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9854 
9855 // Returns the related absolute value function that is larger, of 0 if one
9856 // does not exist.
9857 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9858   switch (AbsFunction) {
9859   default:
9860     return 0;
9861 
9862   case Builtin::BI__builtin_abs:
9863     return Builtin::BI__builtin_labs;
9864   case Builtin::BI__builtin_labs:
9865     return Builtin::BI__builtin_llabs;
9866   case Builtin::BI__builtin_llabs:
9867     return 0;
9868 
9869   case Builtin::BI__builtin_fabsf:
9870     return Builtin::BI__builtin_fabs;
9871   case Builtin::BI__builtin_fabs:
9872     return Builtin::BI__builtin_fabsl;
9873   case Builtin::BI__builtin_fabsl:
9874     return 0;
9875 
9876   case Builtin::BI__builtin_cabsf:
9877     return Builtin::BI__builtin_cabs;
9878   case Builtin::BI__builtin_cabs:
9879     return Builtin::BI__builtin_cabsl;
9880   case Builtin::BI__builtin_cabsl:
9881     return 0;
9882 
9883   case Builtin::BIabs:
9884     return Builtin::BIlabs;
9885   case Builtin::BIlabs:
9886     return Builtin::BIllabs;
9887   case Builtin::BIllabs:
9888     return 0;
9889 
9890   case Builtin::BIfabsf:
9891     return Builtin::BIfabs;
9892   case Builtin::BIfabs:
9893     return Builtin::BIfabsl;
9894   case Builtin::BIfabsl:
9895     return 0;
9896 
9897   case Builtin::BIcabsf:
9898    return Builtin::BIcabs;
9899   case Builtin::BIcabs:
9900     return Builtin::BIcabsl;
9901   case Builtin::BIcabsl:
9902     return 0;
9903   }
9904 }
9905 
9906 // Returns the argument type of the absolute value function.
9907 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9908                                              unsigned AbsType) {
9909   if (AbsType == 0)
9910     return QualType();
9911 
9912   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9913   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9914   if (Error != ASTContext::GE_None)
9915     return QualType();
9916 
9917   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9918   if (!FT)
9919     return QualType();
9920 
9921   if (FT->getNumParams() != 1)
9922     return QualType();
9923 
9924   return FT->getParamType(0);
9925 }
9926 
9927 // Returns the best absolute value function, or zero, based on type and
9928 // current absolute value function.
9929 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9930                                    unsigned AbsFunctionKind) {
9931   unsigned BestKind = 0;
9932   uint64_t ArgSize = Context.getTypeSize(ArgType);
9933   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9934        Kind = getLargerAbsoluteValueFunction(Kind)) {
9935     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9936     if (Context.getTypeSize(ParamType) >= ArgSize) {
9937       if (BestKind == 0)
9938         BestKind = Kind;
9939       else if (Context.hasSameType(ParamType, ArgType)) {
9940         BestKind = Kind;
9941         break;
9942       }
9943     }
9944   }
9945   return BestKind;
9946 }
9947 
9948 enum AbsoluteValueKind {
9949   AVK_Integer,
9950   AVK_Floating,
9951   AVK_Complex
9952 };
9953 
9954 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9955   if (T->isIntegralOrEnumerationType())
9956     return AVK_Integer;
9957   if (T->isRealFloatingType())
9958     return AVK_Floating;
9959   if (T->isAnyComplexType())
9960     return AVK_Complex;
9961 
9962   llvm_unreachable("Type not integer, floating, or complex");
9963 }
9964 
9965 // Changes the absolute value function to a different type.  Preserves whether
9966 // the function is a builtin.
9967 static unsigned changeAbsFunction(unsigned AbsKind,
9968                                   AbsoluteValueKind ValueKind) {
9969   switch (ValueKind) {
9970   case AVK_Integer:
9971     switch (AbsKind) {
9972     default:
9973       return 0;
9974     case Builtin::BI__builtin_fabsf:
9975     case Builtin::BI__builtin_fabs:
9976     case Builtin::BI__builtin_fabsl:
9977     case Builtin::BI__builtin_cabsf:
9978     case Builtin::BI__builtin_cabs:
9979     case Builtin::BI__builtin_cabsl:
9980       return Builtin::BI__builtin_abs;
9981     case Builtin::BIfabsf:
9982     case Builtin::BIfabs:
9983     case Builtin::BIfabsl:
9984     case Builtin::BIcabsf:
9985     case Builtin::BIcabs:
9986     case Builtin::BIcabsl:
9987       return Builtin::BIabs;
9988     }
9989   case AVK_Floating:
9990     switch (AbsKind) {
9991     default:
9992       return 0;
9993     case Builtin::BI__builtin_abs:
9994     case Builtin::BI__builtin_labs:
9995     case Builtin::BI__builtin_llabs:
9996     case Builtin::BI__builtin_cabsf:
9997     case Builtin::BI__builtin_cabs:
9998     case Builtin::BI__builtin_cabsl:
9999       return Builtin::BI__builtin_fabsf;
10000     case Builtin::BIabs:
10001     case Builtin::BIlabs:
10002     case Builtin::BIllabs:
10003     case Builtin::BIcabsf:
10004     case Builtin::BIcabs:
10005     case Builtin::BIcabsl:
10006       return Builtin::BIfabsf;
10007     }
10008   case AVK_Complex:
10009     switch (AbsKind) {
10010     default:
10011       return 0;
10012     case Builtin::BI__builtin_abs:
10013     case Builtin::BI__builtin_labs:
10014     case Builtin::BI__builtin_llabs:
10015     case Builtin::BI__builtin_fabsf:
10016     case Builtin::BI__builtin_fabs:
10017     case Builtin::BI__builtin_fabsl:
10018       return Builtin::BI__builtin_cabsf;
10019     case Builtin::BIabs:
10020     case Builtin::BIlabs:
10021     case Builtin::BIllabs:
10022     case Builtin::BIfabsf:
10023     case Builtin::BIfabs:
10024     case Builtin::BIfabsl:
10025       return Builtin::BIcabsf;
10026     }
10027   }
10028   llvm_unreachable("Unable to convert function");
10029 }
10030 
10031 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
10032   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
10033   if (!FnInfo)
10034     return 0;
10035 
10036   switch (FDecl->getBuiltinID()) {
10037   default:
10038     return 0;
10039   case Builtin::BI__builtin_abs:
10040   case Builtin::BI__builtin_fabs:
10041   case Builtin::BI__builtin_fabsf:
10042   case Builtin::BI__builtin_fabsl:
10043   case Builtin::BI__builtin_labs:
10044   case Builtin::BI__builtin_llabs:
10045   case Builtin::BI__builtin_cabs:
10046   case Builtin::BI__builtin_cabsf:
10047   case Builtin::BI__builtin_cabsl:
10048   case Builtin::BIabs:
10049   case Builtin::BIlabs:
10050   case Builtin::BIllabs:
10051   case Builtin::BIfabs:
10052   case Builtin::BIfabsf:
10053   case Builtin::BIfabsl:
10054   case Builtin::BIcabs:
10055   case Builtin::BIcabsf:
10056   case Builtin::BIcabsl:
10057     return FDecl->getBuiltinID();
10058   }
10059   llvm_unreachable("Unknown Builtin type");
10060 }
10061 
10062 // If the replacement is valid, emit a note with replacement function.
10063 // Additionally, suggest including the proper header if not already included.
10064 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
10065                             unsigned AbsKind, QualType ArgType) {
10066   bool EmitHeaderHint = true;
10067   const char *HeaderName = nullptr;
10068   const char *FunctionName = nullptr;
10069   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
10070     FunctionName = "std::abs";
10071     if (ArgType->isIntegralOrEnumerationType()) {
10072       HeaderName = "cstdlib";
10073     } else if (ArgType->isRealFloatingType()) {
10074       HeaderName = "cmath";
10075     } else {
10076       llvm_unreachable("Invalid Type");
10077     }
10078 
10079     // Lookup all std::abs
10080     if (NamespaceDecl *Std = S.getStdNamespace()) {
10081       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
10082       R.suppressDiagnostics();
10083       S.LookupQualifiedName(R, Std);
10084 
10085       for (const auto *I : R) {
10086         const FunctionDecl *FDecl = nullptr;
10087         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
10088           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
10089         } else {
10090           FDecl = dyn_cast<FunctionDecl>(I);
10091         }
10092         if (!FDecl)
10093           continue;
10094 
10095         // Found std::abs(), check that they are the right ones.
10096         if (FDecl->getNumParams() != 1)
10097           continue;
10098 
10099         // Check that the parameter type can handle the argument.
10100         QualType ParamType = FDecl->getParamDecl(0)->getType();
10101         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10102             S.Context.getTypeSize(ArgType) <=
10103                 S.Context.getTypeSize(ParamType)) {
10104           // Found a function, don't need the header hint.
10105           EmitHeaderHint = false;
10106           break;
10107         }
10108       }
10109     }
10110   } else {
10111     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10112     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10113 
10114     if (HeaderName) {
10115       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10116       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10117       R.suppressDiagnostics();
10118       S.LookupName(R, S.getCurScope());
10119 
10120       if (R.isSingleResult()) {
10121         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10122         if (FD && FD->getBuiltinID() == AbsKind) {
10123           EmitHeaderHint = false;
10124         } else {
10125           return;
10126         }
10127       } else if (!R.empty()) {
10128         return;
10129       }
10130     }
10131   }
10132 
10133   S.Diag(Loc, diag::note_replace_abs_function)
10134       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10135 
10136   if (!HeaderName)
10137     return;
10138 
10139   if (!EmitHeaderHint)
10140     return;
10141 
10142   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10143                                                     << FunctionName;
10144 }
10145 
10146 template <std::size_t StrLen>
10147 static bool IsStdFunction(const FunctionDecl *FDecl,
10148                           const char (&Str)[StrLen]) {
10149   if (!FDecl)
10150     return false;
10151   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10152     return false;
10153   if (!FDecl->isInStdNamespace())
10154     return false;
10155 
10156   return true;
10157 }
10158 
10159 // Warn when using the wrong abs() function.
10160 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10161                                       const FunctionDecl *FDecl) {
10162   if (Call->getNumArgs() != 1)
10163     return;
10164 
10165   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10166   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10167   if (AbsKind == 0 && !IsStdAbs)
10168     return;
10169 
10170   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10171   QualType ParamType = Call->getArg(0)->getType();
10172 
10173   // Unsigned types cannot be negative.  Suggest removing the absolute value
10174   // function call.
10175   if (ArgType->isUnsignedIntegerType()) {
10176     const char *FunctionName =
10177         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10178     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10179     Diag(Call->getExprLoc(), diag::note_remove_abs)
10180         << FunctionName
10181         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10182     return;
10183   }
10184 
10185   // Taking the absolute value of a pointer is very suspicious, they probably
10186   // wanted to index into an array, dereference a pointer, call a function, etc.
10187   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10188     unsigned DiagType = 0;
10189     if (ArgType->isFunctionType())
10190       DiagType = 1;
10191     else if (ArgType->isArrayType())
10192       DiagType = 2;
10193 
10194     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10195     return;
10196   }
10197 
10198   // std::abs has overloads which prevent most of the absolute value problems
10199   // from occurring.
10200   if (IsStdAbs)
10201     return;
10202 
10203   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10204   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10205 
10206   // The argument and parameter are the same kind.  Check if they are the right
10207   // size.
10208   if (ArgValueKind == ParamValueKind) {
10209     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10210       return;
10211 
10212     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10213     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10214         << FDecl << ArgType << ParamType;
10215 
10216     if (NewAbsKind == 0)
10217       return;
10218 
10219     emitReplacement(*this, Call->getExprLoc(),
10220                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10221     return;
10222   }
10223 
10224   // ArgValueKind != ParamValueKind
10225   // The wrong type of absolute value function was used.  Attempt to find the
10226   // proper one.
10227   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10228   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10229   if (NewAbsKind == 0)
10230     return;
10231 
10232   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10233       << FDecl << ParamValueKind << ArgValueKind;
10234 
10235   emitReplacement(*this, Call->getExprLoc(),
10236                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10237 }
10238 
10239 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10240 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10241                                 const FunctionDecl *FDecl) {
10242   if (!Call || !FDecl) return;
10243 
10244   // Ignore template specializations and macros.
10245   if (inTemplateInstantiation()) return;
10246   if (Call->getExprLoc().isMacroID()) return;
10247 
10248   // Only care about the one template argument, two function parameter std::max
10249   if (Call->getNumArgs() != 2) return;
10250   if (!IsStdFunction(FDecl, "max")) return;
10251   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10252   if (!ArgList) return;
10253   if (ArgList->size() != 1) return;
10254 
10255   // Check that template type argument is unsigned integer.
10256   const auto& TA = ArgList->get(0);
10257   if (TA.getKind() != TemplateArgument::Type) return;
10258   QualType ArgType = TA.getAsType();
10259   if (!ArgType->isUnsignedIntegerType()) return;
10260 
10261   // See if either argument is a literal zero.
10262   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10263     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10264     if (!MTE) return false;
10265     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10266     if (!Num) return false;
10267     if (Num->getValue() != 0) return false;
10268     return true;
10269   };
10270 
10271   const Expr *FirstArg = Call->getArg(0);
10272   const Expr *SecondArg = Call->getArg(1);
10273   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10274   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10275 
10276   // Only warn when exactly one argument is zero.
10277   if (IsFirstArgZero == IsSecondArgZero) return;
10278 
10279   SourceRange FirstRange = FirstArg->getSourceRange();
10280   SourceRange SecondRange = SecondArg->getSourceRange();
10281 
10282   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10283 
10284   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10285       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10286 
10287   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10288   SourceRange RemovalRange;
10289   if (IsFirstArgZero) {
10290     RemovalRange = SourceRange(FirstRange.getBegin(),
10291                                SecondRange.getBegin().getLocWithOffset(-1));
10292   } else {
10293     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10294                                SecondRange.getEnd());
10295   }
10296 
10297   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10298         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10299         << FixItHint::CreateRemoval(RemovalRange);
10300 }
10301 
10302 //===--- CHECK: Standard memory functions ---------------------------------===//
10303 
10304 /// Takes the expression passed to the size_t parameter of functions
10305 /// such as memcmp, strncat, etc and warns if it's a comparison.
10306 ///
10307 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10308 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10309                                            IdentifierInfo *FnName,
10310                                            SourceLocation FnLoc,
10311                                            SourceLocation RParenLoc) {
10312   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10313   if (!Size)
10314     return false;
10315 
10316   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10317   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10318     return false;
10319 
10320   SourceRange SizeRange = Size->getSourceRange();
10321   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10322       << SizeRange << FnName;
10323   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10324       << FnName
10325       << FixItHint::CreateInsertion(
10326              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10327       << FixItHint::CreateRemoval(RParenLoc);
10328   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10329       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10330       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10331                                     ")");
10332 
10333   return true;
10334 }
10335 
10336 /// Determine whether the given type is or contains a dynamic class type
10337 /// (e.g., whether it has a vtable).
10338 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10339                                                      bool &IsContained) {
10340   // Look through array types while ignoring qualifiers.
10341   const Type *Ty = T->getBaseElementTypeUnsafe();
10342   IsContained = false;
10343 
10344   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10345   RD = RD ? RD->getDefinition() : nullptr;
10346   if (!RD || RD->isInvalidDecl())
10347     return nullptr;
10348 
10349   if (RD->isDynamicClass())
10350     return RD;
10351 
10352   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10353   // It's impossible for a class to transitively contain itself by value, so
10354   // infinite recursion is impossible.
10355   for (auto *FD : RD->fields()) {
10356     bool SubContained;
10357     if (const CXXRecordDecl *ContainedRD =
10358             getContainedDynamicClass(FD->getType(), SubContained)) {
10359       IsContained = true;
10360       return ContainedRD;
10361     }
10362   }
10363 
10364   return nullptr;
10365 }
10366 
10367 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10368   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10369     if (Unary->getKind() == UETT_SizeOf)
10370       return Unary;
10371   return nullptr;
10372 }
10373 
10374 /// If E is a sizeof expression, returns its argument expression,
10375 /// otherwise returns NULL.
10376 static const Expr *getSizeOfExprArg(const Expr *E) {
10377   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10378     if (!SizeOf->isArgumentType())
10379       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10380   return nullptr;
10381 }
10382 
10383 /// If E is a sizeof expression, returns its argument type.
10384 static QualType getSizeOfArgType(const Expr *E) {
10385   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10386     return SizeOf->getTypeOfArgument();
10387   return QualType();
10388 }
10389 
10390 namespace {
10391 
10392 struct SearchNonTrivialToInitializeField
10393     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10394   using Super =
10395       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10396 
10397   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10398 
10399   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10400                      SourceLocation SL) {
10401     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10402       asDerived().visitArray(PDIK, AT, SL);
10403       return;
10404     }
10405 
10406     Super::visitWithKind(PDIK, FT, SL);
10407   }
10408 
10409   void visitARCStrong(QualType FT, SourceLocation SL) {
10410     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10411   }
10412   void visitARCWeak(QualType FT, SourceLocation SL) {
10413     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10414   }
10415   void visitStruct(QualType FT, SourceLocation SL) {
10416     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10417       visit(FD->getType(), FD->getLocation());
10418   }
10419   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10420                   const ArrayType *AT, SourceLocation SL) {
10421     visit(getContext().getBaseElementType(AT), SL);
10422   }
10423   void visitTrivial(QualType FT, SourceLocation SL) {}
10424 
10425   static void diag(QualType RT, const Expr *E, Sema &S) {
10426     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10427   }
10428 
10429   ASTContext &getContext() { return S.getASTContext(); }
10430 
10431   const Expr *E;
10432   Sema &S;
10433 };
10434 
10435 struct SearchNonTrivialToCopyField
10436     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10437   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10438 
10439   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10440 
10441   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10442                      SourceLocation SL) {
10443     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10444       asDerived().visitArray(PCK, AT, SL);
10445       return;
10446     }
10447 
10448     Super::visitWithKind(PCK, FT, SL);
10449   }
10450 
10451   void visitARCStrong(QualType FT, SourceLocation SL) {
10452     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10453   }
10454   void visitARCWeak(QualType FT, SourceLocation SL) {
10455     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10456   }
10457   void visitStruct(QualType FT, SourceLocation SL) {
10458     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10459       visit(FD->getType(), FD->getLocation());
10460   }
10461   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10462                   SourceLocation SL) {
10463     visit(getContext().getBaseElementType(AT), SL);
10464   }
10465   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10466                 SourceLocation SL) {}
10467   void visitTrivial(QualType FT, SourceLocation SL) {}
10468   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10469 
10470   static void diag(QualType RT, const Expr *E, Sema &S) {
10471     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10472   }
10473 
10474   ASTContext &getContext() { return S.getASTContext(); }
10475 
10476   const Expr *E;
10477   Sema &S;
10478 };
10479 
10480 }
10481 
10482 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10483 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10484   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10485 
10486   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10487     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10488       return false;
10489 
10490     return doesExprLikelyComputeSize(BO->getLHS()) ||
10491            doesExprLikelyComputeSize(BO->getRHS());
10492   }
10493 
10494   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10495 }
10496 
10497 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10498 ///
10499 /// \code
10500 ///   #define MACRO 0
10501 ///   foo(MACRO);
10502 ///   foo(0);
10503 /// \endcode
10504 ///
10505 /// This should return true for the first call to foo, but not for the second
10506 /// (regardless of whether foo is a macro or function).
10507 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10508                                         SourceLocation CallLoc,
10509                                         SourceLocation ArgLoc) {
10510   if (!CallLoc.isMacroID())
10511     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10512 
10513   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10514          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10515 }
10516 
10517 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10518 /// last two arguments transposed.
10519 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10520   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10521     return;
10522 
10523   const Expr *SizeArg =
10524     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10525 
10526   auto isLiteralZero = [](const Expr *E) {
10527     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10528   };
10529 
10530   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10531   SourceLocation CallLoc = Call->getRParenLoc();
10532   SourceManager &SM = S.getSourceManager();
10533   if (isLiteralZero(SizeArg) &&
10534       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10535 
10536     SourceLocation DiagLoc = SizeArg->getExprLoc();
10537 
10538     // Some platforms #define bzero to __builtin_memset. See if this is the
10539     // case, and if so, emit a better diagnostic.
10540     if (BId == Builtin::BIbzero ||
10541         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10542                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10543       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10544       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10545     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10546       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10547       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10548     }
10549     return;
10550   }
10551 
10552   // If the second argument to a memset is a sizeof expression and the third
10553   // isn't, this is also likely an error. This should catch
10554   // 'memset(buf, sizeof(buf), 0xff)'.
10555   if (BId == Builtin::BImemset &&
10556       doesExprLikelyComputeSize(Call->getArg(1)) &&
10557       !doesExprLikelyComputeSize(Call->getArg(2))) {
10558     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10559     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10560     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10561     return;
10562   }
10563 }
10564 
10565 /// Check for dangerous or invalid arguments to memset().
10566 ///
10567 /// This issues warnings on known problematic, dangerous or unspecified
10568 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10569 /// function calls.
10570 ///
10571 /// \param Call The call expression to diagnose.
10572 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10573                                    unsigned BId,
10574                                    IdentifierInfo *FnName) {
10575   assert(BId != 0);
10576 
10577   // It is possible to have a non-standard definition of memset.  Validate
10578   // we have enough arguments, and if not, abort further checking.
10579   unsigned ExpectedNumArgs =
10580       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10581   if (Call->getNumArgs() < ExpectedNumArgs)
10582     return;
10583 
10584   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10585                       BId == Builtin::BIstrndup ? 1 : 2);
10586   unsigned LenArg =
10587       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10588   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10589 
10590   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10591                                      Call->getBeginLoc(), Call->getRParenLoc()))
10592     return;
10593 
10594   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10595   CheckMemaccessSize(*this, BId, Call);
10596 
10597   // We have special checking when the length is a sizeof expression.
10598   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10599   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10600   llvm::FoldingSetNodeID SizeOfArgID;
10601 
10602   // Although widely used, 'bzero' is not a standard function. Be more strict
10603   // with the argument types before allowing diagnostics and only allow the
10604   // form bzero(ptr, sizeof(...)).
10605   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10606   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10607     return;
10608 
10609   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10610     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10611     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10612 
10613     QualType DestTy = Dest->getType();
10614     QualType PointeeTy;
10615     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10616       PointeeTy = DestPtrTy->getPointeeType();
10617 
10618       // Never warn about void type pointers. This can be used to suppress
10619       // false positives.
10620       if (PointeeTy->isVoidType())
10621         continue;
10622 
10623       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10624       // actually comparing the expressions for equality. Because computing the
10625       // expression IDs can be expensive, we only do this if the diagnostic is
10626       // enabled.
10627       if (SizeOfArg &&
10628           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10629                            SizeOfArg->getExprLoc())) {
10630         // We only compute IDs for expressions if the warning is enabled, and
10631         // cache the sizeof arg's ID.
10632         if (SizeOfArgID == llvm::FoldingSetNodeID())
10633           SizeOfArg->Profile(SizeOfArgID, Context, true);
10634         llvm::FoldingSetNodeID DestID;
10635         Dest->Profile(DestID, Context, true);
10636         if (DestID == SizeOfArgID) {
10637           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10638           //       over sizeof(src) as well.
10639           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10640           StringRef ReadableName = FnName->getName();
10641 
10642           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10643             if (UnaryOp->getOpcode() == UO_AddrOf)
10644               ActionIdx = 1; // If its an address-of operator, just remove it.
10645           if (!PointeeTy->isIncompleteType() &&
10646               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10647             ActionIdx = 2; // If the pointee's size is sizeof(char),
10648                            // suggest an explicit length.
10649 
10650           // If the function is defined as a builtin macro, do not show macro
10651           // expansion.
10652           SourceLocation SL = SizeOfArg->getExprLoc();
10653           SourceRange DSR = Dest->getSourceRange();
10654           SourceRange SSR = SizeOfArg->getSourceRange();
10655           SourceManager &SM = getSourceManager();
10656 
10657           if (SM.isMacroArgExpansion(SL)) {
10658             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10659             SL = SM.getSpellingLoc(SL);
10660             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10661                              SM.getSpellingLoc(DSR.getEnd()));
10662             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10663                              SM.getSpellingLoc(SSR.getEnd()));
10664           }
10665 
10666           DiagRuntimeBehavior(SL, SizeOfArg,
10667                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10668                                 << ReadableName
10669                                 << PointeeTy
10670                                 << DestTy
10671                                 << DSR
10672                                 << SSR);
10673           DiagRuntimeBehavior(SL, SizeOfArg,
10674                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10675                                 << ActionIdx
10676                                 << SSR);
10677 
10678           break;
10679         }
10680       }
10681 
10682       // Also check for cases where the sizeof argument is the exact same
10683       // type as the memory argument, and where it points to a user-defined
10684       // record type.
10685       if (SizeOfArgTy != QualType()) {
10686         if (PointeeTy->isRecordType() &&
10687             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10688           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10689                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10690                                 << FnName << SizeOfArgTy << ArgIdx
10691                                 << PointeeTy << Dest->getSourceRange()
10692                                 << LenExpr->getSourceRange());
10693           break;
10694         }
10695       }
10696     } else if (DestTy->isArrayType()) {
10697       PointeeTy = DestTy;
10698     }
10699 
10700     if (PointeeTy == QualType())
10701       continue;
10702 
10703     // Always complain about dynamic classes.
10704     bool IsContained;
10705     if (const CXXRecordDecl *ContainedRD =
10706             getContainedDynamicClass(PointeeTy, IsContained)) {
10707 
10708       unsigned OperationType = 0;
10709       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10710       // "overwritten" if we're warning about the destination for any call
10711       // but memcmp; otherwise a verb appropriate to the call.
10712       if (ArgIdx != 0 || IsCmp) {
10713         if (BId == Builtin::BImemcpy)
10714           OperationType = 1;
10715         else if(BId == Builtin::BImemmove)
10716           OperationType = 2;
10717         else if (IsCmp)
10718           OperationType = 3;
10719       }
10720 
10721       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10722                           PDiag(diag::warn_dyn_class_memaccess)
10723                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10724                               << IsContained << ContainedRD << OperationType
10725                               << Call->getCallee()->getSourceRange());
10726     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10727              BId != Builtin::BImemset)
10728       DiagRuntimeBehavior(
10729         Dest->getExprLoc(), Dest,
10730         PDiag(diag::warn_arc_object_memaccess)
10731           << ArgIdx << FnName << PointeeTy
10732           << Call->getCallee()->getSourceRange());
10733     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10734       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10735           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10736         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10737                             PDiag(diag::warn_cstruct_memaccess)
10738                                 << ArgIdx << FnName << PointeeTy << 0);
10739         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10740       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10741                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10742         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10743                             PDiag(diag::warn_cstruct_memaccess)
10744                                 << ArgIdx << FnName << PointeeTy << 1);
10745         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10746       } else {
10747         continue;
10748       }
10749     } else
10750       continue;
10751 
10752     DiagRuntimeBehavior(
10753       Dest->getExprLoc(), Dest,
10754       PDiag(diag::note_bad_memaccess_silence)
10755         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10756     break;
10757   }
10758 }
10759 
10760 // A little helper routine: ignore addition and subtraction of integer literals.
10761 // This intentionally does not ignore all integer constant expressions because
10762 // we don't want to remove sizeof().
10763 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10764   Ex = Ex->IgnoreParenCasts();
10765 
10766   while (true) {
10767     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10768     if (!BO || !BO->isAdditiveOp())
10769       break;
10770 
10771     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10772     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10773 
10774     if (isa<IntegerLiteral>(RHS))
10775       Ex = LHS;
10776     else if (isa<IntegerLiteral>(LHS))
10777       Ex = RHS;
10778     else
10779       break;
10780   }
10781 
10782   return Ex;
10783 }
10784 
10785 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10786                                                       ASTContext &Context) {
10787   // Only handle constant-sized or VLAs, but not flexible members.
10788   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10789     // Only issue the FIXIT for arrays of size > 1.
10790     if (CAT->getSize().getSExtValue() <= 1)
10791       return false;
10792   } else if (!Ty->isVariableArrayType()) {
10793     return false;
10794   }
10795   return true;
10796 }
10797 
10798 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10799 // be the size of the source, instead of the destination.
10800 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10801                                     IdentifierInfo *FnName) {
10802 
10803   // Don't crash if the user has the wrong number of arguments
10804   unsigned NumArgs = Call->getNumArgs();
10805   if ((NumArgs != 3) && (NumArgs != 4))
10806     return;
10807 
10808   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10809   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10810   const Expr *CompareWithSrc = nullptr;
10811 
10812   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10813                                      Call->getBeginLoc(), Call->getRParenLoc()))
10814     return;
10815 
10816   // Look for 'strlcpy(dst, x, sizeof(x))'
10817   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10818     CompareWithSrc = Ex;
10819   else {
10820     // Look for 'strlcpy(dst, x, strlen(x))'
10821     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10822       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10823           SizeCall->getNumArgs() == 1)
10824         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10825     }
10826   }
10827 
10828   if (!CompareWithSrc)
10829     return;
10830 
10831   // Determine if the argument to sizeof/strlen is equal to the source
10832   // argument.  In principle there's all kinds of things you could do
10833   // here, for instance creating an == expression and evaluating it with
10834   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10835   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10836   if (!SrcArgDRE)
10837     return;
10838 
10839   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10840   if (!CompareWithSrcDRE ||
10841       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10842     return;
10843 
10844   const Expr *OriginalSizeArg = Call->getArg(2);
10845   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10846       << OriginalSizeArg->getSourceRange() << FnName;
10847 
10848   // Output a FIXIT hint if the destination is an array (rather than a
10849   // pointer to an array).  This could be enhanced to handle some
10850   // pointers if we know the actual size, like if DstArg is 'array+2'
10851   // we could say 'sizeof(array)-2'.
10852   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10853   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10854     return;
10855 
10856   SmallString<128> sizeString;
10857   llvm::raw_svector_ostream OS(sizeString);
10858   OS << "sizeof(";
10859   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10860   OS << ")";
10861 
10862   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10863       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10864                                       OS.str());
10865 }
10866 
10867 /// Check if two expressions refer to the same declaration.
10868 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10869   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10870     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10871       return D1->getDecl() == D2->getDecl();
10872   return false;
10873 }
10874 
10875 static const Expr *getStrlenExprArg(const Expr *E) {
10876   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10877     const FunctionDecl *FD = CE->getDirectCallee();
10878     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10879       return nullptr;
10880     return CE->getArg(0)->IgnoreParenCasts();
10881   }
10882   return nullptr;
10883 }
10884 
10885 // Warn on anti-patterns as the 'size' argument to strncat.
10886 // The correct size argument should look like following:
10887 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10888 void Sema::CheckStrncatArguments(const CallExpr *CE,
10889                                  IdentifierInfo *FnName) {
10890   // Don't crash if the user has the wrong number of arguments.
10891   if (CE->getNumArgs() < 3)
10892     return;
10893   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10894   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10895   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10896 
10897   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10898                                      CE->getRParenLoc()))
10899     return;
10900 
10901   // Identify common expressions, which are wrongly used as the size argument
10902   // to strncat and may lead to buffer overflows.
10903   unsigned PatternType = 0;
10904   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10905     // - sizeof(dst)
10906     if (referToTheSameDecl(SizeOfArg, DstArg))
10907       PatternType = 1;
10908     // - sizeof(src)
10909     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10910       PatternType = 2;
10911   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10912     if (BE->getOpcode() == BO_Sub) {
10913       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10914       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10915       // - sizeof(dst) - strlen(dst)
10916       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10917           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10918         PatternType = 1;
10919       // - sizeof(src) - (anything)
10920       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10921         PatternType = 2;
10922     }
10923   }
10924 
10925   if (PatternType == 0)
10926     return;
10927 
10928   // Generate the diagnostic.
10929   SourceLocation SL = LenArg->getBeginLoc();
10930   SourceRange SR = LenArg->getSourceRange();
10931   SourceManager &SM = getSourceManager();
10932 
10933   // If the function is defined as a builtin macro, do not show macro expansion.
10934   if (SM.isMacroArgExpansion(SL)) {
10935     SL = SM.getSpellingLoc(SL);
10936     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10937                      SM.getSpellingLoc(SR.getEnd()));
10938   }
10939 
10940   // Check if the destination is an array (rather than a pointer to an array).
10941   QualType DstTy = DstArg->getType();
10942   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10943                                                                     Context);
10944   if (!isKnownSizeArray) {
10945     if (PatternType == 1)
10946       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10947     else
10948       Diag(SL, diag::warn_strncat_src_size) << SR;
10949     return;
10950   }
10951 
10952   if (PatternType == 1)
10953     Diag(SL, diag::warn_strncat_large_size) << SR;
10954   else
10955     Diag(SL, diag::warn_strncat_src_size) << SR;
10956 
10957   SmallString<128> sizeString;
10958   llvm::raw_svector_ostream OS(sizeString);
10959   OS << "sizeof(";
10960   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10961   OS << ") - ";
10962   OS << "strlen(";
10963   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10964   OS << ") - 1";
10965 
10966   Diag(SL, diag::note_strncat_wrong_size)
10967     << FixItHint::CreateReplacement(SR, OS.str());
10968 }
10969 
10970 namespace {
10971 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10972                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10973   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10974     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10975         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10976     return;
10977   }
10978 }
10979 
10980 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10981                                  const UnaryOperator *UnaryExpr) {
10982   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10983     const Decl *D = Lvalue->getDecl();
10984     if (isa<DeclaratorDecl>(D))
10985       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10986         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10987   }
10988 
10989   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10990     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10991                                       Lvalue->getMemberDecl());
10992 }
10993 
10994 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10995                             const UnaryOperator *UnaryExpr) {
10996   const auto *Lambda = dyn_cast<LambdaExpr>(
10997       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10998   if (!Lambda)
10999     return;
11000 
11001   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
11002       << CalleeName << 2 /*object: lambda expression*/;
11003 }
11004 
11005 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
11006                                   const DeclRefExpr *Lvalue) {
11007   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
11008   if (Var == nullptr)
11009     return;
11010 
11011   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
11012       << CalleeName << 0 /*object: */ << Var;
11013 }
11014 
11015 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
11016                             const CastExpr *Cast) {
11017   SmallString<128> SizeString;
11018   llvm::raw_svector_ostream OS(SizeString);
11019 
11020   clang::CastKind Kind = Cast->getCastKind();
11021   if (Kind == clang::CK_BitCast &&
11022       !Cast->getSubExpr()->getType()->isFunctionPointerType())
11023     return;
11024   if (Kind == clang::CK_IntegralToPointer &&
11025       !isa<IntegerLiteral>(
11026           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
11027     return;
11028 
11029   switch (Cast->getCastKind()) {
11030   case clang::CK_BitCast:
11031   case clang::CK_IntegralToPointer:
11032   case clang::CK_FunctionToPointerDecay:
11033     OS << '\'';
11034     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
11035     OS << '\'';
11036     break;
11037   default:
11038     return;
11039   }
11040 
11041   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
11042       << CalleeName << 0 /*object: */ << OS.str();
11043 }
11044 } // namespace
11045 
11046 /// Alerts the user that they are attempting to free a non-malloc'd object.
11047 void Sema::CheckFreeArguments(const CallExpr *E) {
11048   const std::string CalleeName =
11049       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
11050 
11051   { // Prefer something that doesn't involve a cast to make things simpler.
11052     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
11053     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
11054       switch (UnaryExpr->getOpcode()) {
11055       case UnaryOperator::Opcode::UO_AddrOf:
11056         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
11057       case UnaryOperator::Opcode::UO_Plus:
11058         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
11059       default:
11060         break;
11061       }
11062 
11063     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
11064       if (Lvalue->getType()->isArrayType())
11065         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
11066 
11067     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
11068       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
11069           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
11070       return;
11071     }
11072 
11073     if (isa<BlockExpr>(Arg)) {
11074       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
11075           << CalleeName << 1 /*object: block*/;
11076       return;
11077     }
11078   }
11079   // Maybe the cast was important, check after the other cases.
11080   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
11081     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
11082 }
11083 
11084 void
11085 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
11086                          SourceLocation ReturnLoc,
11087                          bool isObjCMethod,
11088                          const AttrVec *Attrs,
11089                          const FunctionDecl *FD) {
11090   // Check if the return value is null but should not be.
11091   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
11092        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11093       CheckNonNullExpr(*this, RetValExp))
11094     Diag(ReturnLoc, diag::warn_null_ret)
11095       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11096 
11097   // C++11 [basic.stc.dynamic.allocation]p4:
11098   //   If an allocation function declared with a non-throwing
11099   //   exception-specification fails to allocate storage, it shall return
11100   //   a null pointer. Any other allocation function that fails to allocate
11101   //   storage shall indicate failure only by throwing an exception [...]
11102   if (FD) {
11103     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11104     if (Op == OO_New || Op == OO_Array_New) {
11105       const FunctionProtoType *Proto
11106         = FD->getType()->castAs<FunctionProtoType>();
11107       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11108           CheckNonNullExpr(*this, RetValExp))
11109         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11110           << FD << getLangOpts().CPlusPlus11;
11111     }
11112   }
11113 
11114   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11115   // here prevent the user from using a PPC MMA type as trailing return type.
11116   if (Context.getTargetInfo().getTriple().isPPC64())
11117     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11118 }
11119 
11120 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11121 
11122 /// Check for comparisons of floating point operands using != and ==.
11123 /// Issue a warning if these are no self-comparisons, as they are not likely
11124 /// to do what the programmer intended.
11125 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11126   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11127   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11128 
11129   // Special case: check for x == x (which is OK).
11130   // Do not emit warnings for such cases.
11131   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11132     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11133       if (DRL->getDecl() == DRR->getDecl())
11134         return;
11135 
11136   // Special case: check for comparisons against literals that can be exactly
11137   //  represented by APFloat.  In such cases, do not emit a warning.  This
11138   //  is a heuristic: often comparison against such literals are used to
11139   //  detect if a value in a variable has not changed.  This clearly can
11140   //  lead to false negatives.
11141   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11142     if (FLL->isExact())
11143       return;
11144   } else
11145     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11146       if (FLR->isExact())
11147         return;
11148 
11149   // Check for comparisons with builtin types.
11150   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11151     if (CL->getBuiltinCallee())
11152       return;
11153 
11154   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11155     if (CR->getBuiltinCallee())
11156       return;
11157 
11158   // Emit the diagnostic.
11159   Diag(Loc, diag::warn_floatingpoint_eq)
11160     << LHS->getSourceRange() << RHS->getSourceRange();
11161 }
11162 
11163 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11164 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11165 
11166 namespace {
11167 
11168 /// Structure recording the 'active' range of an integer-valued
11169 /// expression.
11170 struct IntRange {
11171   /// The number of bits active in the int. Note that this includes exactly one
11172   /// sign bit if !NonNegative.
11173   unsigned Width;
11174 
11175   /// True if the int is known not to have negative values. If so, all leading
11176   /// bits before Width are known zero, otherwise they are known to be the
11177   /// same as the MSB within Width.
11178   bool NonNegative;
11179 
11180   IntRange(unsigned Width, bool NonNegative)
11181       : Width(Width), NonNegative(NonNegative) {}
11182 
11183   /// Number of bits excluding the sign bit.
11184   unsigned valueBits() const {
11185     return NonNegative ? Width : Width - 1;
11186   }
11187 
11188   /// Returns the range of the bool type.
11189   static IntRange forBoolType() {
11190     return IntRange(1, true);
11191   }
11192 
11193   /// Returns the range of an opaque value of the given integral type.
11194   static IntRange forValueOfType(ASTContext &C, QualType T) {
11195     return forValueOfCanonicalType(C,
11196                           T->getCanonicalTypeInternal().getTypePtr());
11197   }
11198 
11199   /// Returns the range of an opaque value of a canonical integral type.
11200   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11201     assert(T->isCanonicalUnqualified());
11202 
11203     if (const VectorType *VT = dyn_cast<VectorType>(T))
11204       T = VT->getElementType().getTypePtr();
11205     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11206       T = CT->getElementType().getTypePtr();
11207     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11208       T = AT->getValueType().getTypePtr();
11209 
11210     if (!C.getLangOpts().CPlusPlus) {
11211       // For enum types in C code, use the underlying datatype.
11212       if (const EnumType *ET = dyn_cast<EnumType>(T))
11213         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11214     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11215       // For enum types in C++, use the known bit width of the enumerators.
11216       EnumDecl *Enum = ET->getDecl();
11217       // In C++11, enums can have a fixed underlying type. Use this type to
11218       // compute the range.
11219       if (Enum->isFixed()) {
11220         return IntRange(C.getIntWidth(QualType(T, 0)),
11221                         !ET->isSignedIntegerOrEnumerationType());
11222       }
11223 
11224       unsigned NumPositive = Enum->getNumPositiveBits();
11225       unsigned NumNegative = Enum->getNumNegativeBits();
11226 
11227       if (NumNegative == 0)
11228         return IntRange(NumPositive, true/*NonNegative*/);
11229       else
11230         return IntRange(std::max(NumPositive + 1, NumNegative),
11231                         false/*NonNegative*/);
11232     }
11233 
11234     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11235       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11236 
11237     const BuiltinType *BT = cast<BuiltinType>(T);
11238     assert(BT->isInteger());
11239 
11240     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11241   }
11242 
11243   /// Returns the "target" range of a canonical integral type, i.e.
11244   /// the range of values expressible in the type.
11245   ///
11246   /// This matches forValueOfCanonicalType except that enums have the
11247   /// full range of their type, not the range of their enumerators.
11248   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11249     assert(T->isCanonicalUnqualified());
11250 
11251     if (const VectorType *VT = dyn_cast<VectorType>(T))
11252       T = VT->getElementType().getTypePtr();
11253     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11254       T = CT->getElementType().getTypePtr();
11255     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11256       T = AT->getValueType().getTypePtr();
11257     if (const EnumType *ET = dyn_cast<EnumType>(T))
11258       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11259 
11260     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11261       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11262 
11263     const BuiltinType *BT = cast<BuiltinType>(T);
11264     assert(BT->isInteger());
11265 
11266     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11267   }
11268 
11269   /// Returns the supremum of two ranges: i.e. their conservative merge.
11270   static IntRange join(IntRange L, IntRange R) {
11271     bool Unsigned = L.NonNegative && R.NonNegative;
11272     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11273                     L.NonNegative && R.NonNegative);
11274   }
11275 
11276   /// Return the range of a bitwise-AND of the two ranges.
11277   static IntRange bit_and(IntRange L, IntRange R) {
11278     unsigned Bits = std::max(L.Width, R.Width);
11279     bool NonNegative = false;
11280     if (L.NonNegative) {
11281       Bits = std::min(Bits, L.Width);
11282       NonNegative = true;
11283     }
11284     if (R.NonNegative) {
11285       Bits = std::min(Bits, R.Width);
11286       NonNegative = true;
11287     }
11288     return IntRange(Bits, NonNegative);
11289   }
11290 
11291   /// Return the range of a sum of the two ranges.
11292   static IntRange sum(IntRange L, IntRange R) {
11293     bool Unsigned = L.NonNegative && R.NonNegative;
11294     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11295                     Unsigned);
11296   }
11297 
11298   /// Return the range of a difference of the two ranges.
11299   static IntRange difference(IntRange L, IntRange R) {
11300     // We need a 1-bit-wider range if:
11301     //   1) LHS can be negative: least value can be reduced.
11302     //   2) RHS can be negative: greatest value can be increased.
11303     bool CanWiden = !L.NonNegative || !R.NonNegative;
11304     bool Unsigned = L.NonNegative && R.Width == 0;
11305     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11306                         !Unsigned,
11307                     Unsigned);
11308   }
11309 
11310   /// Return the range of a product of the two ranges.
11311   static IntRange product(IntRange L, IntRange R) {
11312     // If both LHS and RHS can be negative, we can form
11313     //   -2^L * -2^R = 2^(L + R)
11314     // which requires L + R + 1 value bits to represent.
11315     bool CanWiden = !L.NonNegative && !R.NonNegative;
11316     bool Unsigned = L.NonNegative && R.NonNegative;
11317     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11318                     Unsigned);
11319   }
11320 
11321   /// Return the range of a remainder operation between the two ranges.
11322   static IntRange rem(IntRange L, IntRange R) {
11323     // The result of a remainder can't be larger than the result of
11324     // either side. The sign of the result is the sign of the LHS.
11325     bool Unsigned = L.NonNegative;
11326     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11327                     Unsigned);
11328   }
11329 };
11330 
11331 } // namespace
11332 
11333 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11334                               unsigned MaxWidth) {
11335   if (value.isSigned() && value.isNegative())
11336     return IntRange(value.getMinSignedBits(), false);
11337 
11338   if (value.getBitWidth() > MaxWidth)
11339     value = value.trunc(MaxWidth);
11340 
11341   // isNonNegative() just checks the sign bit without considering
11342   // signedness.
11343   return IntRange(value.getActiveBits(), true);
11344 }
11345 
11346 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11347                               unsigned MaxWidth) {
11348   if (result.isInt())
11349     return GetValueRange(C, result.getInt(), MaxWidth);
11350 
11351   if (result.isVector()) {
11352     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11353     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11354       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11355       R = IntRange::join(R, El);
11356     }
11357     return R;
11358   }
11359 
11360   if (result.isComplexInt()) {
11361     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11362     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11363     return IntRange::join(R, I);
11364   }
11365 
11366   // This can happen with lossless casts to intptr_t of "based" lvalues.
11367   // Assume it might use arbitrary bits.
11368   // FIXME: The only reason we need to pass the type in here is to get
11369   // the sign right on this one case.  It would be nice if APValue
11370   // preserved this.
11371   assert(result.isLValue() || result.isAddrLabelDiff());
11372   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11373 }
11374 
11375 static QualType GetExprType(const Expr *E) {
11376   QualType Ty = E->getType();
11377   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11378     Ty = AtomicRHS->getValueType();
11379   return Ty;
11380 }
11381 
11382 /// Pseudo-evaluate the given integer expression, estimating the
11383 /// range of values it might take.
11384 ///
11385 /// \param MaxWidth The width to which the value will be truncated.
11386 /// \param Approximate If \c true, return a likely range for the result: in
11387 ///        particular, assume that arithmetic on narrower types doesn't leave
11388 ///        those types. If \c false, return a range including all possible
11389 ///        result values.
11390 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11391                              bool InConstantContext, bool Approximate) {
11392   E = E->IgnoreParens();
11393 
11394   // Try a full evaluation first.
11395   Expr::EvalResult result;
11396   if (E->EvaluateAsRValue(result, C, InConstantContext))
11397     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11398 
11399   // I think we only want to look through implicit casts here; if the
11400   // user has an explicit widening cast, we should treat the value as
11401   // being of the new, wider type.
11402   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11403     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11404       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11405                           Approximate);
11406 
11407     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11408 
11409     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11410                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11411 
11412     // Assume that non-integer casts can span the full range of the type.
11413     if (!isIntegerCast)
11414       return OutputTypeRange;
11415 
11416     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11417                                      std::min(MaxWidth, OutputTypeRange.Width),
11418                                      InConstantContext, Approximate);
11419 
11420     // Bail out if the subexpr's range is as wide as the cast type.
11421     if (SubRange.Width >= OutputTypeRange.Width)
11422       return OutputTypeRange;
11423 
11424     // Otherwise, we take the smaller width, and we're non-negative if
11425     // either the output type or the subexpr is.
11426     return IntRange(SubRange.Width,
11427                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11428   }
11429 
11430   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11431     // If we can fold the condition, just take that operand.
11432     bool CondResult;
11433     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11434       return GetExprRange(C,
11435                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11436                           MaxWidth, InConstantContext, Approximate);
11437 
11438     // Otherwise, conservatively merge.
11439     // GetExprRange requires an integer expression, but a throw expression
11440     // results in a void type.
11441     Expr *E = CO->getTrueExpr();
11442     IntRange L = E->getType()->isVoidType()
11443                      ? IntRange{0, true}
11444                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11445     E = CO->getFalseExpr();
11446     IntRange R = E->getType()->isVoidType()
11447                      ? IntRange{0, true}
11448                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11449     return IntRange::join(L, R);
11450   }
11451 
11452   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11453     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11454 
11455     switch (BO->getOpcode()) {
11456     case BO_Cmp:
11457       llvm_unreachable("builtin <=> should have class type");
11458 
11459     // Boolean-valued operations are single-bit and positive.
11460     case BO_LAnd:
11461     case BO_LOr:
11462     case BO_LT:
11463     case BO_GT:
11464     case BO_LE:
11465     case BO_GE:
11466     case BO_EQ:
11467     case BO_NE:
11468       return IntRange::forBoolType();
11469 
11470     // The type of the assignments is the type of the LHS, so the RHS
11471     // is not necessarily the same type.
11472     case BO_MulAssign:
11473     case BO_DivAssign:
11474     case BO_RemAssign:
11475     case BO_AddAssign:
11476     case BO_SubAssign:
11477     case BO_XorAssign:
11478     case BO_OrAssign:
11479       // TODO: bitfields?
11480       return IntRange::forValueOfType(C, GetExprType(E));
11481 
11482     // Simple assignments just pass through the RHS, which will have
11483     // been coerced to the LHS type.
11484     case BO_Assign:
11485       // TODO: bitfields?
11486       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11487                           Approximate);
11488 
11489     // Operations with opaque sources are black-listed.
11490     case BO_PtrMemD:
11491     case BO_PtrMemI:
11492       return IntRange::forValueOfType(C, GetExprType(E));
11493 
11494     // Bitwise-and uses the *infinum* of the two source ranges.
11495     case BO_And:
11496     case BO_AndAssign:
11497       Combine = IntRange::bit_and;
11498       break;
11499 
11500     // Left shift gets black-listed based on a judgement call.
11501     case BO_Shl:
11502       // ...except that we want to treat '1 << (blah)' as logically
11503       // positive.  It's an important idiom.
11504       if (IntegerLiteral *I
11505             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11506         if (I->getValue() == 1) {
11507           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11508           return IntRange(R.Width, /*NonNegative*/ true);
11509         }
11510       }
11511       LLVM_FALLTHROUGH;
11512 
11513     case BO_ShlAssign:
11514       return IntRange::forValueOfType(C, GetExprType(E));
11515 
11516     // Right shift by a constant can narrow its left argument.
11517     case BO_Shr:
11518     case BO_ShrAssign: {
11519       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11520                                 Approximate);
11521 
11522       // If the shift amount is a positive constant, drop the width by
11523       // that much.
11524       if (Optional<llvm::APSInt> shift =
11525               BO->getRHS()->getIntegerConstantExpr(C)) {
11526         if (shift->isNonNegative()) {
11527           unsigned zext = shift->getZExtValue();
11528           if (zext >= L.Width)
11529             L.Width = (L.NonNegative ? 0 : 1);
11530           else
11531             L.Width -= zext;
11532         }
11533       }
11534 
11535       return L;
11536     }
11537 
11538     // Comma acts as its right operand.
11539     case BO_Comma:
11540       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11541                           Approximate);
11542 
11543     case BO_Add:
11544       if (!Approximate)
11545         Combine = IntRange::sum;
11546       break;
11547 
11548     case BO_Sub:
11549       if (BO->getLHS()->getType()->isPointerType())
11550         return IntRange::forValueOfType(C, GetExprType(E));
11551       if (!Approximate)
11552         Combine = IntRange::difference;
11553       break;
11554 
11555     case BO_Mul:
11556       if (!Approximate)
11557         Combine = IntRange::product;
11558       break;
11559 
11560     // The width of a division result is mostly determined by the size
11561     // of the LHS.
11562     case BO_Div: {
11563       // Don't 'pre-truncate' the operands.
11564       unsigned opWidth = C.getIntWidth(GetExprType(E));
11565       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11566                                 Approximate);
11567 
11568       // If the divisor is constant, use that.
11569       if (Optional<llvm::APSInt> divisor =
11570               BO->getRHS()->getIntegerConstantExpr(C)) {
11571         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11572         if (log2 >= L.Width)
11573           L.Width = (L.NonNegative ? 0 : 1);
11574         else
11575           L.Width = std::min(L.Width - log2, MaxWidth);
11576         return L;
11577       }
11578 
11579       // Otherwise, just use the LHS's width.
11580       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11581       // could be -1.
11582       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11583                                 Approximate);
11584       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11585     }
11586 
11587     case BO_Rem:
11588       Combine = IntRange::rem;
11589       break;
11590 
11591     // The default behavior is okay for these.
11592     case BO_Xor:
11593     case BO_Or:
11594       break;
11595     }
11596 
11597     // Combine the two ranges, but limit the result to the type in which we
11598     // performed the computation.
11599     QualType T = GetExprType(E);
11600     unsigned opWidth = C.getIntWidth(T);
11601     IntRange L =
11602         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11603     IntRange R =
11604         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11605     IntRange C = Combine(L, R);
11606     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11607     C.Width = std::min(C.Width, MaxWidth);
11608     return C;
11609   }
11610 
11611   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11612     switch (UO->getOpcode()) {
11613     // Boolean-valued operations are white-listed.
11614     case UO_LNot:
11615       return IntRange::forBoolType();
11616 
11617     // Operations with opaque sources are black-listed.
11618     case UO_Deref:
11619     case UO_AddrOf: // should be impossible
11620       return IntRange::forValueOfType(C, GetExprType(E));
11621 
11622     default:
11623       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11624                           Approximate);
11625     }
11626   }
11627 
11628   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11629     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11630                         Approximate);
11631 
11632   if (const auto *BitField = E->getSourceBitField())
11633     return IntRange(BitField->getBitWidthValue(C),
11634                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11635 
11636   return IntRange::forValueOfType(C, GetExprType(E));
11637 }
11638 
11639 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11640                              bool InConstantContext, bool Approximate) {
11641   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11642                       Approximate);
11643 }
11644 
11645 /// Checks whether the given value, which currently has the given
11646 /// source semantics, has the same value when coerced through the
11647 /// target semantics.
11648 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11649                                  const llvm::fltSemantics &Src,
11650                                  const llvm::fltSemantics &Tgt) {
11651   llvm::APFloat truncated = value;
11652 
11653   bool ignored;
11654   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11655   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11656 
11657   return truncated.bitwiseIsEqual(value);
11658 }
11659 
11660 /// Checks whether the given value, which currently has the given
11661 /// source semantics, has the same value when coerced through the
11662 /// target semantics.
11663 ///
11664 /// The value might be a vector of floats (or a complex number).
11665 static bool IsSameFloatAfterCast(const APValue &value,
11666                                  const llvm::fltSemantics &Src,
11667                                  const llvm::fltSemantics &Tgt) {
11668   if (value.isFloat())
11669     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11670 
11671   if (value.isVector()) {
11672     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11673       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11674         return false;
11675     return true;
11676   }
11677 
11678   assert(value.isComplexFloat());
11679   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11680           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11681 }
11682 
11683 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11684                                        bool IsListInit = false);
11685 
11686 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11687   // Suppress cases where we are comparing against an enum constant.
11688   if (const DeclRefExpr *DR =
11689       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11690     if (isa<EnumConstantDecl>(DR->getDecl()))
11691       return true;
11692 
11693   // Suppress cases where the value is expanded from a macro, unless that macro
11694   // is how a language represents a boolean literal. This is the case in both C
11695   // and Objective-C.
11696   SourceLocation BeginLoc = E->getBeginLoc();
11697   if (BeginLoc.isMacroID()) {
11698     StringRef MacroName = Lexer::getImmediateMacroName(
11699         BeginLoc, S.getSourceManager(), S.getLangOpts());
11700     return MacroName != "YES" && MacroName != "NO" &&
11701            MacroName != "true" && MacroName != "false";
11702   }
11703 
11704   return false;
11705 }
11706 
11707 static bool isKnownToHaveUnsignedValue(Expr *E) {
11708   return E->getType()->isIntegerType() &&
11709          (!E->getType()->isSignedIntegerType() ||
11710           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11711 }
11712 
11713 namespace {
11714 /// The promoted range of values of a type. In general this has the
11715 /// following structure:
11716 ///
11717 ///     |-----------| . . . |-----------|
11718 ///     ^           ^       ^           ^
11719 ///    Min       HoleMin  HoleMax      Max
11720 ///
11721 /// ... where there is only a hole if a signed type is promoted to unsigned
11722 /// (in which case Min and Max are the smallest and largest representable
11723 /// values).
11724 struct PromotedRange {
11725   // Min, or HoleMax if there is a hole.
11726   llvm::APSInt PromotedMin;
11727   // Max, or HoleMin if there is a hole.
11728   llvm::APSInt PromotedMax;
11729 
11730   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11731     if (R.Width == 0)
11732       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11733     else if (R.Width >= BitWidth && !Unsigned) {
11734       // Promotion made the type *narrower*. This happens when promoting
11735       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11736       // Treat all values of 'signed int' as being in range for now.
11737       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11738       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11739     } else {
11740       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11741                         .extOrTrunc(BitWidth);
11742       PromotedMin.setIsUnsigned(Unsigned);
11743 
11744       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11745                         .extOrTrunc(BitWidth);
11746       PromotedMax.setIsUnsigned(Unsigned);
11747     }
11748   }
11749 
11750   // Determine whether this range is contiguous (has no hole).
11751   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11752 
11753   // Where a constant value is within the range.
11754   enum ComparisonResult {
11755     LT = 0x1,
11756     LE = 0x2,
11757     GT = 0x4,
11758     GE = 0x8,
11759     EQ = 0x10,
11760     NE = 0x20,
11761     InRangeFlag = 0x40,
11762 
11763     Less = LE | LT | NE,
11764     Min = LE | InRangeFlag,
11765     InRange = InRangeFlag,
11766     Max = GE | InRangeFlag,
11767     Greater = GE | GT | NE,
11768 
11769     OnlyValue = LE | GE | EQ | InRangeFlag,
11770     InHole = NE
11771   };
11772 
11773   ComparisonResult compare(const llvm::APSInt &Value) const {
11774     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11775            Value.isUnsigned() == PromotedMin.isUnsigned());
11776     if (!isContiguous()) {
11777       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11778       if (Value.isMinValue()) return Min;
11779       if (Value.isMaxValue()) return Max;
11780       if (Value >= PromotedMin) return InRange;
11781       if (Value <= PromotedMax) return InRange;
11782       return InHole;
11783     }
11784 
11785     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11786     case -1: return Less;
11787     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11788     case 1:
11789       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11790       case -1: return InRange;
11791       case 0: return Max;
11792       case 1: return Greater;
11793       }
11794     }
11795 
11796     llvm_unreachable("impossible compare result");
11797   }
11798 
11799   static llvm::Optional<StringRef>
11800   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11801     if (Op == BO_Cmp) {
11802       ComparisonResult LTFlag = LT, GTFlag = GT;
11803       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11804 
11805       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11806       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11807       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11808       return llvm::None;
11809     }
11810 
11811     ComparisonResult TrueFlag, FalseFlag;
11812     if (Op == BO_EQ) {
11813       TrueFlag = EQ;
11814       FalseFlag = NE;
11815     } else if (Op == BO_NE) {
11816       TrueFlag = NE;
11817       FalseFlag = EQ;
11818     } else {
11819       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11820         TrueFlag = LT;
11821         FalseFlag = GE;
11822       } else {
11823         TrueFlag = GT;
11824         FalseFlag = LE;
11825       }
11826       if (Op == BO_GE || Op == BO_LE)
11827         std::swap(TrueFlag, FalseFlag);
11828     }
11829     if (R & TrueFlag)
11830       return StringRef("true");
11831     if (R & FalseFlag)
11832       return StringRef("false");
11833     return llvm::None;
11834   }
11835 };
11836 }
11837 
11838 static bool HasEnumType(Expr *E) {
11839   // Strip off implicit integral promotions.
11840   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11841     if (ICE->getCastKind() != CK_IntegralCast &&
11842         ICE->getCastKind() != CK_NoOp)
11843       break;
11844     E = ICE->getSubExpr();
11845   }
11846 
11847   return E->getType()->isEnumeralType();
11848 }
11849 
11850 static int classifyConstantValue(Expr *Constant) {
11851   // The values of this enumeration are used in the diagnostics
11852   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11853   enum ConstantValueKind {
11854     Miscellaneous = 0,
11855     LiteralTrue,
11856     LiteralFalse
11857   };
11858   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11859     return BL->getValue() ? ConstantValueKind::LiteralTrue
11860                           : ConstantValueKind::LiteralFalse;
11861   return ConstantValueKind::Miscellaneous;
11862 }
11863 
11864 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11865                                         Expr *Constant, Expr *Other,
11866                                         const llvm::APSInt &Value,
11867                                         bool RhsConstant) {
11868   if (S.inTemplateInstantiation())
11869     return false;
11870 
11871   Expr *OriginalOther = Other;
11872 
11873   Constant = Constant->IgnoreParenImpCasts();
11874   Other = Other->IgnoreParenImpCasts();
11875 
11876   // Suppress warnings on tautological comparisons between values of the same
11877   // enumeration type. There are only two ways we could warn on this:
11878   //  - If the constant is outside the range of representable values of
11879   //    the enumeration. In such a case, we should warn about the cast
11880   //    to enumeration type, not about the comparison.
11881   //  - If the constant is the maximum / minimum in-range value. For an
11882   //    enumeratin type, such comparisons can be meaningful and useful.
11883   if (Constant->getType()->isEnumeralType() &&
11884       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11885     return false;
11886 
11887   IntRange OtherValueRange = GetExprRange(
11888       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11889 
11890   QualType OtherT = Other->getType();
11891   if (const auto *AT = OtherT->getAs<AtomicType>())
11892     OtherT = AT->getValueType();
11893   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11894 
11895   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11896   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11897   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11898                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11899                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11900 
11901   // Whether we're treating Other as being a bool because of the form of
11902   // expression despite it having another type (typically 'int' in C).
11903   bool OtherIsBooleanDespiteType =
11904       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11905   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11906     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11907 
11908   // Check if all values in the range of possible values of this expression
11909   // lead to the same comparison outcome.
11910   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11911                                         Value.isUnsigned());
11912   auto Cmp = OtherPromotedValueRange.compare(Value);
11913   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11914   if (!Result)
11915     return false;
11916 
11917   // Also consider the range determined by the type alone. This allows us to
11918   // classify the warning under the proper diagnostic group.
11919   bool TautologicalTypeCompare = false;
11920   {
11921     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11922                                          Value.isUnsigned());
11923     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11924     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11925                                                        RhsConstant)) {
11926       TautologicalTypeCompare = true;
11927       Cmp = TypeCmp;
11928       Result = TypeResult;
11929     }
11930   }
11931 
11932   // Don't warn if the non-constant operand actually always evaluates to the
11933   // same value.
11934   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11935     return false;
11936 
11937   // Suppress the diagnostic for an in-range comparison if the constant comes
11938   // from a macro or enumerator. We don't want to diagnose
11939   //
11940   //   some_long_value <= INT_MAX
11941   //
11942   // when sizeof(int) == sizeof(long).
11943   bool InRange = Cmp & PromotedRange::InRangeFlag;
11944   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11945     return false;
11946 
11947   // A comparison of an unsigned bit-field against 0 is really a type problem,
11948   // even though at the type level the bit-field might promote to 'signed int'.
11949   if (Other->refersToBitField() && InRange && Value == 0 &&
11950       Other->getType()->isUnsignedIntegerOrEnumerationType())
11951     TautologicalTypeCompare = true;
11952 
11953   // If this is a comparison to an enum constant, include that
11954   // constant in the diagnostic.
11955   const EnumConstantDecl *ED = nullptr;
11956   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11957     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11958 
11959   // Should be enough for uint128 (39 decimal digits)
11960   SmallString<64> PrettySourceValue;
11961   llvm::raw_svector_ostream OS(PrettySourceValue);
11962   if (ED) {
11963     OS << '\'' << *ED << "' (" << Value << ")";
11964   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11965                Constant->IgnoreParenImpCasts())) {
11966     OS << (BL->getValue() ? "YES" : "NO");
11967   } else {
11968     OS << Value;
11969   }
11970 
11971   if (!TautologicalTypeCompare) {
11972     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11973         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11974         << E->getOpcodeStr() << OS.str() << *Result
11975         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11976     return true;
11977   }
11978 
11979   if (IsObjCSignedCharBool) {
11980     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11981                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11982                               << OS.str() << *Result);
11983     return true;
11984   }
11985 
11986   // FIXME: We use a somewhat different formatting for the in-range cases and
11987   // cases involving boolean values for historical reasons. We should pick a
11988   // consistent way of presenting these diagnostics.
11989   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11990 
11991     S.DiagRuntimeBehavior(
11992         E->getOperatorLoc(), E,
11993         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11994                          : diag::warn_tautological_bool_compare)
11995             << OS.str() << classifyConstantValue(Constant) << OtherT
11996             << OtherIsBooleanDespiteType << *Result
11997             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11998   } else {
11999     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
12000     unsigned Diag =
12001         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
12002             ? (HasEnumType(OriginalOther)
12003                    ? diag::warn_unsigned_enum_always_true_comparison
12004                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
12005                               : diag::warn_unsigned_always_true_comparison)
12006             : diag::warn_tautological_constant_compare;
12007 
12008     S.Diag(E->getOperatorLoc(), Diag)
12009         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
12010         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
12011   }
12012 
12013   return true;
12014 }
12015 
12016 /// Analyze the operands of the given comparison.  Implements the
12017 /// fallback case from AnalyzeComparison.
12018 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
12019   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12020   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12021 }
12022 
12023 /// Implements -Wsign-compare.
12024 ///
12025 /// \param E the binary operator to check for warnings
12026 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
12027   // The type the comparison is being performed in.
12028   QualType T = E->getLHS()->getType();
12029 
12030   // Only analyze comparison operators where both sides have been converted to
12031   // the same type.
12032   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
12033     return AnalyzeImpConvsInComparison(S, E);
12034 
12035   // Don't analyze value-dependent comparisons directly.
12036   if (E->isValueDependent())
12037     return AnalyzeImpConvsInComparison(S, E);
12038 
12039   Expr *LHS = E->getLHS();
12040   Expr *RHS = E->getRHS();
12041 
12042   if (T->isIntegralType(S.Context)) {
12043     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
12044     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
12045 
12046     // We don't care about expressions whose result is a constant.
12047     if (RHSValue && LHSValue)
12048       return AnalyzeImpConvsInComparison(S, E);
12049 
12050     // We only care about expressions where just one side is literal
12051     if ((bool)RHSValue ^ (bool)LHSValue) {
12052       // Is the constant on the RHS or LHS?
12053       const bool RhsConstant = (bool)RHSValue;
12054       Expr *Const = RhsConstant ? RHS : LHS;
12055       Expr *Other = RhsConstant ? LHS : RHS;
12056       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
12057 
12058       // Check whether an integer constant comparison results in a value
12059       // of 'true' or 'false'.
12060       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
12061         return AnalyzeImpConvsInComparison(S, E);
12062     }
12063   }
12064 
12065   if (!T->hasUnsignedIntegerRepresentation()) {
12066     // We don't do anything special if this isn't an unsigned integral
12067     // comparison:  we're only interested in integral comparisons, and
12068     // signed comparisons only happen in cases we don't care to warn about.
12069     return AnalyzeImpConvsInComparison(S, E);
12070   }
12071 
12072   LHS = LHS->IgnoreParenImpCasts();
12073   RHS = RHS->IgnoreParenImpCasts();
12074 
12075   if (!S.getLangOpts().CPlusPlus) {
12076     // Avoid warning about comparison of integers with different signs when
12077     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
12078     // the type of `E`.
12079     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
12080       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12081     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
12082       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
12083   }
12084 
12085   // Check to see if one of the (unmodified) operands is of different
12086   // signedness.
12087   Expr *signedOperand, *unsignedOperand;
12088   if (LHS->getType()->hasSignedIntegerRepresentation()) {
12089     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
12090            "unsigned comparison between two signed integer expressions?");
12091     signedOperand = LHS;
12092     unsignedOperand = RHS;
12093   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12094     signedOperand = RHS;
12095     unsignedOperand = LHS;
12096   } else {
12097     return AnalyzeImpConvsInComparison(S, E);
12098   }
12099 
12100   // Otherwise, calculate the effective range of the signed operand.
12101   IntRange signedRange = GetExprRange(
12102       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12103 
12104   // Go ahead and analyze implicit conversions in the operands.  Note
12105   // that we skip the implicit conversions on both sides.
12106   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12107   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12108 
12109   // If the signed range is non-negative, -Wsign-compare won't fire.
12110   if (signedRange.NonNegative)
12111     return;
12112 
12113   // For (in)equality comparisons, if the unsigned operand is a
12114   // constant which cannot collide with a overflowed signed operand,
12115   // then reinterpreting the signed operand as unsigned will not
12116   // change the result of the comparison.
12117   if (E->isEqualityOp()) {
12118     unsigned comparisonWidth = S.Context.getIntWidth(T);
12119     IntRange unsignedRange =
12120         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12121                      /*Approximate*/ true);
12122 
12123     // We should never be unable to prove that the unsigned operand is
12124     // non-negative.
12125     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12126 
12127     if (unsignedRange.Width < comparisonWidth)
12128       return;
12129   }
12130 
12131   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12132                         S.PDiag(diag::warn_mixed_sign_comparison)
12133                             << LHS->getType() << RHS->getType()
12134                             << LHS->getSourceRange() << RHS->getSourceRange());
12135 }
12136 
12137 /// Analyzes an attempt to assign the given value to a bitfield.
12138 ///
12139 /// Returns true if there was something fishy about the attempt.
12140 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12141                                       SourceLocation InitLoc) {
12142   assert(Bitfield->isBitField());
12143   if (Bitfield->isInvalidDecl())
12144     return false;
12145 
12146   // White-list bool bitfields.
12147   QualType BitfieldType = Bitfield->getType();
12148   if (BitfieldType->isBooleanType())
12149      return false;
12150 
12151   if (BitfieldType->isEnumeralType()) {
12152     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12153     // If the underlying enum type was not explicitly specified as an unsigned
12154     // type and the enum contain only positive values, MSVC++ will cause an
12155     // inconsistency by storing this as a signed type.
12156     if (S.getLangOpts().CPlusPlus11 &&
12157         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12158         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12159         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12160       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12161           << BitfieldEnumDecl;
12162     }
12163   }
12164 
12165   if (Bitfield->getType()->isBooleanType())
12166     return false;
12167 
12168   // Ignore value- or type-dependent expressions.
12169   if (Bitfield->getBitWidth()->isValueDependent() ||
12170       Bitfield->getBitWidth()->isTypeDependent() ||
12171       Init->isValueDependent() ||
12172       Init->isTypeDependent())
12173     return false;
12174 
12175   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12176   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12177 
12178   Expr::EvalResult Result;
12179   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12180                                    Expr::SE_AllowSideEffects)) {
12181     // The RHS is not constant.  If the RHS has an enum type, make sure the
12182     // bitfield is wide enough to hold all the values of the enum without
12183     // truncation.
12184     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12185       EnumDecl *ED = EnumTy->getDecl();
12186       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12187 
12188       // Enum types are implicitly signed on Windows, so check if there are any
12189       // negative enumerators to see if the enum was intended to be signed or
12190       // not.
12191       bool SignedEnum = ED->getNumNegativeBits() > 0;
12192 
12193       // Check for surprising sign changes when assigning enum values to a
12194       // bitfield of different signedness.  If the bitfield is signed and we
12195       // have exactly the right number of bits to store this unsigned enum,
12196       // suggest changing the enum to an unsigned type. This typically happens
12197       // on Windows where unfixed enums always use an underlying type of 'int'.
12198       unsigned DiagID = 0;
12199       if (SignedEnum && !SignedBitfield) {
12200         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12201       } else if (SignedBitfield && !SignedEnum &&
12202                  ED->getNumPositiveBits() == FieldWidth) {
12203         DiagID = diag::warn_signed_bitfield_enum_conversion;
12204       }
12205 
12206       if (DiagID) {
12207         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12208         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12209         SourceRange TypeRange =
12210             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12211         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12212             << SignedEnum << TypeRange;
12213       }
12214 
12215       // Compute the required bitwidth. If the enum has negative values, we need
12216       // one more bit than the normal number of positive bits to represent the
12217       // sign bit.
12218       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12219                                                   ED->getNumNegativeBits())
12220                                        : ED->getNumPositiveBits();
12221 
12222       // Check the bitwidth.
12223       if (BitsNeeded > FieldWidth) {
12224         Expr *WidthExpr = Bitfield->getBitWidth();
12225         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12226             << Bitfield << ED;
12227         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12228             << BitsNeeded << ED << WidthExpr->getSourceRange();
12229       }
12230     }
12231 
12232     return false;
12233   }
12234 
12235   llvm::APSInt Value = Result.Val.getInt();
12236 
12237   unsigned OriginalWidth = Value.getBitWidth();
12238 
12239   if (!Value.isSigned() || Value.isNegative())
12240     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12241       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12242         OriginalWidth = Value.getMinSignedBits();
12243 
12244   if (OriginalWidth <= FieldWidth)
12245     return false;
12246 
12247   // Compute the value which the bitfield will contain.
12248   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12249   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12250 
12251   // Check whether the stored value is equal to the original value.
12252   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12253   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12254     return false;
12255 
12256   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12257   // therefore don't strictly fit into a signed bitfield of width 1.
12258   if (FieldWidth == 1 && Value == 1)
12259     return false;
12260 
12261   std::string PrettyValue = toString(Value, 10);
12262   std::string PrettyTrunc = toString(TruncatedValue, 10);
12263 
12264   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12265     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12266     << Init->getSourceRange();
12267 
12268   return true;
12269 }
12270 
12271 /// Analyze the given simple or compound assignment for warning-worthy
12272 /// operations.
12273 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12274   // Just recurse on the LHS.
12275   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12276 
12277   // We want to recurse on the RHS as normal unless we're assigning to
12278   // a bitfield.
12279   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12280     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12281                                   E->getOperatorLoc())) {
12282       // Recurse, ignoring any implicit conversions on the RHS.
12283       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12284                                         E->getOperatorLoc());
12285     }
12286   }
12287 
12288   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12289 
12290   // Diagnose implicitly sequentially-consistent atomic assignment.
12291   if (E->getLHS()->getType()->isAtomicType())
12292     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12293 }
12294 
12295 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12296 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12297                             SourceLocation CContext, unsigned diag,
12298                             bool pruneControlFlow = false) {
12299   if (pruneControlFlow) {
12300     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12301                           S.PDiag(diag)
12302                               << SourceType << T << E->getSourceRange()
12303                               << SourceRange(CContext));
12304     return;
12305   }
12306   S.Diag(E->getExprLoc(), diag)
12307     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12308 }
12309 
12310 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12311 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12312                             SourceLocation CContext,
12313                             unsigned diag, bool pruneControlFlow = false) {
12314   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12315 }
12316 
12317 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12318   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12319       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12320 }
12321 
12322 static void adornObjCBoolConversionDiagWithTernaryFixit(
12323     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12324   Expr *Ignored = SourceExpr->IgnoreImplicit();
12325   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12326     Ignored = OVE->getSourceExpr();
12327   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12328                      isa<BinaryOperator>(Ignored) ||
12329                      isa<CXXOperatorCallExpr>(Ignored);
12330   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12331   if (NeedsParens)
12332     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12333             << FixItHint::CreateInsertion(EndLoc, ")");
12334   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12335 }
12336 
12337 /// Diagnose an implicit cast from a floating point value to an integer value.
12338 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12339                                     SourceLocation CContext) {
12340   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12341   const bool PruneWarnings = S.inTemplateInstantiation();
12342 
12343   Expr *InnerE = E->IgnoreParenImpCasts();
12344   // We also want to warn on, e.g., "int i = -1.234"
12345   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12346     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12347       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12348 
12349   const bool IsLiteral =
12350       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12351 
12352   llvm::APFloat Value(0.0);
12353   bool IsConstant =
12354     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12355   if (!IsConstant) {
12356     if (isObjCSignedCharBool(S, T)) {
12357       return adornObjCBoolConversionDiagWithTernaryFixit(
12358           S, E,
12359           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12360               << E->getType());
12361     }
12362 
12363     return DiagnoseImpCast(S, E, T, CContext,
12364                            diag::warn_impcast_float_integer, PruneWarnings);
12365   }
12366 
12367   bool isExact = false;
12368 
12369   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12370                             T->hasUnsignedIntegerRepresentation());
12371   llvm::APFloat::opStatus Result = Value.convertToInteger(
12372       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12373 
12374   // FIXME: Force the precision of the source value down so we don't print
12375   // digits which are usually useless (we don't really care here if we
12376   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12377   // would automatically print the shortest representation, but it's a bit
12378   // tricky to implement.
12379   SmallString<16> PrettySourceValue;
12380   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12381   precision = (precision * 59 + 195) / 196;
12382   Value.toString(PrettySourceValue, precision);
12383 
12384   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12385     return adornObjCBoolConversionDiagWithTernaryFixit(
12386         S, E,
12387         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12388             << PrettySourceValue);
12389   }
12390 
12391   if (Result == llvm::APFloat::opOK && isExact) {
12392     if (IsLiteral) return;
12393     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12394                            PruneWarnings);
12395   }
12396 
12397   // Conversion of a floating-point value to a non-bool integer where the
12398   // integral part cannot be represented by the integer type is undefined.
12399   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12400     return DiagnoseImpCast(
12401         S, E, T, CContext,
12402         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12403                   : diag::warn_impcast_float_to_integer_out_of_range,
12404         PruneWarnings);
12405 
12406   unsigned DiagID = 0;
12407   if (IsLiteral) {
12408     // Warn on floating point literal to integer.
12409     DiagID = diag::warn_impcast_literal_float_to_integer;
12410   } else if (IntegerValue == 0) {
12411     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12412       return DiagnoseImpCast(S, E, T, CContext,
12413                              diag::warn_impcast_float_integer, PruneWarnings);
12414     }
12415     // Warn on non-zero to zero conversion.
12416     DiagID = diag::warn_impcast_float_to_integer_zero;
12417   } else {
12418     if (IntegerValue.isUnsigned()) {
12419       if (!IntegerValue.isMaxValue()) {
12420         return DiagnoseImpCast(S, E, T, CContext,
12421                                diag::warn_impcast_float_integer, PruneWarnings);
12422       }
12423     } else {  // IntegerValue.isSigned()
12424       if (!IntegerValue.isMaxSignedValue() &&
12425           !IntegerValue.isMinSignedValue()) {
12426         return DiagnoseImpCast(S, E, T, CContext,
12427                                diag::warn_impcast_float_integer, PruneWarnings);
12428       }
12429     }
12430     // Warn on evaluatable floating point expression to integer conversion.
12431     DiagID = diag::warn_impcast_float_to_integer;
12432   }
12433 
12434   SmallString<16> PrettyTargetValue;
12435   if (IsBool)
12436     PrettyTargetValue = Value.isZero() ? "false" : "true";
12437   else
12438     IntegerValue.toString(PrettyTargetValue);
12439 
12440   if (PruneWarnings) {
12441     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12442                           S.PDiag(DiagID)
12443                               << E->getType() << T.getUnqualifiedType()
12444                               << PrettySourceValue << PrettyTargetValue
12445                               << E->getSourceRange() << SourceRange(CContext));
12446   } else {
12447     S.Diag(E->getExprLoc(), DiagID)
12448         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12449         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12450   }
12451 }
12452 
12453 /// Analyze the given compound assignment for the possible losing of
12454 /// floating-point precision.
12455 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12456   assert(isa<CompoundAssignOperator>(E) &&
12457          "Must be compound assignment operation");
12458   // Recurse on the LHS and RHS in here
12459   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12460   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12461 
12462   if (E->getLHS()->getType()->isAtomicType())
12463     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12464 
12465   // Now check the outermost expression
12466   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12467   const auto *RBT = cast<CompoundAssignOperator>(E)
12468                         ->getComputationResultType()
12469                         ->getAs<BuiltinType>();
12470 
12471   // The below checks assume source is floating point.
12472   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12473 
12474   // If source is floating point but target is an integer.
12475   if (ResultBT->isInteger())
12476     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12477                            E->getExprLoc(), diag::warn_impcast_float_integer);
12478 
12479   if (!ResultBT->isFloatingPoint())
12480     return;
12481 
12482   // If both source and target are floating points, warn about losing precision.
12483   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12484       QualType(ResultBT, 0), QualType(RBT, 0));
12485   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12486     // warn about dropping FP rank.
12487     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12488                     diag::warn_impcast_float_result_precision);
12489 }
12490 
12491 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12492                                       IntRange Range) {
12493   if (!Range.Width) return "0";
12494 
12495   llvm::APSInt ValueInRange = Value;
12496   ValueInRange.setIsSigned(!Range.NonNegative);
12497   ValueInRange = ValueInRange.trunc(Range.Width);
12498   return toString(ValueInRange, 10);
12499 }
12500 
12501 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12502   if (!isa<ImplicitCastExpr>(Ex))
12503     return false;
12504 
12505   Expr *InnerE = Ex->IgnoreParenImpCasts();
12506   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12507   const Type *Source =
12508     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12509   if (Target->isDependentType())
12510     return false;
12511 
12512   const BuiltinType *FloatCandidateBT =
12513     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12514   const Type *BoolCandidateType = ToBool ? Target : Source;
12515 
12516   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12517           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12518 }
12519 
12520 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12521                                              SourceLocation CC) {
12522   unsigned NumArgs = TheCall->getNumArgs();
12523   for (unsigned i = 0; i < NumArgs; ++i) {
12524     Expr *CurrA = TheCall->getArg(i);
12525     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12526       continue;
12527 
12528     bool IsSwapped = ((i > 0) &&
12529         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12530     IsSwapped |= ((i < (NumArgs - 1)) &&
12531         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12532     if (IsSwapped) {
12533       // Warn on this floating-point to bool conversion.
12534       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12535                       CurrA->getType(), CC,
12536                       diag::warn_impcast_floating_point_to_bool);
12537     }
12538   }
12539 }
12540 
12541 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12542                                    SourceLocation CC) {
12543   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12544                         E->getExprLoc()))
12545     return;
12546 
12547   // Don't warn on functions which have return type nullptr_t.
12548   if (isa<CallExpr>(E))
12549     return;
12550 
12551   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12552   const Expr::NullPointerConstantKind NullKind =
12553       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12554   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12555     return;
12556 
12557   // Return if target type is a safe conversion.
12558   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12559       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12560     return;
12561 
12562   SourceLocation Loc = E->getSourceRange().getBegin();
12563 
12564   // Venture through the macro stacks to get to the source of macro arguments.
12565   // The new location is a better location than the complete location that was
12566   // passed in.
12567   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12568   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12569 
12570   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12571   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12572     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12573         Loc, S.SourceMgr, S.getLangOpts());
12574     if (MacroName == "NULL")
12575       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12576   }
12577 
12578   // Only warn if the null and context location are in the same macro expansion.
12579   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12580     return;
12581 
12582   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12583       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12584       << FixItHint::CreateReplacement(Loc,
12585                                       S.getFixItZeroLiteralForType(T, Loc));
12586 }
12587 
12588 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12589                                   ObjCArrayLiteral *ArrayLiteral);
12590 
12591 static void
12592 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12593                            ObjCDictionaryLiteral *DictionaryLiteral);
12594 
12595 /// Check a single element within a collection literal against the
12596 /// target element type.
12597 static void checkObjCCollectionLiteralElement(Sema &S,
12598                                               QualType TargetElementType,
12599                                               Expr *Element,
12600                                               unsigned ElementKind) {
12601   // Skip a bitcast to 'id' or qualified 'id'.
12602   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12603     if (ICE->getCastKind() == CK_BitCast &&
12604         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12605       Element = ICE->getSubExpr();
12606   }
12607 
12608   QualType ElementType = Element->getType();
12609   ExprResult ElementResult(Element);
12610   if (ElementType->getAs<ObjCObjectPointerType>() &&
12611       S.CheckSingleAssignmentConstraints(TargetElementType,
12612                                          ElementResult,
12613                                          false, false)
12614         != Sema::Compatible) {
12615     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12616         << ElementType << ElementKind << TargetElementType
12617         << Element->getSourceRange();
12618   }
12619 
12620   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12621     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12622   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12623     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12624 }
12625 
12626 /// Check an Objective-C array literal being converted to the given
12627 /// target type.
12628 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12629                                   ObjCArrayLiteral *ArrayLiteral) {
12630   if (!S.NSArrayDecl)
12631     return;
12632 
12633   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12634   if (!TargetObjCPtr)
12635     return;
12636 
12637   if (TargetObjCPtr->isUnspecialized() ||
12638       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12639         != S.NSArrayDecl->getCanonicalDecl())
12640     return;
12641 
12642   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12643   if (TypeArgs.size() != 1)
12644     return;
12645 
12646   QualType TargetElementType = TypeArgs[0];
12647   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12648     checkObjCCollectionLiteralElement(S, TargetElementType,
12649                                       ArrayLiteral->getElement(I),
12650                                       0);
12651   }
12652 }
12653 
12654 /// Check an Objective-C dictionary literal being converted to the given
12655 /// target type.
12656 static void
12657 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12658                            ObjCDictionaryLiteral *DictionaryLiteral) {
12659   if (!S.NSDictionaryDecl)
12660     return;
12661 
12662   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12663   if (!TargetObjCPtr)
12664     return;
12665 
12666   if (TargetObjCPtr->isUnspecialized() ||
12667       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12668         != S.NSDictionaryDecl->getCanonicalDecl())
12669     return;
12670 
12671   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12672   if (TypeArgs.size() != 2)
12673     return;
12674 
12675   QualType TargetKeyType = TypeArgs[0];
12676   QualType TargetObjectType = TypeArgs[1];
12677   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12678     auto Element = DictionaryLiteral->getKeyValueElement(I);
12679     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12680     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12681   }
12682 }
12683 
12684 // Helper function to filter out cases for constant width constant conversion.
12685 // Don't warn on char array initialization or for non-decimal values.
12686 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12687                                           SourceLocation CC) {
12688   // If initializing from a constant, and the constant starts with '0',
12689   // then it is a binary, octal, or hexadecimal.  Allow these constants
12690   // to fill all the bits, even if there is a sign change.
12691   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12692     const char FirstLiteralCharacter =
12693         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12694     if (FirstLiteralCharacter == '0')
12695       return false;
12696   }
12697 
12698   // If the CC location points to a '{', and the type is char, then assume
12699   // assume it is an array initialization.
12700   if (CC.isValid() && T->isCharType()) {
12701     const char FirstContextCharacter =
12702         S.getSourceManager().getCharacterData(CC)[0];
12703     if (FirstContextCharacter == '{')
12704       return false;
12705   }
12706 
12707   return true;
12708 }
12709 
12710 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12711   const auto *IL = dyn_cast<IntegerLiteral>(E);
12712   if (!IL) {
12713     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12714       if (UO->getOpcode() == UO_Minus)
12715         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12716     }
12717   }
12718 
12719   return IL;
12720 }
12721 
12722 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12723   E = E->IgnoreParenImpCasts();
12724   SourceLocation ExprLoc = E->getExprLoc();
12725 
12726   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12727     BinaryOperator::Opcode Opc = BO->getOpcode();
12728     Expr::EvalResult Result;
12729     // Do not diagnose unsigned shifts.
12730     if (Opc == BO_Shl) {
12731       const auto *LHS = getIntegerLiteral(BO->getLHS());
12732       const auto *RHS = getIntegerLiteral(BO->getRHS());
12733       if (LHS && LHS->getValue() == 0)
12734         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12735       else if (!E->isValueDependent() && LHS && RHS &&
12736                RHS->getValue().isNonNegative() &&
12737                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12738         S.Diag(ExprLoc, diag::warn_left_shift_always)
12739             << (Result.Val.getInt() != 0);
12740       else if (E->getType()->isSignedIntegerType())
12741         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12742     }
12743   }
12744 
12745   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12746     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12747     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12748     if (!LHS || !RHS)
12749       return;
12750     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12751         (RHS->getValue() == 0 || RHS->getValue() == 1))
12752       // Do not diagnose common idioms.
12753       return;
12754     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12755       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12756   }
12757 }
12758 
12759 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12760                                     SourceLocation CC,
12761                                     bool *ICContext = nullptr,
12762                                     bool IsListInit = false) {
12763   if (E->isTypeDependent() || E->isValueDependent()) return;
12764 
12765   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12766   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12767   if (Source == Target) return;
12768   if (Target->isDependentType()) return;
12769 
12770   // If the conversion context location is invalid don't complain. We also
12771   // don't want to emit a warning if the issue occurs from the expansion of
12772   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12773   // delay this check as long as possible. Once we detect we are in that
12774   // scenario, we just return.
12775   if (CC.isInvalid())
12776     return;
12777 
12778   if (Source->isAtomicType())
12779     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12780 
12781   // Diagnose implicit casts to bool.
12782   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12783     if (isa<StringLiteral>(E))
12784       // Warn on string literal to bool.  Checks for string literals in logical
12785       // and expressions, for instance, assert(0 && "error here"), are
12786       // prevented by a check in AnalyzeImplicitConversions().
12787       return DiagnoseImpCast(S, E, T, CC,
12788                              diag::warn_impcast_string_literal_to_bool);
12789     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12790         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12791       // This covers the literal expressions that evaluate to Objective-C
12792       // objects.
12793       return DiagnoseImpCast(S, E, T, CC,
12794                              diag::warn_impcast_objective_c_literal_to_bool);
12795     }
12796     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12797       // Warn on pointer to bool conversion that is always true.
12798       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12799                                      SourceRange(CC));
12800     }
12801   }
12802 
12803   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12804   // is a typedef for signed char (macOS), then that constant value has to be 1
12805   // or 0.
12806   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12807     Expr::EvalResult Result;
12808     if (E->EvaluateAsInt(Result, S.getASTContext(),
12809                          Expr::SE_AllowSideEffects)) {
12810       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12811         adornObjCBoolConversionDiagWithTernaryFixit(
12812             S, E,
12813             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12814                 << toString(Result.Val.getInt(), 10));
12815       }
12816       return;
12817     }
12818   }
12819 
12820   // Check implicit casts from Objective-C collection literals to specialized
12821   // collection types, e.g., NSArray<NSString *> *.
12822   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12823     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12824   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12825     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12826 
12827   // Strip vector types.
12828   if (isa<VectorType>(Source)) {
12829     if (Target->isVLSTBuiltinType() &&
12830         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12831                                          QualType(Source, 0)) ||
12832          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12833                                             QualType(Source, 0))))
12834       return;
12835 
12836     if (!isa<VectorType>(Target)) {
12837       if (S.SourceMgr.isInSystemMacro(CC))
12838         return;
12839       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12840     }
12841 
12842     // If the vector cast is cast between two vectors of the same size, it is
12843     // a bitcast, not a conversion.
12844     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12845       return;
12846 
12847     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12848     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12849   }
12850   if (auto VecTy = dyn_cast<VectorType>(Target))
12851     Target = VecTy->getElementType().getTypePtr();
12852 
12853   // Strip complex types.
12854   if (isa<ComplexType>(Source)) {
12855     if (!isa<ComplexType>(Target)) {
12856       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12857         return;
12858 
12859       return DiagnoseImpCast(S, E, T, CC,
12860                              S.getLangOpts().CPlusPlus
12861                                  ? diag::err_impcast_complex_scalar
12862                                  : diag::warn_impcast_complex_scalar);
12863     }
12864 
12865     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12866     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12867   }
12868 
12869   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12870   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12871 
12872   // If the source is floating point...
12873   if (SourceBT && SourceBT->isFloatingPoint()) {
12874     // ...and the target is floating point...
12875     if (TargetBT && TargetBT->isFloatingPoint()) {
12876       // ...then warn if we're dropping FP rank.
12877 
12878       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12879           QualType(SourceBT, 0), QualType(TargetBT, 0));
12880       if (Order > 0) {
12881         // Don't warn about float constants that are precisely
12882         // representable in the target type.
12883         Expr::EvalResult result;
12884         if (E->EvaluateAsRValue(result, S.Context)) {
12885           // Value might be a float, a float vector, or a float complex.
12886           if (IsSameFloatAfterCast(result.Val,
12887                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12888                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12889             return;
12890         }
12891 
12892         if (S.SourceMgr.isInSystemMacro(CC))
12893           return;
12894 
12895         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12896       }
12897       // ... or possibly if we're increasing rank, too
12898       else if (Order < 0) {
12899         if (S.SourceMgr.isInSystemMacro(CC))
12900           return;
12901 
12902         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12903       }
12904       return;
12905     }
12906 
12907     // If the target is integral, always warn.
12908     if (TargetBT && TargetBT->isInteger()) {
12909       if (S.SourceMgr.isInSystemMacro(CC))
12910         return;
12911 
12912       DiagnoseFloatingImpCast(S, E, T, CC);
12913     }
12914 
12915     // Detect the case where a call result is converted from floating-point to
12916     // to bool, and the final argument to the call is converted from bool, to
12917     // discover this typo:
12918     //
12919     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12920     //
12921     // FIXME: This is an incredibly special case; is there some more general
12922     // way to detect this class of misplaced-parentheses bug?
12923     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12924       // Check last argument of function call to see if it is an
12925       // implicit cast from a type matching the type the result
12926       // is being cast to.
12927       CallExpr *CEx = cast<CallExpr>(E);
12928       if (unsigned NumArgs = CEx->getNumArgs()) {
12929         Expr *LastA = CEx->getArg(NumArgs - 1);
12930         Expr *InnerE = LastA->IgnoreParenImpCasts();
12931         if (isa<ImplicitCastExpr>(LastA) &&
12932             InnerE->getType()->isBooleanType()) {
12933           // Warn on this floating-point to bool conversion
12934           DiagnoseImpCast(S, E, T, CC,
12935                           diag::warn_impcast_floating_point_to_bool);
12936         }
12937       }
12938     }
12939     return;
12940   }
12941 
12942   // Valid casts involving fixed point types should be accounted for here.
12943   if (Source->isFixedPointType()) {
12944     if (Target->isUnsaturatedFixedPointType()) {
12945       Expr::EvalResult Result;
12946       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12947                                   S.isConstantEvaluated())) {
12948         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12949         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12950         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12951         if (Value > MaxVal || Value < MinVal) {
12952           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12953                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12954                                     << Value.toString() << T
12955                                     << E->getSourceRange()
12956                                     << clang::SourceRange(CC));
12957           return;
12958         }
12959       }
12960     } else if (Target->isIntegerType()) {
12961       Expr::EvalResult Result;
12962       if (!S.isConstantEvaluated() &&
12963           E->EvaluateAsFixedPoint(Result, S.Context,
12964                                   Expr::SE_AllowSideEffects)) {
12965         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12966 
12967         bool Overflowed;
12968         llvm::APSInt IntResult = FXResult.convertToInt(
12969             S.Context.getIntWidth(T),
12970             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12971 
12972         if (Overflowed) {
12973           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12974                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12975                                     << FXResult.toString() << T
12976                                     << E->getSourceRange()
12977                                     << clang::SourceRange(CC));
12978           return;
12979         }
12980       }
12981     }
12982   } else if (Target->isUnsaturatedFixedPointType()) {
12983     if (Source->isIntegerType()) {
12984       Expr::EvalResult Result;
12985       if (!S.isConstantEvaluated() &&
12986           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12987         llvm::APSInt Value = Result.Val.getInt();
12988 
12989         bool Overflowed;
12990         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12991             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12992 
12993         if (Overflowed) {
12994           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12995                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12996                                     << toString(Value, /*Radix=*/10) << T
12997                                     << E->getSourceRange()
12998                                     << clang::SourceRange(CC));
12999           return;
13000         }
13001       }
13002     }
13003   }
13004 
13005   // If we are casting an integer type to a floating point type without
13006   // initialization-list syntax, we might lose accuracy if the floating
13007   // point type has a narrower significand than the integer type.
13008   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
13009       TargetBT->isFloatingType() && !IsListInit) {
13010     // Determine the number of precision bits in the source integer type.
13011     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
13012                                         /*Approximate*/ true);
13013     unsigned int SourcePrecision = SourceRange.Width;
13014 
13015     // Determine the number of precision bits in the
13016     // target floating point type.
13017     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
13018         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13019 
13020     if (SourcePrecision > 0 && TargetPrecision > 0 &&
13021         SourcePrecision > TargetPrecision) {
13022 
13023       if (Optional<llvm::APSInt> SourceInt =
13024               E->getIntegerConstantExpr(S.Context)) {
13025         // If the source integer is a constant, convert it to the target
13026         // floating point type. Issue a warning if the value changes
13027         // during the whole conversion.
13028         llvm::APFloat TargetFloatValue(
13029             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
13030         llvm::APFloat::opStatus ConversionStatus =
13031             TargetFloatValue.convertFromAPInt(
13032                 *SourceInt, SourceBT->isSignedInteger(),
13033                 llvm::APFloat::rmNearestTiesToEven);
13034 
13035         if (ConversionStatus != llvm::APFloat::opOK) {
13036           SmallString<32> PrettySourceValue;
13037           SourceInt->toString(PrettySourceValue, 10);
13038           SmallString<32> PrettyTargetValue;
13039           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
13040 
13041           S.DiagRuntimeBehavior(
13042               E->getExprLoc(), E,
13043               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
13044                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
13045                   << E->getSourceRange() << clang::SourceRange(CC));
13046         }
13047       } else {
13048         // Otherwise, the implicit conversion may lose precision.
13049         DiagnoseImpCast(S, E, T, CC,
13050                         diag::warn_impcast_integer_float_precision);
13051       }
13052     }
13053   }
13054 
13055   DiagnoseNullConversion(S, E, T, CC);
13056 
13057   S.DiscardMisalignedMemberAddress(Target, E);
13058 
13059   if (Target->isBooleanType())
13060     DiagnoseIntInBoolContext(S, E);
13061 
13062   if (!Source->isIntegerType() || !Target->isIntegerType())
13063     return;
13064 
13065   // TODO: remove this early return once the false positives for constant->bool
13066   // in templates, macros, etc, are reduced or removed.
13067   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
13068     return;
13069 
13070   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
13071       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
13072     return adornObjCBoolConversionDiagWithTernaryFixit(
13073         S, E,
13074         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
13075             << E->getType());
13076   }
13077 
13078   IntRange SourceTypeRange =
13079       IntRange::forTargetOfCanonicalType(S.Context, Source);
13080   IntRange LikelySourceRange =
13081       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
13082   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
13083 
13084   if (LikelySourceRange.Width > TargetRange.Width) {
13085     // If the source is a constant, use a default-on diagnostic.
13086     // TODO: this should happen for bitfield stores, too.
13087     Expr::EvalResult Result;
13088     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
13089                          S.isConstantEvaluated())) {
13090       llvm::APSInt Value(32);
13091       Value = Result.Val.getInt();
13092 
13093       if (S.SourceMgr.isInSystemMacro(CC))
13094         return;
13095 
13096       std::string PrettySourceValue = toString(Value, 10);
13097       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13098 
13099       S.DiagRuntimeBehavior(
13100           E->getExprLoc(), E,
13101           S.PDiag(diag::warn_impcast_integer_precision_constant)
13102               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13103               << E->getSourceRange() << SourceRange(CC));
13104       return;
13105     }
13106 
13107     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13108     if (S.SourceMgr.isInSystemMacro(CC))
13109       return;
13110 
13111     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13112       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13113                              /* pruneControlFlow */ true);
13114     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13115   }
13116 
13117   if (TargetRange.Width > SourceTypeRange.Width) {
13118     if (auto *UO = dyn_cast<UnaryOperator>(E))
13119       if (UO->getOpcode() == UO_Minus)
13120         if (Source->isUnsignedIntegerType()) {
13121           if (Target->isUnsignedIntegerType())
13122             return DiagnoseImpCast(S, E, T, CC,
13123                                    diag::warn_impcast_high_order_zero_bits);
13124           if (Target->isSignedIntegerType())
13125             return DiagnoseImpCast(S, E, T, CC,
13126                                    diag::warn_impcast_nonnegative_result);
13127         }
13128   }
13129 
13130   if (TargetRange.Width == LikelySourceRange.Width &&
13131       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13132       Source->isSignedIntegerType()) {
13133     // Warn when doing a signed to signed conversion, warn if the positive
13134     // source value is exactly the width of the target type, which will
13135     // cause a negative value to be stored.
13136 
13137     Expr::EvalResult Result;
13138     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13139         !S.SourceMgr.isInSystemMacro(CC)) {
13140       llvm::APSInt Value = Result.Val.getInt();
13141       if (isSameWidthConstantConversion(S, E, T, CC)) {
13142         std::string PrettySourceValue = toString(Value, 10);
13143         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13144 
13145         S.DiagRuntimeBehavior(
13146             E->getExprLoc(), E,
13147             S.PDiag(diag::warn_impcast_integer_precision_constant)
13148                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13149                 << E->getSourceRange() << SourceRange(CC));
13150         return;
13151       }
13152     }
13153 
13154     // Fall through for non-constants to give a sign conversion warning.
13155   }
13156 
13157   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13158       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13159        LikelySourceRange.Width == TargetRange.Width)) {
13160     if (S.SourceMgr.isInSystemMacro(CC))
13161       return;
13162 
13163     unsigned DiagID = diag::warn_impcast_integer_sign;
13164 
13165     // Traditionally, gcc has warned about this under -Wsign-compare.
13166     // We also want to warn about it in -Wconversion.
13167     // So if -Wconversion is off, use a completely identical diagnostic
13168     // in the sign-compare group.
13169     // The conditional-checking code will
13170     if (ICContext) {
13171       DiagID = diag::warn_impcast_integer_sign_conditional;
13172       *ICContext = true;
13173     }
13174 
13175     return DiagnoseImpCast(S, E, T, CC, DiagID);
13176   }
13177 
13178   // Diagnose conversions between different enumeration types.
13179   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13180   // type, to give us better diagnostics.
13181   QualType SourceType = E->getType();
13182   if (!S.getLangOpts().CPlusPlus) {
13183     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13184       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13185         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13186         SourceType = S.Context.getTypeDeclType(Enum);
13187         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13188       }
13189   }
13190 
13191   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13192     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13193       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13194           TargetEnum->getDecl()->hasNameForLinkage() &&
13195           SourceEnum != TargetEnum) {
13196         if (S.SourceMgr.isInSystemMacro(CC))
13197           return;
13198 
13199         return DiagnoseImpCast(S, E, SourceType, T, CC,
13200                                diag::warn_impcast_different_enum_types);
13201       }
13202 }
13203 
13204 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13205                                      SourceLocation CC, QualType T);
13206 
13207 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13208                                     SourceLocation CC, bool &ICContext) {
13209   E = E->IgnoreParenImpCasts();
13210 
13211   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13212     return CheckConditionalOperator(S, CO, CC, T);
13213 
13214   AnalyzeImplicitConversions(S, E, CC);
13215   if (E->getType() != T)
13216     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13217 }
13218 
13219 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13220                                      SourceLocation CC, QualType T) {
13221   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13222 
13223   Expr *TrueExpr = E->getTrueExpr();
13224   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13225     TrueExpr = BCO->getCommon();
13226 
13227   bool Suspicious = false;
13228   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13229   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13230 
13231   if (T->isBooleanType())
13232     DiagnoseIntInBoolContext(S, E);
13233 
13234   // If -Wconversion would have warned about either of the candidates
13235   // for a signedness conversion to the context type...
13236   if (!Suspicious) return;
13237 
13238   // ...but it's currently ignored...
13239   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13240     return;
13241 
13242   // ...then check whether it would have warned about either of the
13243   // candidates for a signedness conversion to the condition type.
13244   if (E->getType() == T) return;
13245 
13246   Suspicious = false;
13247   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13248                           E->getType(), CC, &Suspicious);
13249   if (!Suspicious)
13250     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13251                             E->getType(), CC, &Suspicious);
13252 }
13253 
13254 /// Check conversion of given expression to boolean.
13255 /// Input argument E is a logical expression.
13256 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13257   if (S.getLangOpts().Bool)
13258     return;
13259   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13260     return;
13261   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13262 }
13263 
13264 namespace {
13265 struct AnalyzeImplicitConversionsWorkItem {
13266   Expr *E;
13267   SourceLocation CC;
13268   bool IsListInit;
13269 };
13270 }
13271 
13272 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13273 /// that should be visited are added to WorkList.
13274 static void AnalyzeImplicitConversions(
13275     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13276     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13277   Expr *OrigE = Item.E;
13278   SourceLocation CC = Item.CC;
13279 
13280   QualType T = OrigE->getType();
13281   Expr *E = OrigE->IgnoreParenImpCasts();
13282 
13283   // Propagate whether we are in a C++ list initialization expression.
13284   // If so, we do not issue warnings for implicit int-float conversion
13285   // precision loss, because C++11 narrowing already handles it.
13286   bool IsListInit = Item.IsListInit ||
13287                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13288 
13289   if (E->isTypeDependent() || E->isValueDependent())
13290     return;
13291 
13292   Expr *SourceExpr = E;
13293   // Examine, but don't traverse into the source expression of an
13294   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13295   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13296   // evaluate it in the context of checking the specific conversion to T though.
13297   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13298     if (auto *Src = OVE->getSourceExpr())
13299       SourceExpr = Src;
13300 
13301   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13302     if (UO->getOpcode() == UO_Not &&
13303         UO->getSubExpr()->isKnownToHaveBooleanValue())
13304       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13305           << OrigE->getSourceRange() << T->isBooleanType()
13306           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13307 
13308   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13309     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13310         BO->getLHS()->isKnownToHaveBooleanValue() &&
13311         BO->getRHS()->isKnownToHaveBooleanValue() &&
13312         BO->getLHS()->HasSideEffects(S.Context) &&
13313         BO->getRHS()->HasSideEffects(S.Context)) {
13314       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13315           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13316           << FixItHint::CreateReplacement(
13317                  BO->getOperatorLoc(),
13318                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13319       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13320     }
13321 
13322   // For conditional operators, we analyze the arguments as if they
13323   // were being fed directly into the output.
13324   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13325     CheckConditionalOperator(S, CO, CC, T);
13326     return;
13327   }
13328 
13329   // Check implicit argument conversions for function calls.
13330   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13331     CheckImplicitArgumentConversions(S, Call, CC);
13332 
13333   // Go ahead and check any implicit conversions we might have skipped.
13334   // The non-canonical typecheck is just an optimization;
13335   // CheckImplicitConversion will filter out dead implicit conversions.
13336   if (SourceExpr->getType() != T)
13337     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13338 
13339   // Now continue drilling into this expression.
13340 
13341   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13342     // The bound subexpressions in a PseudoObjectExpr are not reachable
13343     // as transitive children.
13344     // FIXME: Use a more uniform representation for this.
13345     for (auto *SE : POE->semantics())
13346       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13347         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13348   }
13349 
13350   // Skip past explicit casts.
13351   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13352     E = CE->getSubExpr()->IgnoreParenImpCasts();
13353     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13354       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13355     WorkList.push_back({E, CC, IsListInit});
13356     return;
13357   }
13358 
13359   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13360     // Do a somewhat different check with comparison operators.
13361     if (BO->isComparisonOp())
13362       return AnalyzeComparison(S, BO);
13363 
13364     // And with simple assignments.
13365     if (BO->getOpcode() == BO_Assign)
13366       return AnalyzeAssignment(S, BO);
13367     // And with compound assignments.
13368     if (BO->isAssignmentOp())
13369       return AnalyzeCompoundAssignment(S, BO);
13370   }
13371 
13372   // These break the otherwise-useful invariant below.  Fortunately,
13373   // we don't really need to recurse into them, because any internal
13374   // expressions should have been analyzed already when they were
13375   // built into statements.
13376   if (isa<StmtExpr>(E)) return;
13377 
13378   // Don't descend into unevaluated contexts.
13379   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13380 
13381   // Now just recurse over the expression's children.
13382   CC = E->getExprLoc();
13383   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13384   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13385   for (Stmt *SubStmt : E->children()) {
13386     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13387     if (!ChildExpr)
13388       continue;
13389 
13390     if (IsLogicalAndOperator &&
13391         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13392       // Ignore checking string literals that are in logical and operators.
13393       // This is a common pattern for asserts.
13394       continue;
13395     WorkList.push_back({ChildExpr, CC, IsListInit});
13396   }
13397 
13398   if (BO && BO->isLogicalOp()) {
13399     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13400     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13401       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13402 
13403     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13404     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13405       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13406   }
13407 
13408   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13409     if (U->getOpcode() == UO_LNot) {
13410       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13411     } else if (U->getOpcode() != UO_AddrOf) {
13412       if (U->getSubExpr()->getType()->isAtomicType())
13413         S.Diag(U->getSubExpr()->getBeginLoc(),
13414                diag::warn_atomic_implicit_seq_cst);
13415     }
13416   }
13417 }
13418 
13419 /// AnalyzeImplicitConversions - Find and report any interesting
13420 /// implicit conversions in the given expression.  There are a couple
13421 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13422 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13423                                        bool IsListInit/*= false*/) {
13424   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13425   WorkList.push_back({OrigE, CC, IsListInit});
13426   while (!WorkList.empty())
13427     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13428 }
13429 
13430 /// Diagnose integer type and any valid implicit conversion to it.
13431 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13432   // Taking into account implicit conversions,
13433   // allow any integer.
13434   if (!E->getType()->isIntegerType()) {
13435     S.Diag(E->getBeginLoc(),
13436            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13437     return true;
13438   }
13439   // Potentially emit standard warnings for implicit conversions if enabled
13440   // using -Wconversion.
13441   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13442   return false;
13443 }
13444 
13445 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13446 // Returns true when emitting a warning about taking the address of a reference.
13447 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13448                               const PartialDiagnostic &PD) {
13449   E = E->IgnoreParenImpCasts();
13450 
13451   const FunctionDecl *FD = nullptr;
13452 
13453   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13454     if (!DRE->getDecl()->getType()->isReferenceType())
13455       return false;
13456   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13457     if (!M->getMemberDecl()->getType()->isReferenceType())
13458       return false;
13459   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13460     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13461       return false;
13462     FD = Call->getDirectCallee();
13463   } else {
13464     return false;
13465   }
13466 
13467   SemaRef.Diag(E->getExprLoc(), PD);
13468 
13469   // If possible, point to location of function.
13470   if (FD) {
13471     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13472   }
13473 
13474   return true;
13475 }
13476 
13477 // Returns true if the SourceLocation is expanded from any macro body.
13478 // Returns false if the SourceLocation is invalid, is from not in a macro
13479 // expansion, or is from expanded from a top-level macro argument.
13480 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13481   if (Loc.isInvalid())
13482     return false;
13483 
13484   while (Loc.isMacroID()) {
13485     if (SM.isMacroBodyExpansion(Loc))
13486       return true;
13487     Loc = SM.getImmediateMacroCallerLoc(Loc);
13488   }
13489 
13490   return false;
13491 }
13492 
13493 /// Diagnose pointers that are always non-null.
13494 /// \param E the expression containing the pointer
13495 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13496 /// compared to a null pointer
13497 /// \param IsEqual True when the comparison is equal to a null pointer
13498 /// \param Range Extra SourceRange to highlight in the diagnostic
13499 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13500                                         Expr::NullPointerConstantKind NullKind,
13501                                         bool IsEqual, SourceRange Range) {
13502   if (!E)
13503     return;
13504 
13505   // Don't warn inside macros.
13506   if (E->getExprLoc().isMacroID()) {
13507     const SourceManager &SM = getSourceManager();
13508     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13509         IsInAnyMacroBody(SM, Range.getBegin()))
13510       return;
13511   }
13512   E = E->IgnoreImpCasts();
13513 
13514   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13515 
13516   if (isa<CXXThisExpr>(E)) {
13517     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13518                                 : diag::warn_this_bool_conversion;
13519     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13520     return;
13521   }
13522 
13523   bool IsAddressOf = false;
13524 
13525   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13526     if (UO->getOpcode() != UO_AddrOf)
13527       return;
13528     IsAddressOf = true;
13529     E = UO->getSubExpr();
13530   }
13531 
13532   if (IsAddressOf) {
13533     unsigned DiagID = IsCompare
13534                           ? diag::warn_address_of_reference_null_compare
13535                           : diag::warn_address_of_reference_bool_conversion;
13536     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13537                                          << IsEqual;
13538     if (CheckForReference(*this, E, PD)) {
13539       return;
13540     }
13541   }
13542 
13543   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13544     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13545     std::string Str;
13546     llvm::raw_string_ostream S(Str);
13547     E->printPretty(S, nullptr, getPrintingPolicy());
13548     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13549                                 : diag::warn_cast_nonnull_to_bool;
13550     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13551       << E->getSourceRange() << Range << IsEqual;
13552     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13553   };
13554 
13555   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13556   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13557     if (auto *Callee = Call->getDirectCallee()) {
13558       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13559         ComplainAboutNonnullParamOrCall(A);
13560         return;
13561       }
13562     }
13563   }
13564 
13565   // Expect to find a single Decl.  Skip anything more complicated.
13566   ValueDecl *D = nullptr;
13567   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13568     D = R->getDecl();
13569   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13570     D = M->getMemberDecl();
13571   }
13572 
13573   // Weak Decls can be null.
13574   if (!D || D->isWeak())
13575     return;
13576 
13577   // Check for parameter decl with nonnull attribute
13578   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13579     if (getCurFunction() &&
13580         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13581       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13582         ComplainAboutNonnullParamOrCall(A);
13583         return;
13584       }
13585 
13586       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13587         // Skip function template not specialized yet.
13588         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13589           return;
13590         auto ParamIter = llvm::find(FD->parameters(), PV);
13591         assert(ParamIter != FD->param_end());
13592         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13593 
13594         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13595           if (!NonNull->args_size()) {
13596               ComplainAboutNonnullParamOrCall(NonNull);
13597               return;
13598           }
13599 
13600           for (const ParamIdx &ArgNo : NonNull->args()) {
13601             if (ArgNo.getASTIndex() == ParamNo) {
13602               ComplainAboutNonnullParamOrCall(NonNull);
13603               return;
13604             }
13605           }
13606         }
13607       }
13608     }
13609   }
13610 
13611   QualType T = D->getType();
13612   const bool IsArray = T->isArrayType();
13613   const bool IsFunction = T->isFunctionType();
13614 
13615   // Address of function is used to silence the function warning.
13616   if (IsAddressOf && IsFunction) {
13617     return;
13618   }
13619 
13620   // Found nothing.
13621   if (!IsAddressOf && !IsFunction && !IsArray)
13622     return;
13623 
13624   // Pretty print the expression for the diagnostic.
13625   std::string Str;
13626   llvm::raw_string_ostream S(Str);
13627   E->printPretty(S, nullptr, getPrintingPolicy());
13628 
13629   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13630                               : diag::warn_impcast_pointer_to_bool;
13631   enum {
13632     AddressOf,
13633     FunctionPointer,
13634     ArrayPointer
13635   } DiagType;
13636   if (IsAddressOf)
13637     DiagType = AddressOf;
13638   else if (IsFunction)
13639     DiagType = FunctionPointer;
13640   else if (IsArray)
13641     DiagType = ArrayPointer;
13642   else
13643     llvm_unreachable("Could not determine diagnostic.");
13644   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13645                                 << Range << IsEqual;
13646 
13647   if (!IsFunction)
13648     return;
13649 
13650   // Suggest '&' to silence the function warning.
13651   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13652       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13653 
13654   // Check to see if '()' fixit should be emitted.
13655   QualType ReturnType;
13656   UnresolvedSet<4> NonTemplateOverloads;
13657   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13658   if (ReturnType.isNull())
13659     return;
13660 
13661   if (IsCompare) {
13662     // There are two cases here.  If there is null constant, the only suggest
13663     // for a pointer return type.  If the null is 0, then suggest if the return
13664     // type is a pointer or an integer type.
13665     if (!ReturnType->isPointerType()) {
13666       if (NullKind == Expr::NPCK_ZeroExpression ||
13667           NullKind == Expr::NPCK_ZeroLiteral) {
13668         if (!ReturnType->isIntegerType())
13669           return;
13670       } else {
13671         return;
13672       }
13673     }
13674   } else { // !IsCompare
13675     // For function to bool, only suggest if the function pointer has bool
13676     // return type.
13677     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13678       return;
13679   }
13680   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13681       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13682 }
13683 
13684 /// Diagnoses "dangerous" implicit conversions within the given
13685 /// expression (which is a full expression).  Implements -Wconversion
13686 /// and -Wsign-compare.
13687 ///
13688 /// \param CC the "context" location of the implicit conversion, i.e.
13689 ///   the most location of the syntactic entity requiring the implicit
13690 ///   conversion
13691 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13692   // Don't diagnose in unevaluated contexts.
13693   if (isUnevaluatedContext())
13694     return;
13695 
13696   // Don't diagnose for value- or type-dependent expressions.
13697   if (E->isTypeDependent() || E->isValueDependent())
13698     return;
13699 
13700   // Check for array bounds violations in cases where the check isn't triggered
13701   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13702   // ArraySubscriptExpr is on the RHS of a variable initialization.
13703   CheckArrayAccess(E);
13704 
13705   // This is not the right CC for (e.g.) a variable initialization.
13706   AnalyzeImplicitConversions(*this, E, CC);
13707 }
13708 
13709 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13710 /// Input argument E is a logical expression.
13711 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13712   ::CheckBoolLikeConversion(*this, E, CC);
13713 }
13714 
13715 /// Diagnose when expression is an integer constant expression and its evaluation
13716 /// results in integer overflow
13717 void Sema::CheckForIntOverflow (Expr *E) {
13718   // Use a work list to deal with nested struct initializers.
13719   SmallVector<Expr *, 2> Exprs(1, E);
13720 
13721   do {
13722     Expr *OriginalE = Exprs.pop_back_val();
13723     Expr *E = OriginalE->IgnoreParenCasts();
13724 
13725     if (isa<BinaryOperator>(E)) {
13726       E->EvaluateForOverflow(Context);
13727       continue;
13728     }
13729 
13730     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13731       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13732     else if (isa<ObjCBoxedExpr>(OriginalE))
13733       E->EvaluateForOverflow(Context);
13734     else if (auto Call = dyn_cast<CallExpr>(E))
13735       Exprs.append(Call->arg_begin(), Call->arg_end());
13736     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13737       Exprs.append(Message->arg_begin(), Message->arg_end());
13738   } while (!Exprs.empty());
13739 }
13740 
13741 namespace {
13742 
13743 /// Visitor for expressions which looks for unsequenced operations on the
13744 /// same object.
13745 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13746   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13747 
13748   /// A tree of sequenced regions within an expression. Two regions are
13749   /// unsequenced if one is an ancestor or a descendent of the other. When we
13750   /// finish processing an expression with sequencing, such as a comma
13751   /// expression, we fold its tree nodes into its parent, since they are
13752   /// unsequenced with respect to nodes we will visit later.
13753   class SequenceTree {
13754     struct Value {
13755       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13756       unsigned Parent : 31;
13757       unsigned Merged : 1;
13758     };
13759     SmallVector<Value, 8> Values;
13760 
13761   public:
13762     /// A region within an expression which may be sequenced with respect
13763     /// to some other region.
13764     class Seq {
13765       friend class SequenceTree;
13766 
13767       unsigned Index;
13768 
13769       explicit Seq(unsigned N) : Index(N) {}
13770 
13771     public:
13772       Seq() : Index(0) {}
13773     };
13774 
13775     SequenceTree() { Values.push_back(Value(0)); }
13776     Seq root() const { return Seq(0); }
13777 
13778     /// Create a new sequence of operations, which is an unsequenced
13779     /// subset of \p Parent. This sequence of operations is sequenced with
13780     /// respect to other children of \p Parent.
13781     Seq allocate(Seq Parent) {
13782       Values.push_back(Value(Parent.Index));
13783       return Seq(Values.size() - 1);
13784     }
13785 
13786     /// Merge a sequence of operations into its parent.
13787     void merge(Seq S) {
13788       Values[S.Index].Merged = true;
13789     }
13790 
13791     /// Determine whether two operations are unsequenced. This operation
13792     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13793     /// should have been merged into its parent as appropriate.
13794     bool isUnsequenced(Seq Cur, Seq Old) {
13795       unsigned C = representative(Cur.Index);
13796       unsigned Target = representative(Old.Index);
13797       while (C >= Target) {
13798         if (C == Target)
13799           return true;
13800         C = Values[C].Parent;
13801       }
13802       return false;
13803     }
13804 
13805   private:
13806     /// Pick a representative for a sequence.
13807     unsigned representative(unsigned K) {
13808       if (Values[K].Merged)
13809         // Perform path compression as we go.
13810         return Values[K].Parent = representative(Values[K].Parent);
13811       return K;
13812     }
13813   };
13814 
13815   /// An object for which we can track unsequenced uses.
13816   using Object = const NamedDecl *;
13817 
13818   /// Different flavors of object usage which we track. We only track the
13819   /// least-sequenced usage of each kind.
13820   enum UsageKind {
13821     /// A read of an object. Multiple unsequenced reads are OK.
13822     UK_Use,
13823 
13824     /// A modification of an object which is sequenced before the value
13825     /// computation of the expression, such as ++n in C++.
13826     UK_ModAsValue,
13827 
13828     /// A modification of an object which is not sequenced before the value
13829     /// computation of the expression, such as n++.
13830     UK_ModAsSideEffect,
13831 
13832     UK_Count = UK_ModAsSideEffect + 1
13833   };
13834 
13835   /// Bundle together a sequencing region and the expression corresponding
13836   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13837   struct Usage {
13838     const Expr *UsageExpr;
13839     SequenceTree::Seq Seq;
13840 
13841     Usage() : UsageExpr(nullptr), Seq() {}
13842   };
13843 
13844   struct UsageInfo {
13845     Usage Uses[UK_Count];
13846 
13847     /// Have we issued a diagnostic for this object already?
13848     bool Diagnosed;
13849 
13850     UsageInfo() : Uses(), Diagnosed(false) {}
13851   };
13852   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13853 
13854   Sema &SemaRef;
13855 
13856   /// Sequenced regions within the expression.
13857   SequenceTree Tree;
13858 
13859   /// Declaration modifications and references which we have seen.
13860   UsageInfoMap UsageMap;
13861 
13862   /// The region we are currently within.
13863   SequenceTree::Seq Region;
13864 
13865   /// Filled in with declarations which were modified as a side-effect
13866   /// (that is, post-increment operations).
13867   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13868 
13869   /// Expressions to check later. We defer checking these to reduce
13870   /// stack usage.
13871   SmallVectorImpl<const Expr *> &WorkList;
13872 
13873   /// RAII object wrapping the visitation of a sequenced subexpression of an
13874   /// expression. At the end of this process, the side-effects of the evaluation
13875   /// become sequenced with respect to the value computation of the result, so
13876   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13877   /// UK_ModAsValue.
13878   struct SequencedSubexpression {
13879     SequencedSubexpression(SequenceChecker &Self)
13880       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13881       Self.ModAsSideEffect = &ModAsSideEffect;
13882     }
13883 
13884     ~SequencedSubexpression() {
13885       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13886         // Add a new usage with usage kind UK_ModAsValue, and then restore
13887         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13888         // the previous one was empty).
13889         UsageInfo &UI = Self.UsageMap[M.first];
13890         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13891         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13892         SideEffectUsage = M.second;
13893       }
13894       Self.ModAsSideEffect = OldModAsSideEffect;
13895     }
13896 
13897     SequenceChecker &Self;
13898     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13899     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13900   };
13901 
13902   /// RAII object wrapping the visitation of a subexpression which we might
13903   /// choose to evaluate as a constant. If any subexpression is evaluated and
13904   /// found to be non-constant, this allows us to suppress the evaluation of
13905   /// the outer expression.
13906   class EvaluationTracker {
13907   public:
13908     EvaluationTracker(SequenceChecker &Self)
13909         : Self(Self), Prev(Self.EvalTracker) {
13910       Self.EvalTracker = this;
13911     }
13912 
13913     ~EvaluationTracker() {
13914       Self.EvalTracker = Prev;
13915       if (Prev)
13916         Prev->EvalOK &= EvalOK;
13917     }
13918 
13919     bool evaluate(const Expr *E, bool &Result) {
13920       if (!EvalOK || E->isValueDependent())
13921         return false;
13922       EvalOK = E->EvaluateAsBooleanCondition(
13923           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13924       return EvalOK;
13925     }
13926 
13927   private:
13928     SequenceChecker &Self;
13929     EvaluationTracker *Prev;
13930     bool EvalOK = true;
13931   } *EvalTracker = nullptr;
13932 
13933   /// Find the object which is produced by the specified expression,
13934   /// if any.
13935   Object getObject(const Expr *E, bool Mod) const {
13936     E = E->IgnoreParenCasts();
13937     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13938       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13939         return getObject(UO->getSubExpr(), Mod);
13940     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13941       if (BO->getOpcode() == BO_Comma)
13942         return getObject(BO->getRHS(), Mod);
13943       if (Mod && BO->isAssignmentOp())
13944         return getObject(BO->getLHS(), Mod);
13945     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13946       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13947       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13948         return ME->getMemberDecl();
13949     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13950       // FIXME: If this is a reference, map through to its value.
13951       return DRE->getDecl();
13952     return nullptr;
13953   }
13954 
13955   /// Note that an object \p O was modified or used by an expression
13956   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13957   /// the object \p O as obtained via the \p UsageMap.
13958   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13959     // Get the old usage for the given object and usage kind.
13960     Usage &U = UI.Uses[UK];
13961     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13962       // If we have a modification as side effect and are in a sequenced
13963       // subexpression, save the old Usage so that we can restore it later
13964       // in SequencedSubexpression::~SequencedSubexpression.
13965       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13966         ModAsSideEffect->push_back(std::make_pair(O, U));
13967       // Then record the new usage with the current sequencing region.
13968       U.UsageExpr = UsageExpr;
13969       U.Seq = Region;
13970     }
13971   }
13972 
13973   /// Check whether a modification or use of an object \p O in an expression
13974   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13975   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13976   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13977   /// usage and false we are checking for a mod-use unsequenced usage.
13978   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13979                   UsageKind OtherKind, bool IsModMod) {
13980     if (UI.Diagnosed)
13981       return;
13982 
13983     const Usage &U = UI.Uses[OtherKind];
13984     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13985       return;
13986 
13987     const Expr *Mod = U.UsageExpr;
13988     const Expr *ModOrUse = UsageExpr;
13989     if (OtherKind == UK_Use)
13990       std::swap(Mod, ModOrUse);
13991 
13992     SemaRef.DiagRuntimeBehavior(
13993         Mod->getExprLoc(), {Mod, ModOrUse},
13994         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13995                                : diag::warn_unsequenced_mod_use)
13996             << O << SourceRange(ModOrUse->getExprLoc()));
13997     UI.Diagnosed = true;
13998   }
13999 
14000   // A note on note{Pre, Post}{Use, Mod}:
14001   //
14002   // (It helps to follow the algorithm with an expression such as
14003   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
14004   //  operations before C++17 and both are well-defined in C++17).
14005   //
14006   // When visiting a node which uses/modify an object we first call notePreUse
14007   // or notePreMod before visiting its sub-expression(s). At this point the
14008   // children of the current node have not yet been visited and so the eventual
14009   // uses/modifications resulting from the children of the current node have not
14010   // been recorded yet.
14011   //
14012   // We then visit the children of the current node. After that notePostUse or
14013   // notePostMod is called. These will 1) detect an unsequenced modification
14014   // as side effect (as in "k++ + k") and 2) add a new usage with the
14015   // appropriate usage kind.
14016   //
14017   // We also have to be careful that some operation sequences modification as
14018   // side effect as well (for example: || or ,). To account for this we wrap
14019   // the visitation of such a sub-expression (for example: the LHS of || or ,)
14020   // with SequencedSubexpression. SequencedSubexpression is an RAII object
14021   // which record usages which are modifications as side effect, and then
14022   // downgrade them (or more accurately restore the previous usage which was a
14023   // modification as side effect) when exiting the scope of the sequenced
14024   // subexpression.
14025 
14026   void notePreUse(Object O, const Expr *UseExpr) {
14027     UsageInfo &UI = UsageMap[O];
14028     // Uses conflict with other modifications.
14029     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
14030   }
14031 
14032   void notePostUse(Object O, const Expr *UseExpr) {
14033     UsageInfo &UI = UsageMap[O];
14034     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
14035                /*IsModMod=*/false);
14036     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
14037   }
14038 
14039   void notePreMod(Object O, const Expr *ModExpr) {
14040     UsageInfo &UI = UsageMap[O];
14041     // Modifications conflict with other modifications and with uses.
14042     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
14043     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
14044   }
14045 
14046   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
14047     UsageInfo &UI = UsageMap[O];
14048     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
14049                /*IsModMod=*/true);
14050     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
14051   }
14052 
14053 public:
14054   SequenceChecker(Sema &S, const Expr *E,
14055                   SmallVectorImpl<const Expr *> &WorkList)
14056       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
14057     Visit(E);
14058     // Silence a -Wunused-private-field since WorkList is now unused.
14059     // TODO: Evaluate if it can be used, and if not remove it.
14060     (void)this->WorkList;
14061   }
14062 
14063   void VisitStmt(const Stmt *S) {
14064     // Skip all statements which aren't expressions for now.
14065   }
14066 
14067   void VisitExpr(const Expr *E) {
14068     // By default, just recurse to evaluated subexpressions.
14069     Base::VisitStmt(E);
14070   }
14071 
14072   void VisitCastExpr(const CastExpr *E) {
14073     Object O = Object();
14074     if (E->getCastKind() == CK_LValueToRValue)
14075       O = getObject(E->getSubExpr(), false);
14076 
14077     if (O)
14078       notePreUse(O, E);
14079     VisitExpr(E);
14080     if (O)
14081       notePostUse(O, E);
14082   }
14083 
14084   void VisitSequencedExpressions(const Expr *SequencedBefore,
14085                                  const Expr *SequencedAfter) {
14086     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
14087     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
14088     SequenceTree::Seq OldRegion = Region;
14089 
14090     {
14091       SequencedSubexpression SeqBefore(*this);
14092       Region = BeforeRegion;
14093       Visit(SequencedBefore);
14094     }
14095 
14096     Region = AfterRegion;
14097     Visit(SequencedAfter);
14098 
14099     Region = OldRegion;
14100 
14101     Tree.merge(BeforeRegion);
14102     Tree.merge(AfterRegion);
14103   }
14104 
14105   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
14106     // C++17 [expr.sub]p1:
14107     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14108     //   expression E1 is sequenced before the expression E2.
14109     if (SemaRef.getLangOpts().CPlusPlus17)
14110       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14111     else {
14112       Visit(ASE->getLHS());
14113       Visit(ASE->getRHS());
14114     }
14115   }
14116 
14117   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14118   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14119   void VisitBinPtrMem(const BinaryOperator *BO) {
14120     // C++17 [expr.mptr.oper]p4:
14121     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14122     //  the expression E1 is sequenced before the expression E2.
14123     if (SemaRef.getLangOpts().CPlusPlus17)
14124       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14125     else {
14126       Visit(BO->getLHS());
14127       Visit(BO->getRHS());
14128     }
14129   }
14130 
14131   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14132   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14133   void VisitBinShlShr(const BinaryOperator *BO) {
14134     // C++17 [expr.shift]p4:
14135     //  The expression E1 is sequenced before the expression E2.
14136     if (SemaRef.getLangOpts().CPlusPlus17)
14137       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14138     else {
14139       Visit(BO->getLHS());
14140       Visit(BO->getRHS());
14141     }
14142   }
14143 
14144   void VisitBinComma(const BinaryOperator *BO) {
14145     // C++11 [expr.comma]p1:
14146     //   Every value computation and side effect associated with the left
14147     //   expression is sequenced before every value computation and side
14148     //   effect associated with the right expression.
14149     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14150   }
14151 
14152   void VisitBinAssign(const BinaryOperator *BO) {
14153     SequenceTree::Seq RHSRegion;
14154     SequenceTree::Seq LHSRegion;
14155     if (SemaRef.getLangOpts().CPlusPlus17) {
14156       RHSRegion = Tree.allocate(Region);
14157       LHSRegion = Tree.allocate(Region);
14158     } else {
14159       RHSRegion = Region;
14160       LHSRegion = Region;
14161     }
14162     SequenceTree::Seq OldRegion = Region;
14163 
14164     // C++11 [expr.ass]p1:
14165     //  [...] the assignment is sequenced after the value computation
14166     //  of the right and left operands, [...]
14167     //
14168     // so check it before inspecting the operands and update the
14169     // map afterwards.
14170     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14171     if (O)
14172       notePreMod(O, BO);
14173 
14174     if (SemaRef.getLangOpts().CPlusPlus17) {
14175       // C++17 [expr.ass]p1:
14176       //  [...] The right operand is sequenced before the left operand. [...]
14177       {
14178         SequencedSubexpression SeqBefore(*this);
14179         Region = RHSRegion;
14180         Visit(BO->getRHS());
14181       }
14182 
14183       Region = LHSRegion;
14184       Visit(BO->getLHS());
14185 
14186       if (O && isa<CompoundAssignOperator>(BO))
14187         notePostUse(O, BO);
14188 
14189     } else {
14190       // C++11 does not specify any sequencing between the LHS and RHS.
14191       Region = LHSRegion;
14192       Visit(BO->getLHS());
14193 
14194       if (O && isa<CompoundAssignOperator>(BO))
14195         notePostUse(O, BO);
14196 
14197       Region = RHSRegion;
14198       Visit(BO->getRHS());
14199     }
14200 
14201     // C++11 [expr.ass]p1:
14202     //  the assignment is sequenced [...] before the value computation of the
14203     //  assignment expression.
14204     // C11 6.5.16/3 has no such rule.
14205     Region = OldRegion;
14206     if (O)
14207       notePostMod(O, BO,
14208                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14209                                                   : UK_ModAsSideEffect);
14210     if (SemaRef.getLangOpts().CPlusPlus17) {
14211       Tree.merge(RHSRegion);
14212       Tree.merge(LHSRegion);
14213     }
14214   }
14215 
14216   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14217     VisitBinAssign(CAO);
14218   }
14219 
14220   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14221   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14222   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14223     Object O = getObject(UO->getSubExpr(), true);
14224     if (!O)
14225       return VisitExpr(UO);
14226 
14227     notePreMod(O, UO);
14228     Visit(UO->getSubExpr());
14229     // C++11 [expr.pre.incr]p1:
14230     //   the expression ++x is equivalent to x+=1
14231     notePostMod(O, UO,
14232                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14233                                                 : UK_ModAsSideEffect);
14234   }
14235 
14236   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14237   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14238   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14239     Object O = getObject(UO->getSubExpr(), true);
14240     if (!O)
14241       return VisitExpr(UO);
14242 
14243     notePreMod(O, UO);
14244     Visit(UO->getSubExpr());
14245     notePostMod(O, UO, UK_ModAsSideEffect);
14246   }
14247 
14248   void VisitBinLOr(const BinaryOperator *BO) {
14249     // C++11 [expr.log.or]p2:
14250     //  If the second expression is evaluated, every value computation and
14251     //  side effect associated with the first expression is sequenced before
14252     //  every value computation and side effect associated with the
14253     //  second expression.
14254     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14255     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14256     SequenceTree::Seq OldRegion = Region;
14257 
14258     EvaluationTracker Eval(*this);
14259     {
14260       SequencedSubexpression Sequenced(*this);
14261       Region = LHSRegion;
14262       Visit(BO->getLHS());
14263     }
14264 
14265     // C++11 [expr.log.or]p1:
14266     //  [...] the second operand is not evaluated if the first operand
14267     //  evaluates to true.
14268     bool EvalResult = false;
14269     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14270     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14271     if (ShouldVisitRHS) {
14272       Region = RHSRegion;
14273       Visit(BO->getRHS());
14274     }
14275 
14276     Region = OldRegion;
14277     Tree.merge(LHSRegion);
14278     Tree.merge(RHSRegion);
14279   }
14280 
14281   void VisitBinLAnd(const BinaryOperator *BO) {
14282     // C++11 [expr.log.and]p2:
14283     //  If the second expression is evaluated, every value computation and
14284     //  side effect associated with the first expression is sequenced before
14285     //  every value computation and side effect associated with the
14286     //  second expression.
14287     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14288     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14289     SequenceTree::Seq OldRegion = Region;
14290 
14291     EvaluationTracker Eval(*this);
14292     {
14293       SequencedSubexpression Sequenced(*this);
14294       Region = LHSRegion;
14295       Visit(BO->getLHS());
14296     }
14297 
14298     // C++11 [expr.log.and]p1:
14299     //  [...] the second operand is not evaluated if the first operand is false.
14300     bool EvalResult = false;
14301     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14302     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14303     if (ShouldVisitRHS) {
14304       Region = RHSRegion;
14305       Visit(BO->getRHS());
14306     }
14307 
14308     Region = OldRegion;
14309     Tree.merge(LHSRegion);
14310     Tree.merge(RHSRegion);
14311   }
14312 
14313   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14314     // C++11 [expr.cond]p1:
14315     //  [...] Every value computation and side effect associated with the first
14316     //  expression is sequenced before every value computation and side effect
14317     //  associated with the second or third expression.
14318     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14319 
14320     // No sequencing is specified between the true and false expression.
14321     // However since exactly one of both is going to be evaluated we can
14322     // consider them to be sequenced. This is needed to avoid warning on
14323     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14324     // both the true and false expressions because we can't evaluate x.
14325     // This will still allow us to detect an expression like (pre C++17)
14326     // "(x ? y += 1 : y += 2) = y".
14327     //
14328     // We don't wrap the visitation of the true and false expression with
14329     // SequencedSubexpression because we don't want to downgrade modifications
14330     // as side effect in the true and false expressions after the visition
14331     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14332     // not warn between the two "y++", but we should warn between the "y++"
14333     // and the "y".
14334     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14335     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14336     SequenceTree::Seq OldRegion = Region;
14337 
14338     EvaluationTracker Eval(*this);
14339     {
14340       SequencedSubexpression Sequenced(*this);
14341       Region = ConditionRegion;
14342       Visit(CO->getCond());
14343     }
14344 
14345     // C++11 [expr.cond]p1:
14346     // [...] The first expression is contextually converted to bool (Clause 4).
14347     // It is evaluated and if it is true, the result of the conditional
14348     // expression is the value of the second expression, otherwise that of the
14349     // third expression. Only one of the second and third expressions is
14350     // evaluated. [...]
14351     bool EvalResult = false;
14352     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14353     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14354     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14355     if (ShouldVisitTrueExpr) {
14356       Region = TrueRegion;
14357       Visit(CO->getTrueExpr());
14358     }
14359     if (ShouldVisitFalseExpr) {
14360       Region = FalseRegion;
14361       Visit(CO->getFalseExpr());
14362     }
14363 
14364     Region = OldRegion;
14365     Tree.merge(ConditionRegion);
14366     Tree.merge(TrueRegion);
14367     Tree.merge(FalseRegion);
14368   }
14369 
14370   void VisitCallExpr(const CallExpr *CE) {
14371     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14372 
14373     if (CE->isUnevaluatedBuiltinCall(Context))
14374       return;
14375 
14376     // C++11 [intro.execution]p15:
14377     //   When calling a function [...], every value computation and side effect
14378     //   associated with any argument expression, or with the postfix expression
14379     //   designating the called function, is sequenced before execution of every
14380     //   expression or statement in the body of the function [and thus before
14381     //   the value computation of its result].
14382     SequencedSubexpression Sequenced(*this);
14383     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14384       // C++17 [expr.call]p5
14385       //   The postfix-expression is sequenced before each expression in the
14386       //   expression-list and any default argument. [...]
14387       SequenceTree::Seq CalleeRegion;
14388       SequenceTree::Seq OtherRegion;
14389       if (SemaRef.getLangOpts().CPlusPlus17) {
14390         CalleeRegion = Tree.allocate(Region);
14391         OtherRegion = Tree.allocate(Region);
14392       } else {
14393         CalleeRegion = Region;
14394         OtherRegion = Region;
14395       }
14396       SequenceTree::Seq OldRegion = Region;
14397 
14398       // Visit the callee expression first.
14399       Region = CalleeRegion;
14400       if (SemaRef.getLangOpts().CPlusPlus17) {
14401         SequencedSubexpression Sequenced(*this);
14402         Visit(CE->getCallee());
14403       } else {
14404         Visit(CE->getCallee());
14405       }
14406 
14407       // Then visit the argument expressions.
14408       Region = OtherRegion;
14409       for (const Expr *Argument : CE->arguments())
14410         Visit(Argument);
14411 
14412       Region = OldRegion;
14413       if (SemaRef.getLangOpts().CPlusPlus17) {
14414         Tree.merge(CalleeRegion);
14415         Tree.merge(OtherRegion);
14416       }
14417     });
14418   }
14419 
14420   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14421     // C++17 [over.match.oper]p2:
14422     //   [...] the operator notation is first transformed to the equivalent
14423     //   function-call notation as summarized in Table 12 (where @ denotes one
14424     //   of the operators covered in the specified subclause). However, the
14425     //   operands are sequenced in the order prescribed for the built-in
14426     //   operator (Clause 8).
14427     //
14428     // From the above only overloaded binary operators and overloaded call
14429     // operators have sequencing rules in C++17 that we need to handle
14430     // separately.
14431     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14432         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14433       return VisitCallExpr(CXXOCE);
14434 
14435     enum {
14436       NoSequencing,
14437       LHSBeforeRHS,
14438       RHSBeforeLHS,
14439       LHSBeforeRest
14440     } SequencingKind;
14441     switch (CXXOCE->getOperator()) {
14442     case OO_Equal:
14443     case OO_PlusEqual:
14444     case OO_MinusEqual:
14445     case OO_StarEqual:
14446     case OO_SlashEqual:
14447     case OO_PercentEqual:
14448     case OO_CaretEqual:
14449     case OO_AmpEqual:
14450     case OO_PipeEqual:
14451     case OO_LessLessEqual:
14452     case OO_GreaterGreaterEqual:
14453       SequencingKind = RHSBeforeLHS;
14454       break;
14455 
14456     case OO_LessLess:
14457     case OO_GreaterGreater:
14458     case OO_AmpAmp:
14459     case OO_PipePipe:
14460     case OO_Comma:
14461     case OO_ArrowStar:
14462     case OO_Subscript:
14463       SequencingKind = LHSBeforeRHS;
14464       break;
14465 
14466     case OO_Call:
14467       SequencingKind = LHSBeforeRest;
14468       break;
14469 
14470     default:
14471       SequencingKind = NoSequencing;
14472       break;
14473     }
14474 
14475     if (SequencingKind == NoSequencing)
14476       return VisitCallExpr(CXXOCE);
14477 
14478     // This is a call, so all subexpressions are sequenced before the result.
14479     SequencedSubexpression Sequenced(*this);
14480 
14481     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14482       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14483              "Should only get there with C++17 and above!");
14484       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14485              "Should only get there with an overloaded binary operator"
14486              " or an overloaded call operator!");
14487 
14488       if (SequencingKind == LHSBeforeRest) {
14489         assert(CXXOCE->getOperator() == OO_Call &&
14490                "We should only have an overloaded call operator here!");
14491 
14492         // This is very similar to VisitCallExpr, except that we only have the
14493         // C++17 case. The postfix-expression is the first argument of the
14494         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14495         // are in the following arguments.
14496         //
14497         // Note that we intentionally do not visit the callee expression since
14498         // it is just a decayed reference to a function.
14499         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14500         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14501         SequenceTree::Seq OldRegion = Region;
14502 
14503         assert(CXXOCE->getNumArgs() >= 1 &&
14504                "An overloaded call operator must have at least one argument"
14505                " for the postfix-expression!");
14506         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14507         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14508                                           CXXOCE->getNumArgs() - 1);
14509 
14510         // Visit the postfix-expression first.
14511         {
14512           Region = PostfixExprRegion;
14513           SequencedSubexpression Sequenced(*this);
14514           Visit(PostfixExpr);
14515         }
14516 
14517         // Then visit the argument expressions.
14518         Region = ArgsRegion;
14519         for (const Expr *Arg : Args)
14520           Visit(Arg);
14521 
14522         Region = OldRegion;
14523         Tree.merge(PostfixExprRegion);
14524         Tree.merge(ArgsRegion);
14525       } else {
14526         assert(CXXOCE->getNumArgs() == 2 &&
14527                "Should only have two arguments here!");
14528         assert((SequencingKind == LHSBeforeRHS ||
14529                 SequencingKind == RHSBeforeLHS) &&
14530                "Unexpected sequencing kind!");
14531 
14532         // We do not visit the callee expression since it is just a decayed
14533         // reference to a function.
14534         const Expr *E1 = CXXOCE->getArg(0);
14535         const Expr *E2 = CXXOCE->getArg(1);
14536         if (SequencingKind == RHSBeforeLHS)
14537           std::swap(E1, E2);
14538 
14539         return VisitSequencedExpressions(E1, E2);
14540       }
14541     });
14542   }
14543 
14544   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14545     // This is a call, so all subexpressions are sequenced before the result.
14546     SequencedSubexpression Sequenced(*this);
14547 
14548     if (!CCE->isListInitialization())
14549       return VisitExpr(CCE);
14550 
14551     // In C++11, list initializations are sequenced.
14552     SmallVector<SequenceTree::Seq, 32> Elts;
14553     SequenceTree::Seq Parent = Region;
14554     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14555                                               E = CCE->arg_end();
14556          I != E; ++I) {
14557       Region = Tree.allocate(Parent);
14558       Elts.push_back(Region);
14559       Visit(*I);
14560     }
14561 
14562     // Forget that the initializers are sequenced.
14563     Region = Parent;
14564     for (unsigned I = 0; I < Elts.size(); ++I)
14565       Tree.merge(Elts[I]);
14566   }
14567 
14568   void VisitInitListExpr(const InitListExpr *ILE) {
14569     if (!SemaRef.getLangOpts().CPlusPlus11)
14570       return VisitExpr(ILE);
14571 
14572     // In C++11, list initializations are sequenced.
14573     SmallVector<SequenceTree::Seq, 32> Elts;
14574     SequenceTree::Seq Parent = Region;
14575     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14576       const Expr *E = ILE->getInit(I);
14577       if (!E)
14578         continue;
14579       Region = Tree.allocate(Parent);
14580       Elts.push_back(Region);
14581       Visit(E);
14582     }
14583 
14584     // Forget that the initializers are sequenced.
14585     Region = Parent;
14586     for (unsigned I = 0; I < Elts.size(); ++I)
14587       Tree.merge(Elts[I]);
14588   }
14589 };
14590 
14591 } // namespace
14592 
14593 void Sema::CheckUnsequencedOperations(const Expr *E) {
14594   SmallVector<const Expr *, 8> WorkList;
14595   WorkList.push_back(E);
14596   while (!WorkList.empty()) {
14597     const Expr *Item = WorkList.pop_back_val();
14598     SequenceChecker(*this, Item, WorkList);
14599   }
14600 }
14601 
14602 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14603                               bool IsConstexpr) {
14604   llvm::SaveAndRestore<bool> ConstantContext(
14605       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14606   CheckImplicitConversions(E, CheckLoc);
14607   if (!E->isInstantiationDependent())
14608     CheckUnsequencedOperations(E);
14609   if (!IsConstexpr && !E->isValueDependent())
14610     CheckForIntOverflow(E);
14611   DiagnoseMisalignedMembers();
14612 }
14613 
14614 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14615                                        FieldDecl *BitField,
14616                                        Expr *Init) {
14617   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14618 }
14619 
14620 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14621                                          SourceLocation Loc) {
14622   if (!PType->isVariablyModifiedType())
14623     return;
14624   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14625     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14626     return;
14627   }
14628   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14629     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14630     return;
14631   }
14632   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14633     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14634     return;
14635   }
14636 
14637   const ArrayType *AT = S.Context.getAsArrayType(PType);
14638   if (!AT)
14639     return;
14640 
14641   if (AT->getSizeModifier() != ArrayType::Star) {
14642     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14643     return;
14644   }
14645 
14646   S.Diag(Loc, diag::err_array_star_in_function_definition);
14647 }
14648 
14649 /// CheckParmsForFunctionDef - Check that the parameters of the given
14650 /// function are appropriate for the definition of a function. This
14651 /// takes care of any checks that cannot be performed on the
14652 /// declaration itself, e.g., that the types of each of the function
14653 /// parameters are complete.
14654 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14655                                     bool CheckParameterNames) {
14656   bool HasInvalidParm = false;
14657   for (ParmVarDecl *Param : Parameters) {
14658     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14659     // function declarator that is part of a function definition of
14660     // that function shall not have incomplete type.
14661     //
14662     // This is also C++ [dcl.fct]p6.
14663     if (!Param->isInvalidDecl() &&
14664         RequireCompleteType(Param->getLocation(), Param->getType(),
14665                             diag::err_typecheck_decl_incomplete_type)) {
14666       Param->setInvalidDecl();
14667       HasInvalidParm = true;
14668     }
14669 
14670     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14671     // declaration of each parameter shall include an identifier.
14672     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14673         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14674       // Diagnose this as an extension in C17 and earlier.
14675       if (!getLangOpts().C2x)
14676         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14677     }
14678 
14679     // C99 6.7.5.3p12:
14680     //   If the function declarator is not part of a definition of that
14681     //   function, parameters may have incomplete type and may use the [*]
14682     //   notation in their sequences of declarator specifiers to specify
14683     //   variable length array types.
14684     QualType PType = Param->getOriginalType();
14685     // FIXME: This diagnostic should point the '[*]' if source-location
14686     // information is added for it.
14687     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14688 
14689     // If the parameter is a c++ class type and it has to be destructed in the
14690     // callee function, declare the destructor so that it can be called by the
14691     // callee function. Do not perform any direct access check on the dtor here.
14692     if (!Param->isInvalidDecl()) {
14693       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14694         if (!ClassDecl->isInvalidDecl() &&
14695             !ClassDecl->hasIrrelevantDestructor() &&
14696             !ClassDecl->isDependentContext() &&
14697             ClassDecl->isParamDestroyedInCallee()) {
14698           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14699           MarkFunctionReferenced(Param->getLocation(), Destructor);
14700           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14701         }
14702       }
14703     }
14704 
14705     // Parameters with the pass_object_size attribute only need to be marked
14706     // constant at function definitions. Because we lack information about
14707     // whether we're on a declaration or definition when we're instantiating the
14708     // attribute, we need to check for constness here.
14709     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14710       if (!Param->getType().isConstQualified())
14711         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14712             << Attr->getSpelling() << 1;
14713 
14714     // Check for parameter names shadowing fields from the class.
14715     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14716       // The owning context for the parameter should be the function, but we
14717       // want to see if this function's declaration context is a record.
14718       DeclContext *DC = Param->getDeclContext();
14719       if (DC && DC->isFunctionOrMethod()) {
14720         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14721           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14722                                      RD, /*DeclIsField*/ false);
14723       }
14724     }
14725   }
14726 
14727   return HasInvalidParm;
14728 }
14729 
14730 Optional<std::pair<CharUnits, CharUnits>>
14731 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14732 
14733 /// Compute the alignment and offset of the base class object given the
14734 /// derived-to-base cast expression and the alignment and offset of the derived
14735 /// class object.
14736 static std::pair<CharUnits, CharUnits>
14737 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14738                                    CharUnits BaseAlignment, CharUnits Offset,
14739                                    ASTContext &Ctx) {
14740   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14741        ++PathI) {
14742     const CXXBaseSpecifier *Base = *PathI;
14743     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14744     if (Base->isVirtual()) {
14745       // The complete object may have a lower alignment than the non-virtual
14746       // alignment of the base, in which case the base may be misaligned. Choose
14747       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14748       // conservative lower bound of the complete object alignment.
14749       CharUnits NonVirtualAlignment =
14750           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14751       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14752       Offset = CharUnits::Zero();
14753     } else {
14754       const ASTRecordLayout &RL =
14755           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14756       Offset += RL.getBaseClassOffset(BaseDecl);
14757     }
14758     DerivedType = Base->getType();
14759   }
14760 
14761   return std::make_pair(BaseAlignment, Offset);
14762 }
14763 
14764 /// Compute the alignment and offset of a binary additive operator.
14765 static Optional<std::pair<CharUnits, CharUnits>>
14766 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14767                                      bool IsSub, ASTContext &Ctx) {
14768   QualType PointeeType = PtrE->getType()->getPointeeType();
14769 
14770   if (!PointeeType->isConstantSizeType())
14771     return llvm::None;
14772 
14773   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14774 
14775   if (!P)
14776     return llvm::None;
14777 
14778   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14779   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14780     CharUnits Offset = EltSize * IdxRes->getExtValue();
14781     if (IsSub)
14782       Offset = -Offset;
14783     return std::make_pair(P->first, P->second + Offset);
14784   }
14785 
14786   // If the integer expression isn't a constant expression, compute the lower
14787   // bound of the alignment using the alignment and offset of the pointer
14788   // expression and the element size.
14789   return std::make_pair(
14790       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14791       CharUnits::Zero());
14792 }
14793 
14794 /// This helper function takes an lvalue expression and returns the alignment of
14795 /// a VarDecl and a constant offset from the VarDecl.
14796 Optional<std::pair<CharUnits, CharUnits>>
14797 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14798   E = E->IgnoreParens();
14799   switch (E->getStmtClass()) {
14800   default:
14801     break;
14802   case Stmt::CStyleCastExprClass:
14803   case Stmt::CXXStaticCastExprClass:
14804   case Stmt::ImplicitCastExprClass: {
14805     auto *CE = cast<CastExpr>(E);
14806     const Expr *From = CE->getSubExpr();
14807     switch (CE->getCastKind()) {
14808     default:
14809       break;
14810     case CK_NoOp:
14811       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14812     case CK_UncheckedDerivedToBase:
14813     case CK_DerivedToBase: {
14814       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14815       if (!P)
14816         break;
14817       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14818                                                 P->second, Ctx);
14819     }
14820     }
14821     break;
14822   }
14823   case Stmt::ArraySubscriptExprClass: {
14824     auto *ASE = cast<ArraySubscriptExpr>(E);
14825     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14826                                                 false, Ctx);
14827   }
14828   case Stmt::DeclRefExprClass: {
14829     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14830       // FIXME: If VD is captured by copy or is an escaping __block variable,
14831       // use the alignment of VD's type.
14832       if (!VD->getType()->isReferenceType())
14833         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14834       if (VD->hasInit())
14835         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14836     }
14837     break;
14838   }
14839   case Stmt::MemberExprClass: {
14840     auto *ME = cast<MemberExpr>(E);
14841     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14842     if (!FD || FD->getType()->isReferenceType() ||
14843         FD->getParent()->isInvalidDecl())
14844       break;
14845     Optional<std::pair<CharUnits, CharUnits>> P;
14846     if (ME->isArrow())
14847       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14848     else
14849       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14850     if (!P)
14851       break;
14852     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14853     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14854     return std::make_pair(P->first,
14855                           P->second + CharUnits::fromQuantity(Offset));
14856   }
14857   case Stmt::UnaryOperatorClass: {
14858     auto *UO = cast<UnaryOperator>(E);
14859     switch (UO->getOpcode()) {
14860     default:
14861       break;
14862     case UO_Deref:
14863       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14864     }
14865     break;
14866   }
14867   case Stmt::BinaryOperatorClass: {
14868     auto *BO = cast<BinaryOperator>(E);
14869     auto Opcode = BO->getOpcode();
14870     switch (Opcode) {
14871     default:
14872       break;
14873     case BO_Comma:
14874       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14875     }
14876     break;
14877   }
14878   }
14879   return llvm::None;
14880 }
14881 
14882 /// This helper function takes a pointer expression and returns the alignment of
14883 /// a VarDecl and a constant offset from the VarDecl.
14884 Optional<std::pair<CharUnits, CharUnits>>
14885 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14886   E = E->IgnoreParens();
14887   switch (E->getStmtClass()) {
14888   default:
14889     break;
14890   case Stmt::CStyleCastExprClass:
14891   case Stmt::CXXStaticCastExprClass:
14892   case Stmt::ImplicitCastExprClass: {
14893     auto *CE = cast<CastExpr>(E);
14894     const Expr *From = CE->getSubExpr();
14895     switch (CE->getCastKind()) {
14896     default:
14897       break;
14898     case CK_NoOp:
14899       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14900     case CK_ArrayToPointerDecay:
14901       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14902     case CK_UncheckedDerivedToBase:
14903     case CK_DerivedToBase: {
14904       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14905       if (!P)
14906         break;
14907       return getDerivedToBaseAlignmentAndOffset(
14908           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14909     }
14910     }
14911     break;
14912   }
14913   case Stmt::CXXThisExprClass: {
14914     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14915     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14916     return std::make_pair(Alignment, CharUnits::Zero());
14917   }
14918   case Stmt::UnaryOperatorClass: {
14919     auto *UO = cast<UnaryOperator>(E);
14920     if (UO->getOpcode() == UO_AddrOf)
14921       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14922     break;
14923   }
14924   case Stmt::BinaryOperatorClass: {
14925     auto *BO = cast<BinaryOperator>(E);
14926     auto Opcode = BO->getOpcode();
14927     switch (Opcode) {
14928     default:
14929       break;
14930     case BO_Add:
14931     case BO_Sub: {
14932       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14933       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14934         std::swap(LHS, RHS);
14935       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14936                                                   Ctx);
14937     }
14938     case BO_Comma:
14939       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14940     }
14941     break;
14942   }
14943   }
14944   return llvm::None;
14945 }
14946 
14947 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14948   // See if we can compute the alignment of a VarDecl and an offset from it.
14949   Optional<std::pair<CharUnits, CharUnits>> P =
14950       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14951 
14952   if (P)
14953     return P->first.alignmentAtOffset(P->second);
14954 
14955   // If that failed, return the type's alignment.
14956   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14957 }
14958 
14959 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14960 /// pointer cast increases the alignment requirements.
14961 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14962   // This is actually a lot of work to potentially be doing on every
14963   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14964   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14965     return;
14966 
14967   // Ignore dependent types.
14968   if (T->isDependentType() || Op->getType()->isDependentType())
14969     return;
14970 
14971   // Require that the destination be a pointer type.
14972   const PointerType *DestPtr = T->getAs<PointerType>();
14973   if (!DestPtr) return;
14974 
14975   // If the destination has alignment 1, we're done.
14976   QualType DestPointee = DestPtr->getPointeeType();
14977   if (DestPointee->isIncompleteType()) return;
14978   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14979   if (DestAlign.isOne()) return;
14980 
14981   // Require that the source be a pointer type.
14982   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14983   if (!SrcPtr) return;
14984   QualType SrcPointee = SrcPtr->getPointeeType();
14985 
14986   // Explicitly allow casts from cv void*.  We already implicitly
14987   // allowed casts to cv void*, since they have alignment 1.
14988   // Also allow casts involving incomplete types, which implicitly
14989   // includes 'void'.
14990   if (SrcPointee->isIncompleteType()) return;
14991 
14992   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14993 
14994   if (SrcAlign >= DestAlign) return;
14995 
14996   Diag(TRange.getBegin(), diag::warn_cast_align)
14997     << Op->getType() << T
14998     << static_cast<unsigned>(SrcAlign.getQuantity())
14999     << static_cast<unsigned>(DestAlign.getQuantity())
15000     << TRange << Op->getSourceRange();
15001 }
15002 
15003 /// Check whether this array fits the idiom of a size-one tail padded
15004 /// array member of a struct.
15005 ///
15006 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
15007 /// commonly used to emulate flexible arrays in C89 code.
15008 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
15009                                     const NamedDecl *ND) {
15010   if (Size != 1 || !ND) return false;
15011 
15012   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
15013   if (!FD) return false;
15014 
15015   // Don't consider sizes resulting from macro expansions or template argument
15016   // substitution to form C89 tail-padded arrays.
15017 
15018   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
15019   while (TInfo) {
15020     TypeLoc TL = TInfo->getTypeLoc();
15021     // Look through typedefs.
15022     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
15023       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
15024       TInfo = TDL->getTypeSourceInfo();
15025       continue;
15026     }
15027     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
15028       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
15029       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
15030         return false;
15031     }
15032     break;
15033   }
15034 
15035   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
15036   if (!RD) return false;
15037   if (RD->isUnion()) return false;
15038   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
15039     if (!CRD->isStandardLayout()) return false;
15040   }
15041 
15042   // See if this is the last field decl in the record.
15043   const Decl *D = FD;
15044   while ((D = D->getNextDeclInContext()))
15045     if (isa<FieldDecl>(D))
15046       return false;
15047   return true;
15048 }
15049 
15050 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
15051                             const ArraySubscriptExpr *ASE,
15052                             bool AllowOnePastEnd, bool IndexNegated) {
15053   // Already diagnosed by the constant evaluator.
15054   if (isConstantEvaluated())
15055     return;
15056 
15057   IndexExpr = IndexExpr->IgnoreParenImpCasts();
15058   if (IndexExpr->isValueDependent())
15059     return;
15060 
15061   const Type *EffectiveType =
15062       BaseExpr->getType()->getPointeeOrArrayElementType();
15063   BaseExpr = BaseExpr->IgnoreParenCasts();
15064   const ConstantArrayType *ArrayTy =
15065       Context.getAsConstantArrayType(BaseExpr->getType());
15066 
15067   const Type *BaseType =
15068       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
15069   bool IsUnboundedArray = (BaseType == nullptr);
15070   if (EffectiveType->isDependentType() ||
15071       (!IsUnboundedArray && BaseType->isDependentType()))
15072     return;
15073 
15074   Expr::EvalResult Result;
15075   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
15076     return;
15077 
15078   llvm::APSInt index = Result.Val.getInt();
15079   if (IndexNegated) {
15080     index.setIsUnsigned(false);
15081     index = -index;
15082   }
15083 
15084   const NamedDecl *ND = nullptr;
15085   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15086     ND = DRE->getDecl();
15087   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
15088     ND = ME->getMemberDecl();
15089 
15090   if (IsUnboundedArray) {
15091     if (index.isUnsigned() || !index.isNegative()) {
15092       const auto &ASTC = getASTContext();
15093       unsigned AddrBits =
15094           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
15095               EffectiveType->getCanonicalTypeInternal()));
15096       if (index.getBitWidth() < AddrBits)
15097         index = index.zext(AddrBits);
15098       Optional<CharUnits> ElemCharUnits =
15099           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
15100       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
15101       // pointer) bounds-checking isn't meaningful.
15102       if (!ElemCharUnits)
15103         return;
15104       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
15105       // If index has more active bits than address space, we already know
15106       // we have a bounds violation to warn about.  Otherwise, compute
15107       // address of (index + 1)th element, and warn about bounds violation
15108       // only if that address exceeds address space.
15109       if (index.getActiveBits() <= AddrBits) {
15110         bool Overflow;
15111         llvm::APInt Product(index);
15112         Product += 1;
15113         Product = Product.umul_ov(ElemBytes, Overflow);
15114         if (!Overflow && Product.getActiveBits() <= AddrBits)
15115           return;
15116       }
15117 
15118       // Need to compute max possible elements in address space, since that
15119       // is included in diag message.
15120       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15121       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15122       MaxElems += 1;
15123       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15124       MaxElems = MaxElems.udiv(ElemBytes);
15125 
15126       unsigned DiagID =
15127           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15128               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15129 
15130       // Diag message shows element size in bits and in "bytes" (platform-
15131       // dependent CharUnits)
15132       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15133                           PDiag(DiagID)
15134                               << toString(index, 10, true) << AddrBits
15135                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15136                               << toString(ElemBytes, 10, false)
15137                               << toString(MaxElems, 10, false)
15138                               << (unsigned)MaxElems.getLimitedValue(~0U)
15139                               << IndexExpr->getSourceRange());
15140 
15141       if (!ND) {
15142         // Try harder to find a NamedDecl to point at in the note.
15143         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15144           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15145         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15146           ND = DRE->getDecl();
15147         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15148           ND = ME->getMemberDecl();
15149       }
15150 
15151       if (ND)
15152         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15153                             PDiag(diag::note_array_declared_here) << ND);
15154     }
15155     return;
15156   }
15157 
15158   if (index.isUnsigned() || !index.isNegative()) {
15159     // It is possible that the type of the base expression after
15160     // IgnoreParenCasts is incomplete, even though the type of the base
15161     // expression before IgnoreParenCasts is complete (see PR39746 for an
15162     // example). In this case we have no information about whether the array
15163     // access exceeds the array bounds. However we can still diagnose an array
15164     // access which precedes the array bounds.
15165     if (BaseType->isIncompleteType())
15166       return;
15167 
15168     llvm::APInt size = ArrayTy->getSize();
15169     if (!size.isStrictlyPositive())
15170       return;
15171 
15172     if (BaseType != EffectiveType) {
15173       // Make sure we're comparing apples to apples when comparing index to size
15174       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15175       uint64_t array_typesize = Context.getTypeSize(BaseType);
15176       // Handle ptrarith_typesize being zero, such as when casting to void*
15177       if (!ptrarith_typesize) ptrarith_typesize = 1;
15178       if (ptrarith_typesize != array_typesize) {
15179         // There's a cast to a different size type involved
15180         uint64_t ratio = array_typesize / ptrarith_typesize;
15181         // TODO: Be smarter about handling cases where array_typesize is not a
15182         // multiple of ptrarith_typesize
15183         if (ptrarith_typesize * ratio == array_typesize)
15184           size *= llvm::APInt(size.getBitWidth(), ratio);
15185       }
15186     }
15187 
15188     if (size.getBitWidth() > index.getBitWidth())
15189       index = index.zext(size.getBitWidth());
15190     else if (size.getBitWidth() < index.getBitWidth())
15191       size = size.zext(index.getBitWidth());
15192 
15193     // For array subscripting the index must be less than size, but for pointer
15194     // arithmetic also allow the index (offset) to be equal to size since
15195     // computing the next address after the end of the array is legal and
15196     // commonly done e.g. in C++ iterators and range-based for loops.
15197     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15198       return;
15199 
15200     // Also don't warn for arrays of size 1 which are members of some
15201     // structure. These are often used to approximate flexible arrays in C89
15202     // code.
15203     if (IsTailPaddedMemberArray(*this, size, ND))
15204       return;
15205 
15206     // Suppress the warning if the subscript expression (as identified by the
15207     // ']' location) and the index expression are both from macro expansions
15208     // within a system header.
15209     if (ASE) {
15210       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15211           ASE->getRBracketLoc());
15212       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15213         SourceLocation IndexLoc =
15214             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15215         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15216           return;
15217       }
15218     }
15219 
15220     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15221                           : diag::warn_ptr_arith_exceeds_bounds;
15222 
15223     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15224                         PDiag(DiagID) << toString(index, 10, true)
15225                                       << toString(size, 10, true)
15226                                       << (unsigned)size.getLimitedValue(~0U)
15227                                       << IndexExpr->getSourceRange());
15228   } else {
15229     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15230     if (!ASE) {
15231       DiagID = diag::warn_ptr_arith_precedes_bounds;
15232       if (index.isNegative()) index = -index;
15233     }
15234 
15235     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15236                         PDiag(DiagID) << toString(index, 10, true)
15237                                       << IndexExpr->getSourceRange());
15238   }
15239 
15240   if (!ND) {
15241     // Try harder to find a NamedDecl to point at in the note.
15242     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15243       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15244     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15245       ND = DRE->getDecl();
15246     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15247       ND = ME->getMemberDecl();
15248   }
15249 
15250   if (ND)
15251     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15252                         PDiag(diag::note_array_declared_here) << ND);
15253 }
15254 
15255 void Sema::CheckArrayAccess(const Expr *expr) {
15256   int AllowOnePastEnd = 0;
15257   while (expr) {
15258     expr = expr->IgnoreParenImpCasts();
15259     switch (expr->getStmtClass()) {
15260       case Stmt::ArraySubscriptExprClass: {
15261         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15262         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15263                          AllowOnePastEnd > 0);
15264         expr = ASE->getBase();
15265         break;
15266       }
15267       case Stmt::MemberExprClass: {
15268         expr = cast<MemberExpr>(expr)->getBase();
15269         break;
15270       }
15271       case Stmt::OMPArraySectionExprClass: {
15272         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15273         if (ASE->getLowerBound())
15274           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15275                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15276         return;
15277       }
15278       case Stmt::UnaryOperatorClass: {
15279         // Only unwrap the * and & unary operators
15280         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15281         expr = UO->getSubExpr();
15282         switch (UO->getOpcode()) {
15283           case UO_AddrOf:
15284             AllowOnePastEnd++;
15285             break;
15286           case UO_Deref:
15287             AllowOnePastEnd--;
15288             break;
15289           default:
15290             return;
15291         }
15292         break;
15293       }
15294       case Stmt::ConditionalOperatorClass: {
15295         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15296         if (const Expr *lhs = cond->getLHS())
15297           CheckArrayAccess(lhs);
15298         if (const Expr *rhs = cond->getRHS())
15299           CheckArrayAccess(rhs);
15300         return;
15301       }
15302       case Stmt::CXXOperatorCallExprClass: {
15303         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15304         for (const auto *Arg : OCE->arguments())
15305           CheckArrayAccess(Arg);
15306         return;
15307       }
15308       default:
15309         return;
15310     }
15311   }
15312 }
15313 
15314 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15315 
15316 namespace {
15317 
15318 struct RetainCycleOwner {
15319   VarDecl *Variable = nullptr;
15320   SourceRange Range;
15321   SourceLocation Loc;
15322   bool Indirect = false;
15323 
15324   RetainCycleOwner() = default;
15325 
15326   void setLocsFrom(Expr *e) {
15327     Loc = e->getExprLoc();
15328     Range = e->getSourceRange();
15329   }
15330 };
15331 
15332 } // namespace
15333 
15334 /// Consider whether capturing the given variable can possibly lead to
15335 /// a retain cycle.
15336 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15337   // In ARC, it's captured strongly iff the variable has __strong
15338   // lifetime.  In MRR, it's captured strongly if the variable is
15339   // __block and has an appropriate type.
15340   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15341     return false;
15342 
15343   owner.Variable = var;
15344   if (ref)
15345     owner.setLocsFrom(ref);
15346   return true;
15347 }
15348 
15349 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15350   while (true) {
15351     e = e->IgnoreParens();
15352     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15353       switch (cast->getCastKind()) {
15354       case CK_BitCast:
15355       case CK_LValueBitCast:
15356       case CK_LValueToRValue:
15357       case CK_ARCReclaimReturnedObject:
15358         e = cast->getSubExpr();
15359         continue;
15360 
15361       default:
15362         return false;
15363       }
15364     }
15365 
15366     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15367       ObjCIvarDecl *ivar = ref->getDecl();
15368       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15369         return false;
15370 
15371       // Try to find a retain cycle in the base.
15372       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15373         return false;
15374 
15375       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15376       owner.Indirect = true;
15377       return true;
15378     }
15379 
15380     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15381       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15382       if (!var) return false;
15383       return considerVariable(var, ref, owner);
15384     }
15385 
15386     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15387       if (member->isArrow()) return false;
15388 
15389       // Don't count this as an indirect ownership.
15390       e = member->getBase();
15391       continue;
15392     }
15393 
15394     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15395       // Only pay attention to pseudo-objects on property references.
15396       ObjCPropertyRefExpr *pre
15397         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15398                                               ->IgnoreParens());
15399       if (!pre) return false;
15400       if (pre->isImplicitProperty()) return false;
15401       ObjCPropertyDecl *property = pre->getExplicitProperty();
15402       if (!property->isRetaining() &&
15403           !(property->getPropertyIvarDecl() &&
15404             property->getPropertyIvarDecl()->getType()
15405               .getObjCLifetime() == Qualifiers::OCL_Strong))
15406           return false;
15407 
15408       owner.Indirect = true;
15409       if (pre->isSuperReceiver()) {
15410         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15411         if (!owner.Variable)
15412           return false;
15413         owner.Loc = pre->getLocation();
15414         owner.Range = pre->getSourceRange();
15415         return true;
15416       }
15417       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15418                               ->getSourceExpr());
15419       continue;
15420     }
15421 
15422     // Array ivars?
15423 
15424     return false;
15425   }
15426 }
15427 
15428 namespace {
15429 
15430   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15431     ASTContext &Context;
15432     VarDecl *Variable;
15433     Expr *Capturer = nullptr;
15434     bool VarWillBeReased = false;
15435 
15436     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15437         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15438           Context(Context), Variable(variable) {}
15439 
15440     void VisitDeclRefExpr(DeclRefExpr *ref) {
15441       if (ref->getDecl() == Variable && !Capturer)
15442         Capturer = ref;
15443     }
15444 
15445     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15446       if (Capturer) return;
15447       Visit(ref->getBase());
15448       if (Capturer && ref->isFreeIvar())
15449         Capturer = ref;
15450     }
15451 
15452     void VisitBlockExpr(BlockExpr *block) {
15453       // Look inside nested blocks
15454       if (block->getBlockDecl()->capturesVariable(Variable))
15455         Visit(block->getBlockDecl()->getBody());
15456     }
15457 
15458     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15459       if (Capturer) return;
15460       if (OVE->getSourceExpr())
15461         Visit(OVE->getSourceExpr());
15462     }
15463 
15464     void VisitBinaryOperator(BinaryOperator *BinOp) {
15465       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15466         return;
15467       Expr *LHS = BinOp->getLHS();
15468       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15469         if (DRE->getDecl() != Variable)
15470           return;
15471         if (Expr *RHS = BinOp->getRHS()) {
15472           RHS = RHS->IgnoreParenCasts();
15473           Optional<llvm::APSInt> Value;
15474           VarWillBeReased =
15475               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15476                *Value == 0);
15477         }
15478       }
15479     }
15480   };
15481 
15482 } // namespace
15483 
15484 /// Check whether the given argument is a block which captures a
15485 /// variable.
15486 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15487   assert(owner.Variable && owner.Loc.isValid());
15488 
15489   e = e->IgnoreParenCasts();
15490 
15491   // Look through [^{...} copy] and Block_copy(^{...}).
15492   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15493     Selector Cmd = ME->getSelector();
15494     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15495       e = ME->getInstanceReceiver();
15496       if (!e)
15497         return nullptr;
15498       e = e->IgnoreParenCasts();
15499     }
15500   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15501     if (CE->getNumArgs() == 1) {
15502       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15503       if (Fn) {
15504         const IdentifierInfo *FnI = Fn->getIdentifier();
15505         if (FnI && FnI->isStr("_Block_copy")) {
15506           e = CE->getArg(0)->IgnoreParenCasts();
15507         }
15508       }
15509     }
15510   }
15511 
15512   BlockExpr *block = dyn_cast<BlockExpr>(e);
15513   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15514     return nullptr;
15515 
15516   FindCaptureVisitor visitor(S.Context, owner.Variable);
15517   visitor.Visit(block->getBlockDecl()->getBody());
15518   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15519 }
15520 
15521 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15522                                 RetainCycleOwner &owner) {
15523   assert(capturer);
15524   assert(owner.Variable && owner.Loc.isValid());
15525 
15526   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15527     << owner.Variable << capturer->getSourceRange();
15528   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15529     << owner.Indirect << owner.Range;
15530 }
15531 
15532 /// Check for a keyword selector that starts with the word 'add' or
15533 /// 'set'.
15534 static bool isSetterLikeSelector(Selector sel) {
15535   if (sel.isUnarySelector()) return false;
15536 
15537   StringRef str = sel.getNameForSlot(0);
15538   while (!str.empty() && str.front() == '_') str = str.substr(1);
15539   if (str.startswith("set"))
15540     str = str.substr(3);
15541   else if (str.startswith("add")) {
15542     // Specially allow 'addOperationWithBlock:'.
15543     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15544       return false;
15545     str = str.substr(3);
15546   }
15547   else
15548     return false;
15549 
15550   if (str.empty()) return true;
15551   return !isLowercase(str.front());
15552 }
15553 
15554 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15555                                                     ObjCMessageExpr *Message) {
15556   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15557                                                 Message->getReceiverInterface(),
15558                                                 NSAPI::ClassId_NSMutableArray);
15559   if (!IsMutableArray) {
15560     return None;
15561   }
15562 
15563   Selector Sel = Message->getSelector();
15564 
15565   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15566     S.NSAPIObj->getNSArrayMethodKind(Sel);
15567   if (!MKOpt) {
15568     return None;
15569   }
15570 
15571   NSAPI::NSArrayMethodKind MK = *MKOpt;
15572 
15573   switch (MK) {
15574     case NSAPI::NSMutableArr_addObject:
15575     case NSAPI::NSMutableArr_insertObjectAtIndex:
15576     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15577       return 0;
15578     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15579       return 1;
15580 
15581     default:
15582       return None;
15583   }
15584 
15585   return None;
15586 }
15587 
15588 static
15589 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15590                                                   ObjCMessageExpr *Message) {
15591   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15592                                             Message->getReceiverInterface(),
15593                                             NSAPI::ClassId_NSMutableDictionary);
15594   if (!IsMutableDictionary) {
15595     return None;
15596   }
15597 
15598   Selector Sel = Message->getSelector();
15599 
15600   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15601     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15602   if (!MKOpt) {
15603     return None;
15604   }
15605 
15606   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15607 
15608   switch (MK) {
15609     case NSAPI::NSMutableDict_setObjectForKey:
15610     case NSAPI::NSMutableDict_setValueForKey:
15611     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15612       return 0;
15613 
15614     default:
15615       return None;
15616   }
15617 
15618   return None;
15619 }
15620 
15621 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15622   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15623                                                 Message->getReceiverInterface(),
15624                                                 NSAPI::ClassId_NSMutableSet);
15625 
15626   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15627                                             Message->getReceiverInterface(),
15628                                             NSAPI::ClassId_NSMutableOrderedSet);
15629   if (!IsMutableSet && !IsMutableOrderedSet) {
15630     return None;
15631   }
15632 
15633   Selector Sel = Message->getSelector();
15634 
15635   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15636   if (!MKOpt) {
15637     return None;
15638   }
15639 
15640   NSAPI::NSSetMethodKind MK = *MKOpt;
15641 
15642   switch (MK) {
15643     case NSAPI::NSMutableSet_addObject:
15644     case NSAPI::NSOrderedSet_setObjectAtIndex:
15645     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15646     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15647       return 0;
15648     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15649       return 1;
15650   }
15651 
15652   return None;
15653 }
15654 
15655 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15656   if (!Message->isInstanceMessage()) {
15657     return;
15658   }
15659 
15660   Optional<int> ArgOpt;
15661 
15662   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15663       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15664       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15665     return;
15666   }
15667 
15668   int ArgIndex = *ArgOpt;
15669 
15670   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15671   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15672     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15673   }
15674 
15675   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15676     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15677       if (ArgRE->isObjCSelfExpr()) {
15678         Diag(Message->getSourceRange().getBegin(),
15679              diag::warn_objc_circular_container)
15680           << ArgRE->getDecl() << StringRef("'super'");
15681       }
15682     }
15683   } else {
15684     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15685 
15686     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15687       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15688     }
15689 
15690     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15691       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15692         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15693           ValueDecl *Decl = ReceiverRE->getDecl();
15694           Diag(Message->getSourceRange().getBegin(),
15695                diag::warn_objc_circular_container)
15696             << Decl << Decl;
15697           if (!ArgRE->isObjCSelfExpr()) {
15698             Diag(Decl->getLocation(),
15699                  diag::note_objc_circular_container_declared_here)
15700               << Decl;
15701           }
15702         }
15703       }
15704     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15705       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15706         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15707           ObjCIvarDecl *Decl = IvarRE->getDecl();
15708           Diag(Message->getSourceRange().getBegin(),
15709                diag::warn_objc_circular_container)
15710             << Decl << Decl;
15711           Diag(Decl->getLocation(),
15712                diag::note_objc_circular_container_declared_here)
15713             << Decl;
15714         }
15715       }
15716     }
15717   }
15718 }
15719 
15720 /// Check a message send to see if it's likely to cause a retain cycle.
15721 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15722   // Only check instance methods whose selector looks like a setter.
15723   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15724     return;
15725 
15726   // Try to find a variable that the receiver is strongly owned by.
15727   RetainCycleOwner owner;
15728   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15729     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15730       return;
15731   } else {
15732     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15733     owner.Variable = getCurMethodDecl()->getSelfDecl();
15734     owner.Loc = msg->getSuperLoc();
15735     owner.Range = msg->getSuperLoc();
15736   }
15737 
15738   // Check whether the receiver is captured by any of the arguments.
15739   const ObjCMethodDecl *MD = msg->getMethodDecl();
15740   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15741     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15742       // noescape blocks should not be retained by the method.
15743       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15744         continue;
15745       return diagnoseRetainCycle(*this, capturer, owner);
15746     }
15747   }
15748 }
15749 
15750 /// Check a property assign to see if it's likely to cause a retain cycle.
15751 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15752   RetainCycleOwner owner;
15753   if (!findRetainCycleOwner(*this, receiver, owner))
15754     return;
15755 
15756   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15757     diagnoseRetainCycle(*this, capturer, owner);
15758 }
15759 
15760 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15761   RetainCycleOwner Owner;
15762   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15763     return;
15764 
15765   // Because we don't have an expression for the variable, we have to set the
15766   // location explicitly here.
15767   Owner.Loc = Var->getLocation();
15768   Owner.Range = Var->getSourceRange();
15769 
15770   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15771     diagnoseRetainCycle(*this, Capturer, Owner);
15772 }
15773 
15774 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15775                                      Expr *RHS, bool isProperty) {
15776   // Check if RHS is an Objective-C object literal, which also can get
15777   // immediately zapped in a weak reference.  Note that we explicitly
15778   // allow ObjCStringLiterals, since those are designed to never really die.
15779   RHS = RHS->IgnoreParenImpCasts();
15780 
15781   // This enum needs to match with the 'select' in
15782   // warn_objc_arc_literal_assign (off-by-1).
15783   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15784   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15785     return false;
15786 
15787   S.Diag(Loc, diag::warn_arc_literal_assign)
15788     << (unsigned) Kind
15789     << (isProperty ? 0 : 1)
15790     << RHS->getSourceRange();
15791 
15792   return true;
15793 }
15794 
15795 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15796                                     Qualifiers::ObjCLifetime LT,
15797                                     Expr *RHS, bool isProperty) {
15798   // Strip off any implicit cast added to get to the one ARC-specific.
15799   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15800     if (cast->getCastKind() == CK_ARCConsumeObject) {
15801       S.Diag(Loc, diag::warn_arc_retained_assign)
15802         << (LT == Qualifiers::OCL_ExplicitNone)
15803         << (isProperty ? 0 : 1)
15804         << RHS->getSourceRange();
15805       return true;
15806     }
15807     RHS = cast->getSubExpr();
15808   }
15809 
15810   if (LT == Qualifiers::OCL_Weak &&
15811       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15812     return true;
15813 
15814   return false;
15815 }
15816 
15817 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15818                               QualType LHS, Expr *RHS) {
15819   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15820 
15821   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15822     return false;
15823 
15824   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15825     return true;
15826 
15827   return false;
15828 }
15829 
15830 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15831                               Expr *LHS, Expr *RHS) {
15832   QualType LHSType;
15833   // PropertyRef on LHS type need be directly obtained from
15834   // its declaration as it has a PseudoType.
15835   ObjCPropertyRefExpr *PRE
15836     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15837   if (PRE && !PRE->isImplicitProperty()) {
15838     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15839     if (PD)
15840       LHSType = PD->getType();
15841   }
15842 
15843   if (LHSType.isNull())
15844     LHSType = LHS->getType();
15845 
15846   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15847 
15848   if (LT == Qualifiers::OCL_Weak) {
15849     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15850       getCurFunction()->markSafeWeakUse(LHS);
15851   }
15852 
15853   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15854     return;
15855 
15856   // FIXME. Check for other life times.
15857   if (LT != Qualifiers::OCL_None)
15858     return;
15859 
15860   if (PRE) {
15861     if (PRE->isImplicitProperty())
15862       return;
15863     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15864     if (!PD)
15865       return;
15866 
15867     unsigned Attributes = PD->getPropertyAttributes();
15868     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15869       // when 'assign' attribute was not explicitly specified
15870       // by user, ignore it and rely on property type itself
15871       // for lifetime info.
15872       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15873       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15874           LHSType->isObjCRetainableType())
15875         return;
15876 
15877       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15878         if (cast->getCastKind() == CK_ARCConsumeObject) {
15879           Diag(Loc, diag::warn_arc_retained_property_assign)
15880           << RHS->getSourceRange();
15881           return;
15882         }
15883         RHS = cast->getSubExpr();
15884       }
15885     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15886       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15887         return;
15888     }
15889   }
15890 }
15891 
15892 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15893 
15894 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15895                                         SourceLocation StmtLoc,
15896                                         const NullStmt *Body) {
15897   // Do not warn if the body is a macro that expands to nothing, e.g:
15898   //
15899   // #define CALL(x)
15900   // if (condition)
15901   //   CALL(0);
15902   if (Body->hasLeadingEmptyMacro())
15903     return false;
15904 
15905   // Get line numbers of statement and body.
15906   bool StmtLineInvalid;
15907   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15908                                                       &StmtLineInvalid);
15909   if (StmtLineInvalid)
15910     return false;
15911 
15912   bool BodyLineInvalid;
15913   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15914                                                       &BodyLineInvalid);
15915   if (BodyLineInvalid)
15916     return false;
15917 
15918   // Warn if null statement and body are on the same line.
15919   if (StmtLine != BodyLine)
15920     return false;
15921 
15922   return true;
15923 }
15924 
15925 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15926                                  const Stmt *Body,
15927                                  unsigned DiagID) {
15928   // Since this is a syntactic check, don't emit diagnostic for template
15929   // instantiations, this just adds noise.
15930   if (CurrentInstantiationScope)
15931     return;
15932 
15933   // The body should be a null statement.
15934   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15935   if (!NBody)
15936     return;
15937 
15938   // Do the usual checks.
15939   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15940     return;
15941 
15942   Diag(NBody->getSemiLoc(), DiagID);
15943   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15944 }
15945 
15946 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15947                                  const Stmt *PossibleBody) {
15948   assert(!CurrentInstantiationScope); // Ensured by caller
15949 
15950   SourceLocation StmtLoc;
15951   const Stmt *Body;
15952   unsigned DiagID;
15953   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15954     StmtLoc = FS->getRParenLoc();
15955     Body = FS->getBody();
15956     DiagID = diag::warn_empty_for_body;
15957   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15958     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15959     Body = WS->getBody();
15960     DiagID = diag::warn_empty_while_body;
15961   } else
15962     return; // Neither `for' nor `while'.
15963 
15964   // The body should be a null statement.
15965   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15966   if (!NBody)
15967     return;
15968 
15969   // Skip expensive checks if diagnostic is disabled.
15970   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15971     return;
15972 
15973   // Do the usual checks.
15974   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15975     return;
15976 
15977   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15978   // noise level low, emit diagnostics only if for/while is followed by a
15979   // CompoundStmt, e.g.:
15980   //    for (int i = 0; i < n; i++);
15981   //    {
15982   //      a(i);
15983   //    }
15984   // or if for/while is followed by a statement with more indentation
15985   // than for/while itself:
15986   //    for (int i = 0; i < n; i++);
15987   //      a(i);
15988   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15989   if (!ProbableTypo) {
15990     bool BodyColInvalid;
15991     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15992         PossibleBody->getBeginLoc(), &BodyColInvalid);
15993     if (BodyColInvalid)
15994       return;
15995 
15996     bool StmtColInvalid;
15997     unsigned StmtCol =
15998         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15999     if (StmtColInvalid)
16000       return;
16001 
16002     if (BodyCol > StmtCol)
16003       ProbableTypo = true;
16004   }
16005 
16006   if (ProbableTypo) {
16007     Diag(NBody->getSemiLoc(), DiagID);
16008     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
16009   }
16010 }
16011 
16012 //===--- CHECK: Warn on self move with std::move. -------------------------===//
16013 
16014 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
16015 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
16016                              SourceLocation OpLoc) {
16017   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
16018     return;
16019 
16020   if (inTemplateInstantiation())
16021     return;
16022 
16023   // Strip parens and casts away.
16024   LHSExpr = LHSExpr->IgnoreParenImpCasts();
16025   RHSExpr = RHSExpr->IgnoreParenImpCasts();
16026 
16027   // Check for a call expression
16028   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
16029   if (!CE || CE->getNumArgs() != 1)
16030     return;
16031 
16032   // Check for a call to std::move
16033   if (!CE->isCallToStdMove())
16034     return;
16035 
16036   // Get argument from std::move
16037   RHSExpr = CE->getArg(0);
16038 
16039   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
16040   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
16041 
16042   // Two DeclRefExpr's, check that the decls are the same.
16043   if (LHSDeclRef && RHSDeclRef) {
16044     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16045       return;
16046     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16047         RHSDeclRef->getDecl()->getCanonicalDecl())
16048       return;
16049 
16050     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16051                                         << LHSExpr->getSourceRange()
16052                                         << RHSExpr->getSourceRange();
16053     return;
16054   }
16055 
16056   // Member variables require a different approach to check for self moves.
16057   // MemberExpr's are the same if every nested MemberExpr refers to the same
16058   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
16059   // the base Expr's are CXXThisExpr's.
16060   const Expr *LHSBase = LHSExpr;
16061   const Expr *RHSBase = RHSExpr;
16062   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
16063   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
16064   if (!LHSME || !RHSME)
16065     return;
16066 
16067   while (LHSME && RHSME) {
16068     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
16069         RHSME->getMemberDecl()->getCanonicalDecl())
16070       return;
16071 
16072     LHSBase = LHSME->getBase();
16073     RHSBase = RHSME->getBase();
16074     LHSME = dyn_cast<MemberExpr>(LHSBase);
16075     RHSME = dyn_cast<MemberExpr>(RHSBase);
16076   }
16077 
16078   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
16079   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
16080   if (LHSDeclRef && RHSDeclRef) {
16081     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
16082       return;
16083     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
16084         RHSDeclRef->getDecl()->getCanonicalDecl())
16085       return;
16086 
16087     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16088                                         << LHSExpr->getSourceRange()
16089                                         << RHSExpr->getSourceRange();
16090     return;
16091   }
16092 
16093   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
16094     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
16095                                         << LHSExpr->getSourceRange()
16096                                         << RHSExpr->getSourceRange();
16097 }
16098 
16099 //===--- Layout compatibility ----------------------------------------------//
16100 
16101 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
16102 
16103 /// Check if two enumeration types are layout-compatible.
16104 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
16105   // C++11 [dcl.enum] p8:
16106   // Two enumeration types are layout-compatible if they have the same
16107   // underlying type.
16108   return ED1->isComplete() && ED2->isComplete() &&
16109          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16110 }
16111 
16112 /// Check if two fields are layout-compatible.
16113 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16114                                FieldDecl *Field2) {
16115   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16116     return false;
16117 
16118   if (Field1->isBitField() != Field2->isBitField())
16119     return false;
16120 
16121   if (Field1->isBitField()) {
16122     // Make sure that the bit-fields are the same length.
16123     unsigned Bits1 = Field1->getBitWidthValue(C);
16124     unsigned Bits2 = Field2->getBitWidthValue(C);
16125 
16126     if (Bits1 != Bits2)
16127       return false;
16128   }
16129 
16130   return true;
16131 }
16132 
16133 /// Check if two standard-layout structs are layout-compatible.
16134 /// (C++11 [class.mem] p17)
16135 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16136                                      RecordDecl *RD2) {
16137   // If both records are C++ classes, check that base classes match.
16138   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16139     // If one of records is a CXXRecordDecl we are in C++ mode,
16140     // thus the other one is a CXXRecordDecl, too.
16141     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16142     // Check number of base classes.
16143     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16144       return false;
16145 
16146     // Check the base classes.
16147     for (CXXRecordDecl::base_class_const_iterator
16148                Base1 = D1CXX->bases_begin(),
16149            BaseEnd1 = D1CXX->bases_end(),
16150               Base2 = D2CXX->bases_begin();
16151          Base1 != BaseEnd1;
16152          ++Base1, ++Base2) {
16153       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16154         return false;
16155     }
16156   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16157     // If only RD2 is a C++ class, it should have zero base classes.
16158     if (D2CXX->getNumBases() > 0)
16159       return false;
16160   }
16161 
16162   // Check the fields.
16163   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16164                              Field2End = RD2->field_end(),
16165                              Field1 = RD1->field_begin(),
16166                              Field1End = RD1->field_end();
16167   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16168     if (!isLayoutCompatible(C, *Field1, *Field2))
16169       return false;
16170   }
16171   if (Field1 != Field1End || Field2 != Field2End)
16172     return false;
16173 
16174   return true;
16175 }
16176 
16177 /// Check if two standard-layout unions are layout-compatible.
16178 /// (C++11 [class.mem] p18)
16179 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16180                                     RecordDecl *RD2) {
16181   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16182   for (auto *Field2 : RD2->fields())
16183     UnmatchedFields.insert(Field2);
16184 
16185   for (auto *Field1 : RD1->fields()) {
16186     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16187         I = UnmatchedFields.begin(),
16188         E = UnmatchedFields.end();
16189 
16190     for ( ; I != E; ++I) {
16191       if (isLayoutCompatible(C, Field1, *I)) {
16192         bool Result = UnmatchedFields.erase(*I);
16193         (void) Result;
16194         assert(Result);
16195         break;
16196       }
16197     }
16198     if (I == E)
16199       return false;
16200   }
16201 
16202   return UnmatchedFields.empty();
16203 }
16204 
16205 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16206                                RecordDecl *RD2) {
16207   if (RD1->isUnion() != RD2->isUnion())
16208     return false;
16209 
16210   if (RD1->isUnion())
16211     return isLayoutCompatibleUnion(C, RD1, RD2);
16212   else
16213     return isLayoutCompatibleStruct(C, RD1, RD2);
16214 }
16215 
16216 /// Check if two types are layout-compatible in C++11 sense.
16217 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16218   if (T1.isNull() || T2.isNull())
16219     return false;
16220 
16221   // C++11 [basic.types] p11:
16222   // If two types T1 and T2 are the same type, then T1 and T2 are
16223   // layout-compatible types.
16224   if (C.hasSameType(T1, T2))
16225     return true;
16226 
16227   T1 = T1.getCanonicalType().getUnqualifiedType();
16228   T2 = T2.getCanonicalType().getUnqualifiedType();
16229 
16230   const Type::TypeClass TC1 = T1->getTypeClass();
16231   const Type::TypeClass TC2 = T2->getTypeClass();
16232 
16233   if (TC1 != TC2)
16234     return false;
16235 
16236   if (TC1 == Type::Enum) {
16237     return isLayoutCompatible(C,
16238                               cast<EnumType>(T1)->getDecl(),
16239                               cast<EnumType>(T2)->getDecl());
16240   } else if (TC1 == Type::Record) {
16241     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16242       return false;
16243 
16244     return isLayoutCompatible(C,
16245                               cast<RecordType>(T1)->getDecl(),
16246                               cast<RecordType>(T2)->getDecl());
16247   }
16248 
16249   return false;
16250 }
16251 
16252 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16253 
16254 /// Given a type tag expression find the type tag itself.
16255 ///
16256 /// \param TypeExpr Type tag expression, as it appears in user's code.
16257 ///
16258 /// \param VD Declaration of an identifier that appears in a type tag.
16259 ///
16260 /// \param MagicValue Type tag magic value.
16261 ///
16262 /// \param isConstantEvaluated whether the evalaution should be performed in
16263 
16264 /// constant context.
16265 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16266                             const ValueDecl **VD, uint64_t *MagicValue,
16267                             bool isConstantEvaluated) {
16268   while(true) {
16269     if (!TypeExpr)
16270       return false;
16271 
16272     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16273 
16274     switch (TypeExpr->getStmtClass()) {
16275     case Stmt::UnaryOperatorClass: {
16276       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16277       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16278         TypeExpr = UO->getSubExpr();
16279         continue;
16280       }
16281       return false;
16282     }
16283 
16284     case Stmt::DeclRefExprClass: {
16285       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16286       *VD = DRE->getDecl();
16287       return true;
16288     }
16289 
16290     case Stmt::IntegerLiteralClass: {
16291       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16292       llvm::APInt MagicValueAPInt = IL->getValue();
16293       if (MagicValueAPInt.getActiveBits() <= 64) {
16294         *MagicValue = MagicValueAPInt.getZExtValue();
16295         return true;
16296       } else
16297         return false;
16298     }
16299 
16300     case Stmt::BinaryConditionalOperatorClass:
16301     case Stmt::ConditionalOperatorClass: {
16302       const AbstractConditionalOperator *ACO =
16303           cast<AbstractConditionalOperator>(TypeExpr);
16304       bool Result;
16305       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16306                                                      isConstantEvaluated)) {
16307         if (Result)
16308           TypeExpr = ACO->getTrueExpr();
16309         else
16310           TypeExpr = ACO->getFalseExpr();
16311         continue;
16312       }
16313       return false;
16314     }
16315 
16316     case Stmt::BinaryOperatorClass: {
16317       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16318       if (BO->getOpcode() == BO_Comma) {
16319         TypeExpr = BO->getRHS();
16320         continue;
16321       }
16322       return false;
16323     }
16324 
16325     default:
16326       return false;
16327     }
16328   }
16329 }
16330 
16331 /// Retrieve the C type corresponding to type tag TypeExpr.
16332 ///
16333 /// \param TypeExpr Expression that specifies a type tag.
16334 ///
16335 /// \param MagicValues Registered magic values.
16336 ///
16337 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16338 ///        kind.
16339 ///
16340 /// \param TypeInfo Information about the corresponding C type.
16341 ///
16342 /// \param isConstantEvaluated whether the evalaution should be performed in
16343 /// constant context.
16344 ///
16345 /// \returns true if the corresponding C type was found.
16346 static bool GetMatchingCType(
16347     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16348     const ASTContext &Ctx,
16349     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16350         *MagicValues,
16351     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16352     bool isConstantEvaluated) {
16353   FoundWrongKind = false;
16354 
16355   // Variable declaration that has type_tag_for_datatype attribute.
16356   const ValueDecl *VD = nullptr;
16357 
16358   uint64_t MagicValue;
16359 
16360   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16361     return false;
16362 
16363   if (VD) {
16364     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16365       if (I->getArgumentKind() != ArgumentKind) {
16366         FoundWrongKind = true;
16367         return false;
16368       }
16369       TypeInfo.Type = I->getMatchingCType();
16370       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16371       TypeInfo.MustBeNull = I->getMustBeNull();
16372       return true;
16373     }
16374     return false;
16375   }
16376 
16377   if (!MagicValues)
16378     return false;
16379 
16380   llvm::DenseMap<Sema::TypeTagMagicValue,
16381                  Sema::TypeTagData>::const_iterator I =
16382       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16383   if (I == MagicValues->end())
16384     return false;
16385 
16386   TypeInfo = I->second;
16387   return true;
16388 }
16389 
16390 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16391                                       uint64_t MagicValue, QualType Type,
16392                                       bool LayoutCompatible,
16393                                       bool MustBeNull) {
16394   if (!TypeTagForDatatypeMagicValues)
16395     TypeTagForDatatypeMagicValues.reset(
16396         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16397 
16398   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16399   (*TypeTagForDatatypeMagicValues)[Magic] =
16400       TypeTagData(Type, LayoutCompatible, MustBeNull);
16401 }
16402 
16403 static bool IsSameCharType(QualType T1, QualType T2) {
16404   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16405   if (!BT1)
16406     return false;
16407 
16408   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16409   if (!BT2)
16410     return false;
16411 
16412   BuiltinType::Kind T1Kind = BT1->getKind();
16413   BuiltinType::Kind T2Kind = BT2->getKind();
16414 
16415   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16416          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16417          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16418          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16419 }
16420 
16421 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16422                                     const ArrayRef<const Expr *> ExprArgs,
16423                                     SourceLocation CallSiteLoc) {
16424   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16425   bool IsPointerAttr = Attr->getIsPointer();
16426 
16427   // Retrieve the argument representing the 'type_tag'.
16428   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16429   if (TypeTagIdxAST >= ExprArgs.size()) {
16430     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16431         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16432     return;
16433   }
16434   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16435   bool FoundWrongKind;
16436   TypeTagData TypeInfo;
16437   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16438                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16439                         TypeInfo, isConstantEvaluated())) {
16440     if (FoundWrongKind)
16441       Diag(TypeTagExpr->getExprLoc(),
16442            diag::warn_type_tag_for_datatype_wrong_kind)
16443         << TypeTagExpr->getSourceRange();
16444     return;
16445   }
16446 
16447   // Retrieve the argument representing the 'arg_idx'.
16448   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16449   if (ArgumentIdxAST >= ExprArgs.size()) {
16450     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16451         << 1 << Attr->getArgumentIdx().getSourceIndex();
16452     return;
16453   }
16454   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16455   if (IsPointerAttr) {
16456     // Skip implicit cast of pointer to `void *' (as a function argument).
16457     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16458       if (ICE->getType()->isVoidPointerType() &&
16459           ICE->getCastKind() == CK_BitCast)
16460         ArgumentExpr = ICE->getSubExpr();
16461   }
16462   QualType ArgumentType = ArgumentExpr->getType();
16463 
16464   // Passing a `void*' pointer shouldn't trigger a warning.
16465   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16466     return;
16467 
16468   if (TypeInfo.MustBeNull) {
16469     // Type tag with matching void type requires a null pointer.
16470     if (!ArgumentExpr->isNullPointerConstant(Context,
16471                                              Expr::NPC_ValueDependentIsNotNull)) {
16472       Diag(ArgumentExpr->getExprLoc(),
16473            diag::warn_type_safety_null_pointer_required)
16474           << ArgumentKind->getName()
16475           << ArgumentExpr->getSourceRange()
16476           << TypeTagExpr->getSourceRange();
16477     }
16478     return;
16479   }
16480 
16481   QualType RequiredType = TypeInfo.Type;
16482   if (IsPointerAttr)
16483     RequiredType = Context.getPointerType(RequiredType);
16484 
16485   bool mismatch = false;
16486   if (!TypeInfo.LayoutCompatible) {
16487     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16488 
16489     // C++11 [basic.fundamental] p1:
16490     // Plain char, signed char, and unsigned char are three distinct types.
16491     //
16492     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16493     // char' depending on the current char signedness mode.
16494     if (mismatch)
16495       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16496                                            RequiredType->getPointeeType())) ||
16497           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16498         mismatch = false;
16499   } else
16500     if (IsPointerAttr)
16501       mismatch = !isLayoutCompatible(Context,
16502                                      ArgumentType->getPointeeType(),
16503                                      RequiredType->getPointeeType());
16504     else
16505       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16506 
16507   if (mismatch)
16508     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16509         << ArgumentType << ArgumentKind
16510         << TypeInfo.LayoutCompatible << RequiredType
16511         << ArgumentExpr->getSourceRange()
16512         << TypeTagExpr->getSourceRange();
16513 }
16514 
16515 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16516                                          CharUnits Alignment) {
16517   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16518 }
16519 
16520 void Sema::DiagnoseMisalignedMembers() {
16521   for (MisalignedMember &m : MisalignedMembers) {
16522     const NamedDecl *ND = m.RD;
16523     if (ND->getName().empty()) {
16524       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16525         ND = TD;
16526     }
16527     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16528         << m.MD << ND << m.E->getSourceRange();
16529   }
16530   MisalignedMembers.clear();
16531 }
16532 
16533 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16534   E = E->IgnoreParens();
16535   if (!T->isPointerType() && !T->isIntegerType())
16536     return;
16537   if (isa<UnaryOperator>(E) &&
16538       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16539     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16540     if (isa<MemberExpr>(Op)) {
16541       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16542       if (MA != MisalignedMembers.end() &&
16543           (T->isIntegerType() ||
16544            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16545                                    Context.getTypeAlignInChars(
16546                                        T->getPointeeType()) <= MA->Alignment))))
16547         MisalignedMembers.erase(MA);
16548     }
16549   }
16550 }
16551 
16552 void Sema::RefersToMemberWithReducedAlignment(
16553     Expr *E,
16554     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16555         Action) {
16556   const auto *ME = dyn_cast<MemberExpr>(E);
16557   if (!ME)
16558     return;
16559 
16560   // No need to check expressions with an __unaligned-qualified type.
16561   if (E->getType().getQualifiers().hasUnaligned())
16562     return;
16563 
16564   // For a chain of MemberExpr like "a.b.c.d" this list
16565   // will keep FieldDecl's like [d, c, b].
16566   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16567   const MemberExpr *TopME = nullptr;
16568   bool AnyIsPacked = false;
16569   do {
16570     QualType BaseType = ME->getBase()->getType();
16571     if (BaseType->isDependentType())
16572       return;
16573     if (ME->isArrow())
16574       BaseType = BaseType->getPointeeType();
16575     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16576     if (RD->isInvalidDecl())
16577       return;
16578 
16579     ValueDecl *MD = ME->getMemberDecl();
16580     auto *FD = dyn_cast<FieldDecl>(MD);
16581     // We do not care about non-data members.
16582     if (!FD || FD->isInvalidDecl())
16583       return;
16584 
16585     AnyIsPacked =
16586         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16587     ReverseMemberChain.push_back(FD);
16588 
16589     TopME = ME;
16590     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16591   } while (ME);
16592   assert(TopME && "We did not compute a topmost MemberExpr!");
16593 
16594   // Not the scope of this diagnostic.
16595   if (!AnyIsPacked)
16596     return;
16597 
16598   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16599   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16600   // TODO: The innermost base of the member expression may be too complicated.
16601   // For now, just disregard these cases. This is left for future
16602   // improvement.
16603   if (!DRE && !isa<CXXThisExpr>(TopBase))
16604       return;
16605 
16606   // Alignment expected by the whole expression.
16607   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16608 
16609   // No need to do anything else with this case.
16610   if (ExpectedAlignment.isOne())
16611     return;
16612 
16613   // Synthesize offset of the whole access.
16614   CharUnits Offset;
16615   for (const FieldDecl *FD : llvm::reverse(ReverseMemberChain))
16616     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(FD));
16617 
16618   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16619   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16620       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16621 
16622   // The base expression of the innermost MemberExpr may give
16623   // stronger guarantees than the class containing the member.
16624   if (DRE && !TopME->isArrow()) {
16625     const ValueDecl *VD = DRE->getDecl();
16626     if (!VD->getType()->isReferenceType())
16627       CompleteObjectAlignment =
16628           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16629   }
16630 
16631   // Check if the synthesized offset fulfills the alignment.
16632   if (Offset % ExpectedAlignment != 0 ||
16633       // It may fulfill the offset it but the effective alignment may still be
16634       // lower than the expected expression alignment.
16635       CompleteObjectAlignment < ExpectedAlignment) {
16636     // If this happens, we want to determine a sensible culprit of this.
16637     // Intuitively, watching the chain of member expressions from right to
16638     // left, we start with the required alignment (as required by the field
16639     // type) but some packed attribute in that chain has reduced the alignment.
16640     // It may happen that another packed structure increases it again. But if
16641     // we are here such increase has not been enough. So pointing the first
16642     // FieldDecl that either is packed or else its RecordDecl is,
16643     // seems reasonable.
16644     FieldDecl *FD = nullptr;
16645     CharUnits Alignment;
16646     for (FieldDecl *FDI : ReverseMemberChain) {
16647       if (FDI->hasAttr<PackedAttr>() ||
16648           FDI->getParent()->hasAttr<PackedAttr>()) {
16649         FD = FDI;
16650         Alignment = std::min(
16651             Context.getTypeAlignInChars(FD->getType()),
16652             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16653         break;
16654       }
16655     }
16656     assert(FD && "We did not find a packed FieldDecl!");
16657     Action(E, FD->getParent(), FD, Alignment);
16658   }
16659 }
16660 
16661 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16662   using namespace std::placeholders;
16663 
16664   RefersToMemberWithReducedAlignment(
16665       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16666                      _2, _3, _4));
16667 }
16668 
16669 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16670 // not a valid type, emit an error message and return true. Otherwise return
16671 // false.
16672 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16673                                         QualType Ty) {
16674   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16675     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16676         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16677     return true;
16678   }
16679   return false;
16680 }
16681 
16682 bool Sema::SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall) {
16683   if (checkArgCount(*this, TheCall, 1))
16684     return true;
16685 
16686   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16687   SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16688   if (A.isInvalid())
16689     return true;
16690 
16691   TheCall->setArg(0, A.get());
16692   QualType TyA = A.get()->getType();
16693   if (checkMathBuiltinElementType(*this, ArgLoc, TyA))
16694     return true;
16695 
16696   QualType EltTy = TyA;
16697   if (auto *VecTy = EltTy->getAs<VectorType>())
16698     EltTy = VecTy->getElementType();
16699   if (EltTy->isUnsignedIntegerType())
16700     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16701            << 1 << /*signed integer or float ty*/ 3 << TyA;
16702 
16703   TheCall->setType(TyA);
16704   return false;
16705 }
16706 
16707 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16708   if (checkArgCount(*this, TheCall, 2))
16709     return true;
16710 
16711   ExprResult A = TheCall->getArg(0);
16712   ExprResult B = TheCall->getArg(1);
16713   // Do standard promotions between the two arguments, returning their common
16714   // type.
16715   QualType Res =
16716       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16717   if (A.isInvalid() || B.isInvalid())
16718     return true;
16719 
16720   QualType TyA = A.get()->getType();
16721   QualType TyB = B.get()->getType();
16722 
16723   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16724     return Diag(A.get()->getBeginLoc(),
16725                 diag::err_typecheck_call_different_arg_types)
16726            << TyA << TyB;
16727 
16728   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16729     return true;
16730 
16731   TheCall->setArg(0, A.get());
16732   TheCall->setArg(1, B.get());
16733   TheCall->setType(Res);
16734   return false;
16735 }
16736 
16737 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) {
16738   if (checkArgCount(*this, TheCall, 1))
16739     return true;
16740 
16741   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16742   if (A.isInvalid())
16743     return true;
16744 
16745   TheCall->setArg(0, A.get());
16746   const VectorType *TyA = A.get()->getType()->getAs<VectorType>();
16747   if (!TyA) {
16748     SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16749     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16750            << 1 << /* vector ty*/ 4 << A.get()->getType();
16751   }
16752 
16753   TheCall->setType(TyA->getElementType());
16754   return false;
16755 }
16756 
16757 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16758                                             ExprResult CallResult) {
16759   if (checkArgCount(*this, TheCall, 1))
16760     return ExprError();
16761 
16762   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16763   if (MatrixArg.isInvalid())
16764     return MatrixArg;
16765   Expr *Matrix = MatrixArg.get();
16766 
16767   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16768   if (!MType) {
16769     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16770         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16771     return ExprError();
16772   }
16773 
16774   // Create returned matrix type by swapping rows and columns of the argument
16775   // matrix type.
16776   QualType ResultType = Context.getConstantMatrixType(
16777       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16778 
16779   // Change the return type to the type of the returned matrix.
16780   TheCall->setType(ResultType);
16781 
16782   // Update call argument to use the possibly converted matrix argument.
16783   TheCall->setArg(0, Matrix);
16784   return CallResult;
16785 }
16786 
16787 // Get and verify the matrix dimensions.
16788 static llvm::Optional<unsigned>
16789 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16790   SourceLocation ErrorPos;
16791   Optional<llvm::APSInt> Value =
16792       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16793   if (!Value) {
16794     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16795         << Name;
16796     return {};
16797   }
16798   uint64_t Dim = Value->getZExtValue();
16799   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16800     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16801         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16802     return {};
16803   }
16804   return Dim;
16805 }
16806 
16807 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16808                                                   ExprResult CallResult) {
16809   if (!getLangOpts().MatrixTypes) {
16810     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16811     return ExprError();
16812   }
16813 
16814   if (checkArgCount(*this, TheCall, 4))
16815     return ExprError();
16816 
16817   unsigned PtrArgIdx = 0;
16818   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16819   Expr *RowsExpr = TheCall->getArg(1);
16820   Expr *ColumnsExpr = TheCall->getArg(2);
16821   Expr *StrideExpr = TheCall->getArg(3);
16822 
16823   bool ArgError = false;
16824 
16825   // Check pointer argument.
16826   {
16827     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16828     if (PtrConv.isInvalid())
16829       return PtrConv;
16830     PtrExpr = PtrConv.get();
16831     TheCall->setArg(0, PtrExpr);
16832     if (PtrExpr->isTypeDependent()) {
16833       TheCall->setType(Context.DependentTy);
16834       return TheCall;
16835     }
16836   }
16837 
16838   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16839   QualType ElementTy;
16840   if (!PtrTy) {
16841     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16842         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16843     ArgError = true;
16844   } else {
16845     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16846 
16847     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16848       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16849           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
16850           << PtrExpr->getType();
16851       ArgError = true;
16852     }
16853   }
16854 
16855   // Apply default Lvalue conversions and convert the expression to size_t.
16856   auto ApplyArgumentConversions = [this](Expr *E) {
16857     ExprResult Conv = DefaultLvalueConversion(E);
16858     if (Conv.isInvalid())
16859       return Conv;
16860 
16861     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16862   };
16863 
16864   // Apply conversion to row and column expressions.
16865   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16866   if (!RowsConv.isInvalid()) {
16867     RowsExpr = RowsConv.get();
16868     TheCall->setArg(1, RowsExpr);
16869   } else
16870     RowsExpr = nullptr;
16871 
16872   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16873   if (!ColumnsConv.isInvalid()) {
16874     ColumnsExpr = ColumnsConv.get();
16875     TheCall->setArg(2, ColumnsExpr);
16876   } else
16877     ColumnsExpr = nullptr;
16878 
16879   // If any any part of the result matrix type is still pending, just use
16880   // Context.DependentTy, until all parts are resolved.
16881   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16882       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16883     TheCall->setType(Context.DependentTy);
16884     return CallResult;
16885   }
16886 
16887   // Check row and column dimensions.
16888   llvm::Optional<unsigned> MaybeRows;
16889   if (RowsExpr)
16890     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16891 
16892   llvm::Optional<unsigned> MaybeColumns;
16893   if (ColumnsExpr)
16894     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16895 
16896   // Check stride argument.
16897   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16898   if (StrideConv.isInvalid())
16899     return ExprError();
16900   StrideExpr = StrideConv.get();
16901   TheCall->setArg(3, StrideExpr);
16902 
16903   if (MaybeRows) {
16904     if (Optional<llvm::APSInt> Value =
16905             StrideExpr->getIntegerConstantExpr(Context)) {
16906       uint64_t Stride = Value->getZExtValue();
16907       if (Stride < *MaybeRows) {
16908         Diag(StrideExpr->getBeginLoc(),
16909              diag::err_builtin_matrix_stride_too_small);
16910         ArgError = true;
16911       }
16912     }
16913   }
16914 
16915   if (ArgError || !MaybeRows || !MaybeColumns)
16916     return ExprError();
16917 
16918   TheCall->setType(
16919       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16920   return CallResult;
16921 }
16922 
16923 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16924                                                    ExprResult CallResult) {
16925   if (checkArgCount(*this, TheCall, 3))
16926     return ExprError();
16927 
16928   unsigned PtrArgIdx = 1;
16929   Expr *MatrixExpr = TheCall->getArg(0);
16930   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16931   Expr *StrideExpr = TheCall->getArg(2);
16932 
16933   bool ArgError = false;
16934 
16935   {
16936     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16937     if (MatrixConv.isInvalid())
16938       return MatrixConv;
16939     MatrixExpr = MatrixConv.get();
16940     TheCall->setArg(0, MatrixExpr);
16941   }
16942   if (MatrixExpr->isTypeDependent()) {
16943     TheCall->setType(Context.DependentTy);
16944     return TheCall;
16945   }
16946 
16947   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16948   if (!MatrixTy) {
16949     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16950         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
16951     ArgError = true;
16952   }
16953 
16954   {
16955     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16956     if (PtrConv.isInvalid())
16957       return PtrConv;
16958     PtrExpr = PtrConv.get();
16959     TheCall->setArg(1, PtrExpr);
16960     if (PtrExpr->isTypeDependent()) {
16961       TheCall->setType(Context.DependentTy);
16962       return TheCall;
16963     }
16964   }
16965 
16966   // Check pointer argument.
16967   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16968   if (!PtrTy) {
16969     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16970         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16971     ArgError = true;
16972   } else {
16973     QualType ElementTy = PtrTy->getPointeeType();
16974     if (ElementTy.isConstQualified()) {
16975       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16976       ArgError = true;
16977     }
16978     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16979     if (MatrixTy &&
16980         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16981       Diag(PtrExpr->getBeginLoc(),
16982            diag::err_builtin_matrix_pointer_arg_mismatch)
16983           << ElementTy << MatrixTy->getElementType();
16984       ArgError = true;
16985     }
16986   }
16987 
16988   // Apply default Lvalue conversions and convert the stride expression to
16989   // size_t.
16990   {
16991     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16992     if (StrideConv.isInvalid())
16993       return StrideConv;
16994 
16995     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16996     if (StrideConv.isInvalid())
16997       return StrideConv;
16998     StrideExpr = StrideConv.get();
16999     TheCall->setArg(2, StrideExpr);
17000   }
17001 
17002   // Check stride argument.
17003   if (MatrixTy) {
17004     if (Optional<llvm::APSInt> Value =
17005             StrideExpr->getIntegerConstantExpr(Context)) {
17006       uint64_t Stride = Value->getZExtValue();
17007       if (Stride < MatrixTy->getNumRows()) {
17008         Diag(StrideExpr->getBeginLoc(),
17009              diag::err_builtin_matrix_stride_too_small);
17010         ArgError = true;
17011       }
17012     }
17013   }
17014 
17015   if (ArgError)
17016     return ExprError();
17017 
17018   return CallResult;
17019 }
17020 
17021 /// \brief Enforce the bounds of a TCB
17022 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
17023 /// directly calls other functions in the same TCB as marked by the enforce_tcb
17024 /// and enforce_tcb_leaf attributes.
17025 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
17026                                const FunctionDecl *Callee) {
17027   const FunctionDecl *Caller = getCurFunctionDecl();
17028 
17029   // Calls to builtins are not enforced.
17030   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
17031       Callee->getBuiltinID() != 0)
17032     return;
17033 
17034   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
17035   // all TCBs the callee is a part of.
17036   llvm::StringSet<> CalleeTCBs;
17037   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
17038            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17039   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
17040            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
17041 
17042   // Go through the TCBs the caller is a part of and emit warnings if Caller
17043   // is in a TCB that the Callee is not.
17044   for_each(
17045       Caller->specific_attrs<EnforceTCBAttr>(),
17046       [&](const auto *A) {
17047         StringRef CallerTCB = A->getTCBName();
17048         if (CalleeTCBs.count(CallerTCB) == 0) {
17049           this->Diag(TheCall->getExprLoc(),
17050                      diag::warn_tcb_enforcement_violation) << Callee
17051                                                            << CallerTCB;
17052         }
17053       });
17054 }
17055