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 EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
592                                                CallExpr *TheCall) {
593   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
594       isConstantEvaluated())
595     return;
596 
597   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
598   if (!BuiltinID)
599     return;
600 
601   const TargetInfo &TI = getASTContext().getTargetInfo();
602   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
603 
604   auto ComputeExplicitObjectSizeArgument =
605       [&](unsigned Index) -> Optional<llvm::APSInt> {
606     Expr::EvalResult Result;
607     Expr *SizeArg = TheCall->getArg(Index);
608     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
609       return llvm::None;
610     return Result.Val.getInt();
611   };
612 
613   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
614     // If the parameter has a pass_object_size attribute, then we should use its
615     // (potentially) more strict checking mode. Otherwise, conservatively assume
616     // type 0.
617     int BOSType = 0;
618     if (const auto *POS =
619             FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
620       BOSType = POS->getType();
621 
622     const Expr *ObjArg = TheCall->getArg(Index);
623     uint64_t Result;
624     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
625       return llvm::None;
626 
627     // Get the object size in the target's size_t width.
628     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
629   };
630 
631   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
632     Expr *ObjArg = TheCall->getArg(Index);
633     uint64_t Result;
634     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
635       return llvm::None;
636     // Add 1 for null byte.
637     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
638   };
639 
640   Optional<llvm::APSInt> SourceSize;
641   Optional<llvm::APSInt> DestinationSize;
642   unsigned DiagID = 0;
643   bool IsChkVariant = false;
644 
645   switch (BuiltinID) {
646   default:
647     return;
648   case Builtin::BI__builtin_strcpy:
649   case Builtin::BIstrcpy: {
650     DiagID = diag::warn_fortify_strlen_overflow;
651     SourceSize = ComputeStrLenArgument(1);
652     DestinationSize = ComputeSizeArgument(0);
653     break;
654   }
655 
656   case Builtin::BI__builtin___strcpy_chk: {
657     DiagID = diag::warn_fortify_strlen_overflow;
658     SourceSize = ComputeStrLenArgument(1);
659     DestinationSize = ComputeExplicitObjectSizeArgument(2);
660     IsChkVariant = true;
661     break;
662   }
663 
664   case Builtin::BIsprintf:
665   case Builtin::BI__builtin___sprintf_chk: {
666     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
667     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
668 
669     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
670 
671       if (!Format->isAscii() && !Format->isUTF8())
672         return;
673 
674       StringRef FormatStrRef = Format->getString();
675       EstimateSizeFormatHandler H(FormatStrRef);
676       const char *FormatBytes = FormatStrRef.data();
677       const ConstantArrayType *T =
678           Context.getAsConstantArrayType(Format->getType());
679       assert(T && "String literal not of constant array type!");
680       size_t TypeSize = T->getSize().getZExtValue();
681 
682       // In case there's a null byte somewhere.
683       size_t StrLen =
684           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
685       if (!analyze_format_string::ParsePrintfString(
686               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
687               Context.getTargetInfo(), false)) {
688         DiagID = diag::warn_fortify_source_format_overflow;
689         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
690                          .extOrTrunc(SizeTypeWidth);
691         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
692           DestinationSize = ComputeExplicitObjectSizeArgument(2);
693           IsChkVariant = true;
694         } else {
695           DestinationSize = ComputeSizeArgument(0);
696         }
697         break;
698       }
699     }
700     return;
701   }
702   case Builtin::BI__builtin___memcpy_chk:
703   case Builtin::BI__builtin___memmove_chk:
704   case Builtin::BI__builtin___memset_chk:
705   case Builtin::BI__builtin___strlcat_chk:
706   case Builtin::BI__builtin___strlcpy_chk:
707   case Builtin::BI__builtin___strncat_chk:
708   case Builtin::BI__builtin___strncpy_chk:
709   case Builtin::BI__builtin___stpncpy_chk:
710   case Builtin::BI__builtin___memccpy_chk:
711   case Builtin::BI__builtin___mempcpy_chk: {
712     DiagID = diag::warn_builtin_chk_overflow;
713     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
714     DestinationSize =
715         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
716     IsChkVariant = true;
717     break;
718   }
719 
720   case Builtin::BI__builtin___snprintf_chk:
721   case Builtin::BI__builtin___vsnprintf_chk: {
722     DiagID = diag::warn_builtin_chk_overflow;
723     SourceSize = ComputeExplicitObjectSizeArgument(1);
724     DestinationSize = ComputeExplicitObjectSizeArgument(3);
725     IsChkVariant = true;
726     break;
727   }
728 
729   case Builtin::BIstrncat:
730   case Builtin::BI__builtin_strncat:
731   case Builtin::BIstrncpy:
732   case Builtin::BI__builtin_strncpy:
733   case Builtin::BIstpncpy:
734   case Builtin::BI__builtin_stpncpy: {
735     // Whether these functions overflow depends on the runtime strlen of the
736     // string, not just the buffer size, so emitting the "always overflow"
737     // diagnostic isn't quite right. We should still diagnose passing a buffer
738     // size larger than the destination buffer though; this is a runtime abort
739     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
740     DiagID = diag::warn_fortify_source_size_mismatch;
741     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
742     DestinationSize = ComputeSizeArgument(0);
743     break;
744   }
745 
746   case Builtin::BImemcpy:
747   case Builtin::BI__builtin_memcpy:
748   case Builtin::BImemmove:
749   case Builtin::BI__builtin_memmove:
750   case Builtin::BImemset:
751   case Builtin::BI__builtin_memset:
752   case Builtin::BImempcpy:
753   case Builtin::BI__builtin_mempcpy: {
754     DiagID = diag::warn_fortify_source_overflow;
755     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
756     DestinationSize = ComputeSizeArgument(0);
757     break;
758   }
759   case Builtin::BIsnprintf:
760   case Builtin::BI__builtin_snprintf:
761   case Builtin::BIvsnprintf:
762   case Builtin::BI__builtin_vsnprintf: {
763     DiagID = diag::warn_fortify_source_size_mismatch;
764     SourceSize = ComputeExplicitObjectSizeArgument(1);
765     DestinationSize = ComputeSizeArgument(0);
766     break;
767   }
768   }
769 
770   if (!SourceSize || !DestinationSize ||
771       SourceSize.getValue().ule(DestinationSize.getValue()))
772     return;
773 
774   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775   // Skim off the details of whichever builtin was called to produce a better
776   // diagnostic, as it's unlikely that the user wrote the __builtin explicitly.
777   if (IsChkVariant) {
778     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780   } else if (FunctionName.startswith("__builtin_")) {
781     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782   }
783 
784   SmallString<16> DestinationStr;
785   SmallString<16> SourceStr;
786   DestinationSize->toString(DestinationStr, /*Radix=*/10);
787   SourceSize->toString(SourceStr, /*Radix=*/10);
788   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
789                       PDiag(DiagID)
790                           << FunctionName << DestinationStr << SourceStr);
791 }
792 
793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
794                                      Scope::ScopeFlags NeededScopeFlags,
795                                      unsigned DiagID) {
796   // Scopes aren't available during instantiation. Fortunately, builtin
797   // functions cannot be template args so they cannot be formed through template
798   // instantiation. Therefore checking once during the parse is sufficient.
799   if (SemaRef.inTemplateInstantiation())
800     return false;
801 
802   Scope *S = SemaRef.getCurScope();
803   while (S && !S->isSEHExceptScope())
804     S = S->getParent();
805   if (!S || !(S->getFlags() & NeededScopeFlags)) {
806     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
807     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
808         << DRE->getDecl()->getIdentifier();
809     return true;
810   }
811 
812   return false;
813 }
814 
815 static inline bool isBlockPointer(Expr *Arg) {
816   return Arg->getType()->isBlockPointerType();
817 }
818 
819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
820 /// void*, which is a requirement of device side enqueue.
821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
822   const BlockPointerType *BPT =
823       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
824   ArrayRef<QualType> Params =
825       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
826   unsigned ArgCounter = 0;
827   bool IllegalParams = false;
828   // Iterate through the block parameters until either one is found that is not
829   // a local void*, or the block is valid.
830   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
831        I != E; ++I, ++ArgCounter) {
832     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
833         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
834             LangAS::opencl_local) {
835       // Get the location of the error. If a block literal has been passed
836       // (BlockExpr) then we can point straight to the offending argument,
837       // else we just point to the variable reference.
838       SourceLocation ErrorLoc;
839       if (isa<BlockExpr>(BlockArg)) {
840         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
841         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
842       } else if (isa<DeclRefExpr>(BlockArg)) {
843         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
844       }
845       S.Diag(ErrorLoc,
846              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
847       IllegalParams = true;
848     }
849   }
850 
851   return IllegalParams;
852 }
853 
854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
855   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
856     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
857         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
858     return true;
859   }
860   return false;
861 }
862 
863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
864   if (checkArgCount(S, TheCall, 2))
865     return true;
866 
867   if (checkOpenCLSubgroupExt(S, TheCall))
868     return true;
869 
870   // First argument is an ndrange_t type.
871   Expr *NDRangeArg = TheCall->getArg(0);
872   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
873     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
874         << TheCall->getDirectCallee() << "'ndrange_t'";
875     return true;
876   }
877 
878   Expr *BlockArg = TheCall->getArg(1);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
888 /// get_kernel_work_group_size
889 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
891   if (checkArgCount(S, TheCall, 1))
892     return true;
893 
894   Expr *BlockArg = TheCall->getArg(0);
895   if (!isBlockPointer(BlockArg)) {
896     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
897         << TheCall->getDirectCallee() << "block";
898     return true;
899   }
900   return checkOpenCLBlockArgs(S, BlockArg);
901 }
902 
903 /// Diagnose integer type and any valid implicit conversion to it.
904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
905                                       const QualType &IntType);
906 
907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
908                                             unsigned Start, unsigned End) {
909   bool IllegalParams = false;
910   for (unsigned I = Start; I <= End; ++I)
911     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
912                                               S.Context.getSizeType());
913   return IllegalParams;
914 }
915 
916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
917 /// 'local void*' parameter of passed block.
918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
919                                            Expr *BlockArg,
920                                            unsigned NumNonVarArgs) {
921   const BlockPointerType *BPT =
922       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
923   unsigned NumBlockParams =
924       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
925   unsigned TotalNumArgs = TheCall->getNumArgs();
926 
927   // For each argument passed to the block, a corresponding uint needs to
928   // be passed to describe the size of the local memory.
929   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
930     S.Diag(TheCall->getBeginLoc(),
931            diag::err_opencl_enqueue_kernel_local_size_args);
932     return true;
933   }
934 
935   // Check that the sizes of the local memory are specified by integers.
936   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
937                                          TotalNumArgs - 1);
938 }
939 
940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
941 /// overload formats specified in Table 6.13.17.1.
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    void (^block)(void))
946 /// int enqueue_kernel(queue_t queue,
947 ///                    kernel_enqueue_flags_t flags,
948 ///                    const ndrange_t ndrange,
949 ///                    uint num_events_in_wait_list,
950 ///                    clk_event_t *event_wait_list,
951 ///                    clk_event_t *event_ret,
952 ///                    void (^block)(void))
953 /// int enqueue_kernel(queue_t queue,
954 ///                    kernel_enqueue_flags_t flags,
955 ///                    const ndrange_t ndrange,
956 ///                    void (^block)(local void*, ...),
957 ///                    uint size0, ...)
958 /// int enqueue_kernel(queue_t queue,
959 ///                    kernel_enqueue_flags_t flags,
960 ///                    const ndrange_t ndrange,
961 ///                    uint num_events_in_wait_list,
962 ///                    clk_event_t *event_wait_list,
963 ///                    clk_event_t *event_ret,
964 ///                    void (^block)(local void*, ...),
965 ///                    uint size0, ...)
966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
967   unsigned NumArgs = TheCall->getNumArgs();
968 
969   if (NumArgs < 4) {
970     S.Diag(TheCall->getBeginLoc(),
971            diag::err_typecheck_call_too_few_args_at_least)
972         << 0 << 4 << NumArgs;
973     return true;
974   }
975 
976   Expr *Arg0 = TheCall->getArg(0);
977   Expr *Arg1 = TheCall->getArg(1);
978   Expr *Arg2 = TheCall->getArg(2);
979   Expr *Arg3 = TheCall->getArg(3);
980 
981   // First argument always needs to be a queue_t type.
982   if (!Arg0->getType()->isQueueT()) {
983     S.Diag(TheCall->getArg(0)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
986     return true;
987   }
988 
989   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
990   if (!Arg1->getType()->isIntegerType()) {
991     S.Diag(TheCall->getArg(1)->getBeginLoc(),
992            diag::err_opencl_builtin_expected_type)
993         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
994     return true;
995   }
996 
997   // Third argument is always an ndrange_t type.
998   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
999     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1000            diag::err_opencl_builtin_expected_type)
1001         << TheCall->getDirectCallee() << "'ndrange_t'";
1002     return true;
1003   }
1004 
1005   // With four arguments, there is only one form that the function could be
1006   // called in: no events and no variable arguments.
1007   if (NumArgs == 4) {
1008     // check that the last argument is the right block type.
1009     if (!isBlockPointer(Arg3)) {
1010       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1011           << TheCall->getDirectCallee() << "block";
1012       return true;
1013     }
1014     // we have a block type, check the prototype
1015     const BlockPointerType *BPT =
1016         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1017     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1018       S.Diag(Arg3->getBeginLoc(),
1019              diag::err_opencl_enqueue_kernel_blocks_no_args);
1020       return true;
1021     }
1022     return false;
1023   }
1024   // we can have block + varargs.
1025   if (isBlockPointer(Arg3))
1026     return (checkOpenCLBlockArgs(S, Arg3) ||
1027             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1028   // last two cases with either exactly 7 args or 7 args and varargs.
1029   if (NumArgs >= 7) {
1030     // check common block argument.
1031     Expr *Arg6 = TheCall->getArg(6);
1032     if (!isBlockPointer(Arg6)) {
1033       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1034           << TheCall->getDirectCallee() << "block";
1035       return true;
1036     }
1037     if (checkOpenCLBlockArgs(S, Arg6))
1038       return true;
1039 
1040     // Forth argument has to be any integer type.
1041     if (!Arg3->getType()->isIntegerType()) {
1042       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee() << "integer";
1045       return true;
1046     }
1047     // check remaining common arguments.
1048     Expr *Arg4 = TheCall->getArg(4);
1049     Expr *Arg5 = TheCall->getArg(5);
1050 
1051     // Fifth argument is always passed as a pointer to clk_event_t.
1052     if (!Arg4->isNullPointerConstant(S.Context,
1053                                      Expr::NPC_ValueDependentIsNotNull) &&
1054         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1055       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1056              diag::err_opencl_builtin_expected_type)
1057           << TheCall->getDirectCallee()
1058           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1059       return true;
1060     }
1061 
1062     // Sixth argument is always passed as a pointer to clk_event_t.
1063     if (!Arg5->isNullPointerConstant(S.Context,
1064                                      Expr::NPC_ValueDependentIsNotNull) &&
1065         !(Arg5->getType()->isPointerType() &&
1066           Arg5->getType()->getPointeeType()->isClkEventT())) {
1067       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1068              diag::err_opencl_builtin_expected_type)
1069           << TheCall->getDirectCallee()
1070           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1071       return true;
1072     }
1073 
1074     if (NumArgs == 7)
1075       return false;
1076 
1077     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1078   }
1079 
1080   // None of the specific case has been detected, give generic error
1081   S.Diag(TheCall->getBeginLoc(),
1082          diag::err_opencl_enqueue_kernel_incorrect_args);
1083   return true;
1084 }
1085 
1086 /// Returns OpenCL access qual.
1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1088     return D->getAttr<OpenCLAccessAttr>();
1089 }
1090 
1091 /// Returns true if pipe element type is different from the pointer.
1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1093   const Expr *Arg0 = Call->getArg(0);
1094   // First argument type should always be pipe.
1095   if (!Arg0->getType()->isPipeType()) {
1096     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1097         << Call->getDirectCallee() << Arg0->getSourceRange();
1098     return true;
1099   }
1100   OpenCLAccessAttr *AccessQual =
1101       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1102   // Validates the access qualifier is compatible with the call.
1103   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1104   // read_only and write_only, and assumed to be read_only if no qualifier is
1105   // specified.
1106   switch (Call->getDirectCallee()->getBuiltinID()) {
1107   case Builtin::BIread_pipe:
1108   case Builtin::BIreserve_read_pipe:
1109   case Builtin::BIcommit_read_pipe:
1110   case Builtin::BIwork_group_reserve_read_pipe:
1111   case Builtin::BIsub_group_reserve_read_pipe:
1112   case Builtin::BIwork_group_commit_read_pipe:
1113   case Builtin::BIsub_group_commit_read_pipe:
1114     if (!(!AccessQual || AccessQual->isReadOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "read_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   case Builtin::BIwrite_pipe:
1122   case Builtin::BIreserve_write_pipe:
1123   case Builtin::BIcommit_write_pipe:
1124   case Builtin::BIwork_group_reserve_write_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126   case Builtin::BIwork_group_commit_write_pipe:
1127   case Builtin::BIsub_group_commit_write_pipe:
1128     if (!(AccessQual && AccessQual->isWriteOnly())) {
1129       S.Diag(Arg0->getBeginLoc(),
1130              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1131           << "write_only" << Arg0->getSourceRange();
1132       return true;
1133     }
1134     break;
1135   default:
1136     break;
1137   }
1138   return false;
1139 }
1140 
1141 /// Returns true if pipe element type is different from the pointer.
1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1143   const Expr *Arg0 = Call->getArg(0);
1144   const Expr *ArgIdx = Call->getArg(Idx);
1145   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1146   const QualType EltTy = PipeTy->getElementType();
1147   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1148   // The Idx argument should be a pointer and the type of the pointer and
1149   // the type of pipe element should also be the same.
1150   if (!ArgTy ||
1151       !S.Context.hasSameType(
1152           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1153     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1154         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1155         << ArgIdx->getType() << ArgIdx->getSourceRange();
1156     return true;
1157   }
1158   return false;
1159 }
1160 
1161 // Performs semantic analysis for the read/write_pipe call.
1162 // \param S Reference to the semantic analyzer.
1163 // \param Call A pointer to the builtin call.
1164 // \return True if a semantic error has been found, false otherwise.
1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1166   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1167   // functions have two forms.
1168   switch (Call->getNumArgs()) {
1169   case 2:
1170     if (checkOpenCLPipeArg(S, Call))
1171       return true;
1172     // The call with 2 arguments should be
1173     // read/write_pipe(pipe T, T*).
1174     // Check packet type T.
1175     if (checkOpenCLPipePacketType(S, Call, 1))
1176       return true;
1177     break;
1178 
1179   case 4: {
1180     if (checkOpenCLPipeArg(S, Call))
1181       return true;
1182     // The call with 4 arguments should be
1183     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1184     // Check reserve_id_t.
1185     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1186       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1187           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1188           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1189       return true;
1190     }
1191 
1192     // Check the index.
1193     const Expr *Arg2 = Call->getArg(2);
1194     if (!Arg2->getType()->isIntegerType() &&
1195         !Arg2->getType()->isUnsignedIntegerType()) {
1196       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1197           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1198           << Arg2->getType() << Arg2->getSourceRange();
1199       return true;
1200     }
1201 
1202     // Check packet type T.
1203     if (checkOpenCLPipePacketType(S, Call, 3))
1204       return true;
1205   } break;
1206   default:
1207     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1208         << Call->getDirectCallee() << Call->getSourceRange();
1209     return true;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on the {work_group_/sub_group_
1216 //        /_}reserve_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check the reserve size.
1228   if (!Call->getArg(1)->getType()->isIntegerType() &&
1229       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1230     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1231         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1232         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1233     return true;
1234   }
1235 
1236   // Since return type of reserve_read/write_pipe built-in function is
1237   // reserve_id_t, which is not defined in the builtin def file , we used int
1238   // as return type and need to override the return type of these functions.
1239   Call->setType(S.Context.OCLReserveIDTy);
1240 
1241   return false;
1242 }
1243 
1244 // Performs a semantic analysis on {work_group_/sub_group_
1245 //        /_}commit_{read/write}_pipe
1246 // \param S Reference to the semantic analyzer.
1247 // \param Call The call to the builtin function to be analyzed.
1248 // \return True if a semantic error was found, false otherwise.
1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1250   if (checkArgCount(S, Call, 2))
1251     return true;
1252 
1253   if (checkOpenCLPipeArg(S, Call))
1254     return true;
1255 
1256   // Check reserve_id_t.
1257   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1258     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1259         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1260         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 // Performs a semantic analysis on the call to built-in Pipe
1268 //        Query Functions.
1269 // \param S Reference to the semantic analyzer.
1270 // \param Call The call to the builtin function to be analyzed.
1271 // \return True if a semantic error was found, false otherwise.
1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1273   if (checkArgCount(S, Call, 1))
1274     return true;
1275 
1276   if (!Call->getArg(0)->getType()->isPipeType()) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1278         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1279     return true;
1280   }
1281 
1282   return false;
1283 }
1284 
1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1286 // Performs semantic analysis for the to_global/local/private call.
1287 // \param S Reference to the semantic analyzer.
1288 // \param BuiltinID ID of the builtin function.
1289 // \param Call A pointer to the builtin call.
1290 // \return True if a semantic error has been found, false otherwise.
1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1292                                     CallExpr *Call) {
1293   if (checkArgCount(S, Call, 1))
1294     return true;
1295 
1296   auto RT = Call->getArg(0)->getType();
1297   if (!RT->isPointerType() || RT->getPointeeType()
1298       .getAddressSpace() == LangAS::opencl_constant) {
1299     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1300         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1301     return true;
1302   }
1303 
1304   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1305     S.Diag(Call->getArg(0)->getBeginLoc(),
1306            diag::warn_opencl_generic_address_space_arg)
1307         << Call->getDirectCallee()->getNameInfo().getAsString()
1308         << Call->getArg(0)->getSourceRange();
1309   }
1310 
1311   RT = RT->getPointeeType();
1312   auto Qual = RT.getQualifiers();
1313   switch (BuiltinID) {
1314   case Builtin::BIto_global:
1315     Qual.setAddressSpace(LangAS::opencl_global);
1316     break;
1317   case Builtin::BIto_local:
1318     Qual.setAddressSpace(LangAS::opencl_local);
1319     break;
1320   case Builtin::BIto_private:
1321     Qual.setAddressSpace(LangAS::opencl_private);
1322     break;
1323   default:
1324     llvm_unreachable("Invalid builtin function");
1325   }
1326   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1327       RT.getUnqualifiedType(), Qual)));
1328 
1329   return false;
1330 }
1331 
1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1333   if (checkArgCount(S, TheCall, 1))
1334     return ExprError();
1335 
1336   // Compute __builtin_launder's parameter type from the argument.
1337   // The parameter type is:
1338   //  * The type of the argument if it's not an array or function type,
1339   //  Otherwise,
1340   //  * The decayed argument type.
1341   QualType ParamTy = [&]() {
1342     QualType ArgTy = TheCall->getArg(0)->getType();
1343     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1344       return S.Context.getPointerType(Ty->getElementType());
1345     if (ArgTy->isFunctionType()) {
1346       return S.Context.getPointerType(ArgTy);
1347     }
1348     return ArgTy;
1349   }();
1350 
1351   TheCall->setType(ParamTy);
1352 
1353   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1354     if (!ParamTy->isPointerType())
1355       return 0;
1356     if (ParamTy->isFunctionPointerType())
1357       return 1;
1358     if (ParamTy->isVoidPointerType())
1359       return 2;
1360     return llvm::Optional<unsigned>{};
1361   }();
1362   if (DiagSelect.hasValue()) {
1363     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1364         << DiagSelect.getValue() << TheCall->getSourceRange();
1365     return ExprError();
1366   }
1367 
1368   // We either have an incomplete class type, or we have a class template
1369   // whose instantiation has not been forced. Example:
1370   //
1371   //   template <class T> struct Foo { T value; };
1372   //   Foo<int> *p = nullptr;
1373   //   auto *d = __builtin_launder(p);
1374   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1375                             diag::err_incomplete_type))
1376     return ExprError();
1377 
1378   assert(ParamTy->getPointeeType()->isObjectType() &&
1379          "Unhandled non-object pointer case");
1380 
1381   InitializedEntity Entity =
1382       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1383   ExprResult Arg =
1384       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1385   if (Arg.isInvalid())
1386     return ExprError();
1387   TheCall->setArg(0, Arg.get());
1388 
1389   return TheCall;
1390 }
1391 
1392 // Emit an error and return true if the current architecture is not in the list
1393 // of supported architectures.
1394 static bool
1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1396                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1397   llvm::Triple::ArchType CurArch =
1398       S.getASTContext().getTargetInfo().getTriple().getArch();
1399   if (llvm::is_contained(SupportedArchs, CurArch))
1400     return false;
1401   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1402       << TheCall->getSourceRange();
1403   return true;
1404 }
1405 
1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1407                                  SourceLocation CallSiteLoc);
1408 
1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1410                                       CallExpr *TheCall) {
1411   switch (TI.getTriple().getArch()) {
1412   default:
1413     // Some builtins don't require additional checking, so just consider these
1414     // acceptable.
1415     return false;
1416   case llvm::Triple::arm:
1417   case llvm::Triple::armeb:
1418   case llvm::Triple::thumb:
1419   case llvm::Triple::thumbeb:
1420     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::aarch64:
1422   case llvm::Triple::aarch64_32:
1423   case llvm::Triple::aarch64_be:
1424     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::bpfeb:
1426   case llvm::Triple::bpfel:
1427     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1428   case llvm::Triple::hexagon:
1429     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1430   case llvm::Triple::mips:
1431   case llvm::Triple::mipsel:
1432   case llvm::Triple::mips64:
1433   case llvm::Triple::mips64el:
1434     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   case llvm::Triple::systemz:
1436     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1437   case llvm::Triple::x86:
1438   case llvm::Triple::x86_64:
1439     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1440   case llvm::Triple::ppc:
1441   case llvm::Triple::ppcle:
1442   case llvm::Triple::ppc64:
1443   case llvm::Triple::ppc64le:
1444     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1445   case llvm::Triple::amdgcn:
1446     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1447   case llvm::Triple::riscv32:
1448   case llvm::Triple::riscv64:
1449     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1450   }
1451 }
1452 
1453 ExprResult
1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1455                                CallExpr *TheCall) {
1456   ExprResult TheCallResult(TheCall);
1457 
1458   // Find out if any arguments are required to be integer constant expressions.
1459   unsigned ICEArguments = 0;
1460   ASTContext::GetBuiltinTypeError Error;
1461   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1462   if (Error != ASTContext::GE_None)
1463     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1464 
1465   // If any arguments are required to be ICE's, check and diagnose.
1466   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1467     // Skip arguments not required to be ICE's.
1468     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1469 
1470     llvm::APSInt Result;
1471     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1472       return true;
1473     ICEArguments &= ~(1 << ArgNo);
1474   }
1475 
1476   switch (BuiltinID) {
1477   case Builtin::BI__builtin___CFStringMakeConstantString:
1478     assert(TheCall->getNumArgs() == 1 &&
1479            "Wrong # arguments to builtin CFStringMakeConstantString");
1480     if (CheckObjCString(TheCall->getArg(0)))
1481       return ExprError();
1482     break;
1483   case Builtin::BI__builtin_ms_va_start:
1484   case Builtin::BI__builtin_stdarg_start:
1485   case Builtin::BI__builtin_va_start:
1486     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BI__va_start: {
1490     switch (Context.getTargetInfo().getTriple().getArch()) {
1491     case llvm::Triple::aarch64:
1492     case llvm::Triple::arm:
1493     case llvm::Triple::thumb:
1494       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1495         return ExprError();
1496       break;
1497     default:
1498       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1499         return ExprError();
1500       break;
1501     }
1502     break;
1503   }
1504 
1505   // The acquire, release, and no fence variants are ARM and AArch64 only.
1506   case Builtin::BI_interlockedbittestandset_acq:
1507   case Builtin::BI_interlockedbittestandset_rel:
1508   case Builtin::BI_interlockedbittestandset_nf:
1509   case Builtin::BI_interlockedbittestandreset_acq:
1510   case Builtin::BI_interlockedbittestandreset_rel:
1511   case Builtin::BI_interlockedbittestandreset_nf:
1512     if (CheckBuiltinTargetSupport(
1513             *this, BuiltinID, TheCall,
1514             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1519   case Builtin::BI_bittest64:
1520   case Builtin::BI_bittestandcomplement64:
1521   case Builtin::BI_bittestandreset64:
1522   case Builtin::BI_bittestandset64:
1523   case Builtin::BI_interlockedbittestandreset64:
1524   case Builtin::BI_interlockedbittestandset64:
1525     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1526                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1527                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1528       return ExprError();
1529     break;
1530 
1531   case Builtin::BI__builtin_isgreater:
1532   case Builtin::BI__builtin_isgreaterequal:
1533   case Builtin::BI__builtin_isless:
1534   case Builtin::BI__builtin_islessequal:
1535   case Builtin::BI__builtin_islessgreater:
1536   case Builtin::BI__builtin_isunordered:
1537     if (SemaBuiltinUnorderedCompare(TheCall))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_fpclassify:
1541     if (SemaBuiltinFPClassification(TheCall, 6))
1542       return ExprError();
1543     break;
1544   case Builtin::BI__builtin_isfinite:
1545   case Builtin::BI__builtin_isinf:
1546   case Builtin::BI__builtin_isinf_sign:
1547   case Builtin::BI__builtin_isnan:
1548   case Builtin::BI__builtin_isnormal:
1549   case Builtin::BI__builtin_signbit:
1550   case Builtin::BI__builtin_signbitf:
1551   case Builtin::BI__builtin_signbitl:
1552     if (SemaBuiltinFPClassification(TheCall, 1))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_shufflevector:
1556     return SemaBuiltinShuffleVector(TheCall);
1557     // TheCall will be freed by the smart pointer here, but that's fine, since
1558     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1559   case Builtin::BI__builtin_prefetch:
1560     if (SemaBuiltinPrefetch(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_alloca_with_align:
1564     if (SemaBuiltinAllocaWithAlign(TheCall))
1565       return ExprError();
1566     LLVM_FALLTHROUGH;
1567   case Builtin::BI__builtin_alloca:
1568     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1569         << TheCall->getDirectCallee();
1570     break;
1571   case Builtin::BI__arithmetic_fence:
1572     if (SemaBuiltinArithmeticFence(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__assume:
1576   case Builtin::BI__builtin_assume:
1577     if (SemaBuiltinAssume(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_assume_aligned:
1581     if (SemaBuiltinAssumeAligned(TheCall))
1582       return ExprError();
1583     break;
1584   case Builtin::BI__builtin_dynamic_object_size:
1585   case Builtin::BI__builtin_object_size:
1586     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1587       return ExprError();
1588     break;
1589   case Builtin::BI__builtin_longjmp:
1590     if (SemaBuiltinLongjmp(TheCall))
1591       return ExprError();
1592     break;
1593   case Builtin::BI__builtin_setjmp:
1594     if (SemaBuiltinSetjmp(TheCall))
1595       return ExprError();
1596     break;
1597   case Builtin::BI__builtin_classify_type:
1598     if (checkArgCount(*this, TheCall, 1)) return true;
1599     TheCall->setType(Context.IntTy);
1600     break;
1601   case Builtin::BI__builtin_complex:
1602     if (SemaBuiltinComplex(TheCall))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_constant_p: {
1606     if (checkArgCount(*this, TheCall, 1)) return true;
1607     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1608     if (Arg.isInvalid()) return true;
1609     TheCall->setArg(0, Arg.get());
1610     TheCall->setType(Context.IntTy);
1611     break;
1612   }
1613   case Builtin::BI__builtin_launder:
1614     return SemaBuiltinLaunder(*this, TheCall);
1615   case Builtin::BI__sync_fetch_and_add:
1616   case Builtin::BI__sync_fetch_and_add_1:
1617   case Builtin::BI__sync_fetch_and_add_2:
1618   case Builtin::BI__sync_fetch_and_add_4:
1619   case Builtin::BI__sync_fetch_and_add_8:
1620   case Builtin::BI__sync_fetch_and_add_16:
1621   case Builtin::BI__sync_fetch_and_sub:
1622   case Builtin::BI__sync_fetch_and_sub_1:
1623   case Builtin::BI__sync_fetch_and_sub_2:
1624   case Builtin::BI__sync_fetch_and_sub_4:
1625   case Builtin::BI__sync_fetch_and_sub_8:
1626   case Builtin::BI__sync_fetch_and_sub_16:
1627   case Builtin::BI__sync_fetch_and_or:
1628   case Builtin::BI__sync_fetch_and_or_1:
1629   case Builtin::BI__sync_fetch_and_or_2:
1630   case Builtin::BI__sync_fetch_and_or_4:
1631   case Builtin::BI__sync_fetch_and_or_8:
1632   case Builtin::BI__sync_fetch_and_or_16:
1633   case Builtin::BI__sync_fetch_and_and:
1634   case Builtin::BI__sync_fetch_and_and_1:
1635   case Builtin::BI__sync_fetch_and_and_2:
1636   case Builtin::BI__sync_fetch_and_and_4:
1637   case Builtin::BI__sync_fetch_and_and_8:
1638   case Builtin::BI__sync_fetch_and_and_16:
1639   case Builtin::BI__sync_fetch_and_xor:
1640   case Builtin::BI__sync_fetch_and_xor_1:
1641   case Builtin::BI__sync_fetch_and_xor_2:
1642   case Builtin::BI__sync_fetch_and_xor_4:
1643   case Builtin::BI__sync_fetch_and_xor_8:
1644   case Builtin::BI__sync_fetch_and_xor_16:
1645   case Builtin::BI__sync_fetch_and_nand:
1646   case Builtin::BI__sync_fetch_and_nand_1:
1647   case Builtin::BI__sync_fetch_and_nand_2:
1648   case Builtin::BI__sync_fetch_and_nand_4:
1649   case Builtin::BI__sync_fetch_and_nand_8:
1650   case Builtin::BI__sync_fetch_and_nand_16:
1651   case Builtin::BI__sync_add_and_fetch:
1652   case Builtin::BI__sync_add_and_fetch_1:
1653   case Builtin::BI__sync_add_and_fetch_2:
1654   case Builtin::BI__sync_add_and_fetch_4:
1655   case Builtin::BI__sync_add_and_fetch_8:
1656   case Builtin::BI__sync_add_and_fetch_16:
1657   case Builtin::BI__sync_sub_and_fetch:
1658   case Builtin::BI__sync_sub_and_fetch_1:
1659   case Builtin::BI__sync_sub_and_fetch_2:
1660   case Builtin::BI__sync_sub_and_fetch_4:
1661   case Builtin::BI__sync_sub_and_fetch_8:
1662   case Builtin::BI__sync_sub_and_fetch_16:
1663   case Builtin::BI__sync_and_and_fetch:
1664   case Builtin::BI__sync_and_and_fetch_1:
1665   case Builtin::BI__sync_and_and_fetch_2:
1666   case Builtin::BI__sync_and_and_fetch_4:
1667   case Builtin::BI__sync_and_and_fetch_8:
1668   case Builtin::BI__sync_and_and_fetch_16:
1669   case Builtin::BI__sync_or_and_fetch:
1670   case Builtin::BI__sync_or_and_fetch_1:
1671   case Builtin::BI__sync_or_and_fetch_2:
1672   case Builtin::BI__sync_or_and_fetch_4:
1673   case Builtin::BI__sync_or_and_fetch_8:
1674   case Builtin::BI__sync_or_and_fetch_16:
1675   case Builtin::BI__sync_xor_and_fetch:
1676   case Builtin::BI__sync_xor_and_fetch_1:
1677   case Builtin::BI__sync_xor_and_fetch_2:
1678   case Builtin::BI__sync_xor_and_fetch_4:
1679   case Builtin::BI__sync_xor_and_fetch_8:
1680   case Builtin::BI__sync_xor_and_fetch_16:
1681   case Builtin::BI__sync_nand_and_fetch:
1682   case Builtin::BI__sync_nand_and_fetch_1:
1683   case Builtin::BI__sync_nand_and_fetch_2:
1684   case Builtin::BI__sync_nand_and_fetch_4:
1685   case Builtin::BI__sync_nand_and_fetch_8:
1686   case Builtin::BI__sync_nand_and_fetch_16:
1687   case Builtin::BI__sync_val_compare_and_swap:
1688   case Builtin::BI__sync_val_compare_and_swap_1:
1689   case Builtin::BI__sync_val_compare_and_swap_2:
1690   case Builtin::BI__sync_val_compare_and_swap_4:
1691   case Builtin::BI__sync_val_compare_and_swap_8:
1692   case Builtin::BI__sync_val_compare_and_swap_16:
1693   case Builtin::BI__sync_bool_compare_and_swap:
1694   case Builtin::BI__sync_bool_compare_and_swap_1:
1695   case Builtin::BI__sync_bool_compare_and_swap_2:
1696   case Builtin::BI__sync_bool_compare_and_swap_4:
1697   case Builtin::BI__sync_bool_compare_and_swap_8:
1698   case Builtin::BI__sync_bool_compare_and_swap_16:
1699   case Builtin::BI__sync_lock_test_and_set:
1700   case Builtin::BI__sync_lock_test_and_set_1:
1701   case Builtin::BI__sync_lock_test_and_set_2:
1702   case Builtin::BI__sync_lock_test_and_set_4:
1703   case Builtin::BI__sync_lock_test_and_set_8:
1704   case Builtin::BI__sync_lock_test_and_set_16:
1705   case Builtin::BI__sync_lock_release:
1706   case Builtin::BI__sync_lock_release_1:
1707   case Builtin::BI__sync_lock_release_2:
1708   case Builtin::BI__sync_lock_release_4:
1709   case Builtin::BI__sync_lock_release_8:
1710   case Builtin::BI__sync_lock_release_16:
1711   case Builtin::BI__sync_swap:
1712   case Builtin::BI__sync_swap_1:
1713   case Builtin::BI__sync_swap_2:
1714   case Builtin::BI__sync_swap_4:
1715   case Builtin::BI__sync_swap_8:
1716   case Builtin::BI__sync_swap_16:
1717     return SemaBuiltinAtomicOverloaded(TheCallResult);
1718   case Builtin::BI__sync_synchronize:
1719     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1720         << TheCall->getCallee()->getSourceRange();
1721     break;
1722   case Builtin::BI__builtin_nontemporal_load:
1723   case Builtin::BI__builtin_nontemporal_store:
1724     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1725   case Builtin::BI__builtin_memcpy_inline: {
1726     clang::Expr *SizeOp = TheCall->getArg(2);
1727     // We warn about copying to or from `nullptr` pointers when `size` is
1728     // greater than 0. When `size` is value dependent we cannot evaluate its
1729     // value so we bail out.
1730     if (SizeOp->isValueDependent())
1731       break;
1732     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1733       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1734       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1735     }
1736     break;
1737   }
1738 #define BUILTIN(ID, TYPE, ATTRS)
1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1740   case Builtin::BI##ID: \
1741     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1742 #include "clang/Basic/Builtins.def"
1743   case Builtin::BI__annotation:
1744     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_annotation:
1748     if (SemaBuiltinAnnotation(*this, TheCall))
1749       return ExprError();
1750     break;
1751   case Builtin::BI__builtin_addressof:
1752     if (SemaBuiltinAddressof(*this, TheCall))
1753       return ExprError();
1754     break;
1755   case Builtin::BI__builtin_is_aligned:
1756   case Builtin::BI__builtin_align_up:
1757   case Builtin::BI__builtin_align_down:
1758     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__builtin_add_overflow:
1762   case Builtin::BI__builtin_sub_overflow:
1763   case Builtin::BI__builtin_mul_overflow:
1764     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1765       return ExprError();
1766     break;
1767   case Builtin::BI__builtin_operator_new:
1768   case Builtin::BI__builtin_operator_delete: {
1769     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1770     ExprResult Res =
1771         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1772     if (Res.isInvalid())
1773       CorrectDelayedTyposInExpr(TheCallResult.get());
1774     return Res;
1775   }
1776   case Builtin::BI__builtin_dump_struct: {
1777     // We first want to ensure we are called with 2 arguments
1778     if (checkArgCount(*this, TheCall, 2))
1779       return ExprError();
1780     // Ensure that the first argument is of type 'struct XX *'
1781     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1782     const QualType PtrArgType = PtrArg->getType();
1783     if (!PtrArgType->isPointerType() ||
1784         !PtrArgType->getPointeeType()->isRecordType()) {
1785       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1787           << "structure pointer";
1788       return ExprError();
1789     }
1790 
1791     // Ensure that the second argument is of type 'FunctionType'
1792     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1793     const QualType FnPtrArgType = FnPtrArg->getType();
1794     if (!FnPtrArgType->isPointerType()) {
1795       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1797           << FnPtrArgType << "'int (*)(const char *, ...)'";
1798       return ExprError();
1799     }
1800 
1801     const auto *FuncType =
1802         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1803 
1804     if (!FuncType) {
1805       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1806           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1807           << FnPtrArgType << "'int (*)(const char *, ...)'";
1808       return ExprError();
1809     }
1810 
1811     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1812       if (!FT->getNumParams()) {
1813         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1814             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1815             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1816         return ExprError();
1817       }
1818       QualType PT = FT->getParamType(0);
1819       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1820           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1821           !PT->getPointeeType().isConstQualified()) {
1822         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1823             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1824             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1825         return ExprError();
1826       }
1827     }
1828 
1829     TheCall->setType(Context.IntTy);
1830     break;
1831   }
1832   case Builtin::BI__builtin_expect_with_probability: {
1833     // We first want to ensure we are called with 3 arguments
1834     if (checkArgCount(*this, TheCall, 3))
1835       return ExprError();
1836     // then check probability is constant float in range [0.0, 1.0]
1837     const Expr *ProbArg = TheCall->getArg(2);
1838     SmallVector<PartialDiagnosticAt, 8> Notes;
1839     Expr::EvalResult Eval;
1840     Eval.Diag = &Notes;
1841     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1842         !Eval.Val.isFloat()) {
1843       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1844           << ProbArg->getSourceRange();
1845       for (const PartialDiagnosticAt &PDiag : Notes)
1846         Diag(PDiag.first, PDiag.second);
1847       return ExprError();
1848     }
1849     llvm::APFloat Probability = Eval.Val.getFloat();
1850     bool LoseInfo = false;
1851     Probability.convert(llvm::APFloat::IEEEdouble(),
1852                         llvm::RoundingMode::Dynamic, &LoseInfo);
1853     if (!(Probability >= llvm::APFloat(0.0) &&
1854           Probability <= llvm::APFloat(1.0))) {
1855       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1856           << ProbArg->getSourceRange();
1857       return ExprError();
1858     }
1859     break;
1860   }
1861   case Builtin::BI__builtin_preserve_access_index:
1862     if (SemaBuiltinPreserveAI(*this, TheCall))
1863       return ExprError();
1864     break;
1865   case Builtin::BI__builtin_call_with_static_chain:
1866     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__exception_code:
1870   case Builtin::BI_exception_code:
1871     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1872                                  diag::err_seh___except_block))
1873       return ExprError();
1874     break;
1875   case Builtin::BI__exception_info:
1876   case Builtin::BI_exception_info:
1877     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1878                                  diag::err_seh___except_filter))
1879       return ExprError();
1880     break;
1881   case Builtin::BI__GetExceptionInfo:
1882     if (checkArgCount(*this, TheCall, 1))
1883       return ExprError();
1884 
1885     if (CheckCXXThrowOperand(
1886             TheCall->getBeginLoc(),
1887             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1888             TheCall))
1889       return ExprError();
1890 
1891     TheCall->setType(Context.VoidPtrTy);
1892     break;
1893   // OpenCL v2.0, s6.13.16 - Pipe functions
1894   case Builtin::BIread_pipe:
1895   case Builtin::BIwrite_pipe:
1896     // Since those two functions are declared with var args, we need a semantic
1897     // check for the argument.
1898     if (SemaBuiltinRWPipe(*this, TheCall))
1899       return ExprError();
1900     break;
1901   case Builtin::BIreserve_read_pipe:
1902   case Builtin::BIreserve_write_pipe:
1903   case Builtin::BIwork_group_reserve_read_pipe:
1904   case Builtin::BIwork_group_reserve_write_pipe:
1905     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIsub_group_reserve_read_pipe:
1909   case Builtin::BIsub_group_reserve_write_pipe:
1910     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1911         SemaBuiltinReserveRWPipe(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIcommit_read_pipe:
1915   case Builtin::BIcommit_write_pipe:
1916   case Builtin::BIwork_group_commit_read_pipe:
1917   case Builtin::BIwork_group_commit_write_pipe:
1918     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1919       return ExprError();
1920     break;
1921   case Builtin::BIsub_group_commit_read_pipe:
1922   case Builtin::BIsub_group_commit_write_pipe:
1923     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1924         SemaBuiltinCommitRWPipe(*this, TheCall))
1925       return ExprError();
1926     break;
1927   case Builtin::BIget_pipe_num_packets:
1928   case Builtin::BIget_pipe_max_packets:
1929     if (SemaBuiltinPipePackets(*this, TheCall))
1930       return ExprError();
1931     break;
1932   case Builtin::BIto_global:
1933   case Builtin::BIto_local:
1934   case Builtin::BIto_private:
1935     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1936       return ExprError();
1937     break;
1938   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1939   case Builtin::BIenqueue_kernel:
1940     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1941       return ExprError();
1942     break;
1943   case Builtin::BIget_kernel_work_group_size:
1944   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1945     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1946       return ExprError();
1947     break;
1948   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1949   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1950     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1951       return ExprError();
1952     break;
1953   case Builtin::BI__builtin_os_log_format:
1954     Cleanup.setExprNeedsCleanups(true);
1955     LLVM_FALLTHROUGH;
1956   case Builtin::BI__builtin_os_log_format_buffer_size:
1957     if (SemaBuiltinOSLogFormat(TheCall))
1958       return ExprError();
1959     break;
1960   case Builtin::BI__builtin_frame_address:
1961   case Builtin::BI__builtin_return_address: {
1962     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1963       return ExprError();
1964 
1965     // -Wframe-address warning if non-zero passed to builtin
1966     // return/frame address.
1967     Expr::EvalResult Result;
1968     if (!TheCall->getArg(0)->isValueDependent() &&
1969         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1970         Result.Val.getInt() != 0)
1971       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1972           << ((BuiltinID == Builtin::BI__builtin_return_address)
1973                   ? "__builtin_return_address"
1974                   : "__builtin_frame_address")
1975           << TheCall->getSourceRange();
1976     break;
1977   }
1978 
1979   case Builtin::BI__builtin_matrix_transpose:
1980     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1981 
1982   case Builtin::BI__builtin_matrix_column_major_load:
1983     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1984 
1985   case Builtin::BI__builtin_matrix_column_major_store:
1986     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1987 
1988   case Builtin::BI__builtin_get_device_side_mangled_name: {
1989     auto Check = [](CallExpr *TheCall) {
1990       if (TheCall->getNumArgs() != 1)
1991         return false;
1992       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1993       if (!DRE)
1994         return false;
1995       auto *D = DRE->getDecl();
1996       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1997         return false;
1998       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1999              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2000     };
2001     if (!Check(TheCall)) {
2002       Diag(TheCall->getBeginLoc(),
2003            diag::err_hip_invalid_args_builtin_mangled_name);
2004       return ExprError();
2005     }
2006   }
2007   }
2008 
2009   // Since the target specific builtins for each arch overlap, only check those
2010   // of the arch we are compiling for.
2011   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2012     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2013       assert(Context.getAuxTargetInfo() &&
2014              "Aux Target Builtin, but not an aux target?");
2015 
2016       if (CheckTSBuiltinFunctionCall(
2017               *Context.getAuxTargetInfo(),
2018               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2019         return ExprError();
2020     } else {
2021       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2022                                      TheCall))
2023         return ExprError();
2024     }
2025   }
2026 
2027   return TheCallResult;
2028 }
2029 
2030 // Get the valid immediate range for the specified NEON type code.
2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2032   NeonTypeFlags Type(t);
2033   int IsQuad = ForceQuad ? true : Type.isQuad();
2034   switch (Type.getEltType()) {
2035   case NeonTypeFlags::Int8:
2036   case NeonTypeFlags::Poly8:
2037     return shift ? 7 : (8 << IsQuad) - 1;
2038   case NeonTypeFlags::Int16:
2039   case NeonTypeFlags::Poly16:
2040     return shift ? 15 : (4 << IsQuad) - 1;
2041   case NeonTypeFlags::Int32:
2042     return shift ? 31 : (2 << IsQuad) - 1;
2043   case NeonTypeFlags::Int64:
2044   case NeonTypeFlags::Poly64:
2045     return shift ? 63 : (1 << IsQuad) - 1;
2046   case NeonTypeFlags::Poly128:
2047     return shift ? 127 : (1 << IsQuad) - 1;
2048   case NeonTypeFlags::Float16:
2049     assert(!shift && "cannot shift float types!");
2050     return (4 << IsQuad) - 1;
2051   case NeonTypeFlags::Float32:
2052     assert(!shift && "cannot shift float types!");
2053     return (2 << IsQuad) - 1;
2054   case NeonTypeFlags::Float64:
2055     assert(!shift && "cannot shift float types!");
2056     return (1 << IsQuad) - 1;
2057   case NeonTypeFlags::BFloat16:
2058     assert(!shift && "cannot shift float types!");
2059     return (4 << IsQuad) - 1;
2060   }
2061   llvm_unreachable("Invalid NeonTypeFlag!");
2062 }
2063 
2064 /// getNeonEltType - Return the QualType corresponding to the elements of
2065 /// the vector type specified by the NeonTypeFlags.  This is used to check
2066 /// the pointer arguments for Neon load/store intrinsics.
2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2068                                bool IsPolyUnsigned, bool IsInt64Long) {
2069   switch (Flags.getEltType()) {
2070   case NeonTypeFlags::Int8:
2071     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2072   case NeonTypeFlags::Int16:
2073     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2074   case NeonTypeFlags::Int32:
2075     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2076   case NeonTypeFlags::Int64:
2077     if (IsInt64Long)
2078       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2079     else
2080       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2081                                 : Context.LongLongTy;
2082   case NeonTypeFlags::Poly8:
2083     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2084   case NeonTypeFlags::Poly16:
2085     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2086   case NeonTypeFlags::Poly64:
2087     if (IsInt64Long)
2088       return Context.UnsignedLongTy;
2089     else
2090       return Context.UnsignedLongLongTy;
2091   case NeonTypeFlags::Poly128:
2092     break;
2093   case NeonTypeFlags::Float16:
2094     return Context.HalfTy;
2095   case NeonTypeFlags::Float32:
2096     return Context.FloatTy;
2097   case NeonTypeFlags::Float64:
2098     return Context.DoubleTy;
2099   case NeonTypeFlags::BFloat16:
2100     return Context.BFloat16Ty;
2101   }
2102   llvm_unreachable("Invalid NeonTypeFlag!");
2103 }
2104 
2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2106   // Range check SVE intrinsics that take immediate values.
2107   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2108 
2109   switch (BuiltinID) {
2110   default:
2111     return false;
2112 #define GET_SVE_IMMEDIATE_CHECK
2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2114 #undef GET_SVE_IMMEDIATE_CHECK
2115   }
2116 
2117   // Perform all the immediate checks for this builtin call.
2118   bool HasError = false;
2119   for (auto &I : ImmChecks) {
2120     int ArgNum, CheckTy, ElementSizeInBits;
2121     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2122 
2123     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2124 
2125     // Function that checks whether the operand (ArgNum) is an immediate
2126     // that is one of the predefined values.
2127     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2128                                    int ErrDiag) -> bool {
2129       // We can't check the value of a dependent argument.
2130       Expr *Arg = TheCall->getArg(ArgNum);
2131       if (Arg->isTypeDependent() || Arg->isValueDependent())
2132         return false;
2133 
2134       // Check constant-ness first.
2135       llvm::APSInt Imm;
2136       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2137         return true;
2138 
2139       if (!CheckImm(Imm.getSExtValue()))
2140         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2141       return false;
2142     };
2143 
2144     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2145     case SVETypeFlags::ImmCheck0_31:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2147         HasError = true;
2148       break;
2149     case SVETypeFlags::ImmCheck0_13:
2150       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2151         HasError = true;
2152       break;
2153     case SVETypeFlags::ImmCheck1_16:
2154       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheck0_7:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckExtract:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       (2048 / ElementSizeInBits) - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckShiftRight:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2168         HasError = true;
2169       break;
2170     case SVETypeFlags::ImmCheckShiftRightNarrow:
2171       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2172                                       ElementSizeInBits / 2))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheckShiftLeft:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2177                                       ElementSizeInBits - 1))
2178         HasError = true;
2179       break;
2180     case SVETypeFlags::ImmCheckLaneIndex:
2181       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2182                                       (128 / (1 * ElementSizeInBits)) - 1))
2183         HasError = true;
2184       break;
2185     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2186       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2187                                       (128 / (2 * ElementSizeInBits)) - 1))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheckLaneIndexDot:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2192                                       (128 / (4 * ElementSizeInBits)) - 1))
2193         HasError = true;
2194       break;
2195     case SVETypeFlags::ImmCheckComplexRot90_270:
2196       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2197                               diag::err_rotation_argument_to_cadd))
2198         HasError = true;
2199       break;
2200     case SVETypeFlags::ImmCheckComplexRotAll90:
2201       if (CheckImmediateInSet(
2202               [](int64_t V) {
2203                 return V == 0 || V == 90 || V == 180 || V == 270;
2204               },
2205               diag::err_rotation_argument_to_cmla))
2206         HasError = true;
2207       break;
2208     case SVETypeFlags::ImmCheck0_1:
2209       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2210         HasError = true;
2211       break;
2212     case SVETypeFlags::ImmCheck0_2:
2213       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2214         HasError = true;
2215       break;
2216     case SVETypeFlags::ImmCheck0_3:
2217       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2218         HasError = true;
2219       break;
2220     }
2221   }
2222 
2223   return HasError;
2224 }
2225 
2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2227                                         unsigned BuiltinID, CallExpr *TheCall) {
2228   llvm::APSInt Result;
2229   uint64_t mask = 0;
2230   unsigned TV = 0;
2231   int PtrArgNum = -1;
2232   bool HasConstPtr = false;
2233   switch (BuiltinID) {
2234 #define GET_NEON_OVERLOAD_CHECK
2235 #include "clang/Basic/arm_neon.inc"
2236 #include "clang/Basic/arm_fp16.inc"
2237 #undef GET_NEON_OVERLOAD_CHECK
2238   }
2239 
2240   // For NEON intrinsics which are overloaded on vector element type, validate
2241   // the immediate which specifies which variant to emit.
2242   unsigned ImmArg = TheCall->getNumArgs()-1;
2243   if (mask) {
2244     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2245       return true;
2246 
2247     TV = Result.getLimitedValue(64);
2248     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2249       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2250              << TheCall->getArg(ImmArg)->getSourceRange();
2251   }
2252 
2253   if (PtrArgNum >= 0) {
2254     // Check that pointer arguments have the specified type.
2255     Expr *Arg = TheCall->getArg(PtrArgNum);
2256     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2257       Arg = ICE->getSubExpr();
2258     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2259     QualType RHSTy = RHS.get()->getType();
2260 
2261     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2262     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2263                           Arch == llvm::Triple::aarch64_32 ||
2264                           Arch == llvm::Triple::aarch64_be;
2265     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2266     QualType EltTy =
2267         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2268     if (HasConstPtr)
2269       EltTy = EltTy.withConst();
2270     QualType LHSTy = Context.getPointerType(EltTy);
2271     AssignConvertType ConvTy;
2272     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2273     if (RHS.isInvalid())
2274       return true;
2275     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2276                                  RHS.get(), AA_Assigning))
2277       return true;
2278   }
2279 
2280   // For NEON intrinsics which take an immediate value as part of the
2281   // instruction, range check them here.
2282   unsigned i = 0, l = 0, u = 0;
2283   switch (BuiltinID) {
2284   default:
2285     return false;
2286   #define GET_NEON_IMMEDIATE_CHECK
2287   #include "clang/Basic/arm_neon.inc"
2288   #include "clang/Basic/arm_fp16.inc"
2289   #undef GET_NEON_IMMEDIATE_CHECK
2290   }
2291 
2292   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2293 }
2294 
2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2296   switch (BuiltinID) {
2297   default:
2298     return false;
2299   #include "clang/Basic/arm_mve_builtin_sema.inc"
2300   }
2301 }
2302 
2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2304                                        CallExpr *TheCall) {
2305   bool Err = false;
2306   switch (BuiltinID) {
2307   default:
2308     return false;
2309 #include "clang/Basic/arm_cde_builtin_sema.inc"
2310   }
2311 
2312   if (Err)
2313     return true;
2314 
2315   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2316 }
2317 
2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2319                                         const Expr *CoprocArg, bool WantCDE) {
2320   if (isConstantEvaluated())
2321     return false;
2322 
2323   // We can't check the value of a dependent argument.
2324   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2325     return false;
2326 
2327   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2328   int64_t CoprocNo = CoprocNoAP.getExtValue();
2329   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2330 
2331   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2332   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2333 
2334   if (IsCDECoproc != WantCDE)
2335     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2336            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2337 
2338   return false;
2339 }
2340 
2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2342                                         unsigned MaxWidth) {
2343   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2344           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2345           BuiltinID == ARM::BI__builtin_arm_strex ||
2346           BuiltinID == ARM::BI__builtin_arm_stlex ||
2347           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2348           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2349           BuiltinID == AArch64::BI__builtin_arm_strex ||
2350           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2351          "unexpected ARM builtin");
2352   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2353                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2354                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2355                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2356 
2357   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2358 
2359   // Ensure that we have the proper number of arguments.
2360   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2361     return true;
2362 
2363   // Inspect the pointer argument of the atomic builtin.  This should always be
2364   // a pointer type, whose element is an integral scalar or pointer type.
2365   // Because it is a pointer type, we don't have to worry about any implicit
2366   // casts here.
2367   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2368   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2369   if (PointerArgRes.isInvalid())
2370     return true;
2371   PointerArg = PointerArgRes.get();
2372 
2373   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2374   if (!pointerType) {
2375     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2376         << PointerArg->getType() << PointerArg->getSourceRange();
2377     return true;
2378   }
2379 
2380   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2381   // task is to insert the appropriate casts into the AST. First work out just
2382   // what the appropriate type is.
2383   QualType ValType = pointerType->getPointeeType();
2384   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2385   if (IsLdrex)
2386     AddrType.addConst();
2387 
2388   // Issue a warning if the cast is dodgy.
2389   CastKind CastNeeded = CK_NoOp;
2390   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2391     CastNeeded = CK_BitCast;
2392     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2393         << PointerArg->getType() << Context.getPointerType(AddrType)
2394         << AA_Passing << PointerArg->getSourceRange();
2395   }
2396 
2397   // Finally, do the cast and replace the argument with the corrected version.
2398   AddrType = Context.getPointerType(AddrType);
2399   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2400   if (PointerArgRes.isInvalid())
2401     return true;
2402   PointerArg = PointerArgRes.get();
2403 
2404   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2405 
2406   // In general, we allow ints, floats and pointers to be loaded and stored.
2407   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2408       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2409     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2410         << PointerArg->getType() << PointerArg->getSourceRange();
2411     return true;
2412   }
2413 
2414   // But ARM doesn't have instructions to deal with 128-bit versions.
2415   if (Context.getTypeSize(ValType) > MaxWidth) {
2416     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2417     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2418         << PointerArg->getType() << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   switch (ValType.getObjCLifetime()) {
2423   case Qualifiers::OCL_None:
2424   case Qualifiers::OCL_ExplicitNone:
2425     // okay
2426     break;
2427 
2428   case Qualifiers::OCL_Weak:
2429   case Qualifiers::OCL_Strong:
2430   case Qualifiers::OCL_Autoreleasing:
2431     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2432         << ValType << PointerArg->getSourceRange();
2433     return true;
2434   }
2435 
2436   if (IsLdrex) {
2437     TheCall->setType(ValType);
2438     return false;
2439   }
2440 
2441   // Initialize the argument to be stored.
2442   ExprResult ValArg = TheCall->getArg(0);
2443   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2444       Context, ValType, /*consume*/ false);
2445   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2446   if (ValArg.isInvalid())
2447     return true;
2448   TheCall->setArg(0, ValArg.get());
2449 
2450   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2451   // but the custom checker bypasses all default analysis.
2452   TheCall->setType(Context.IntTy);
2453   return false;
2454 }
2455 
2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2457                                        CallExpr *TheCall) {
2458   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2459       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2460       BuiltinID == ARM::BI__builtin_arm_strex ||
2461       BuiltinID == ARM::BI__builtin_arm_stlex) {
2462     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2463   }
2464 
2465   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2466     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2467       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2468   }
2469 
2470   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2471       BuiltinID == ARM::BI__builtin_arm_wsr64)
2472     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2473 
2474   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2475       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2476       BuiltinID == ARM::BI__builtin_arm_wsr ||
2477       BuiltinID == ARM::BI__builtin_arm_wsrp)
2478     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2479 
2480   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2481     return true;
2482   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2483     return true;
2484   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2485     return true;
2486 
2487   // For intrinsics which take an immediate value as part of the instruction,
2488   // range check them here.
2489   // FIXME: VFP Intrinsics should error if VFP not present.
2490   switch (BuiltinID) {
2491   default: return false;
2492   case ARM::BI__builtin_arm_ssat:
2493     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2494   case ARM::BI__builtin_arm_usat:
2495     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2496   case ARM::BI__builtin_arm_ssat16:
2497     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2498   case ARM::BI__builtin_arm_usat16:
2499     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2500   case ARM::BI__builtin_arm_vcvtr_f:
2501   case ARM::BI__builtin_arm_vcvtr_d:
2502     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2503   case ARM::BI__builtin_arm_dmb:
2504   case ARM::BI__builtin_arm_dsb:
2505   case ARM::BI__builtin_arm_isb:
2506   case ARM::BI__builtin_arm_dbg:
2507     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2508   case ARM::BI__builtin_arm_cdp:
2509   case ARM::BI__builtin_arm_cdp2:
2510   case ARM::BI__builtin_arm_mcr:
2511   case ARM::BI__builtin_arm_mcr2:
2512   case ARM::BI__builtin_arm_mrc:
2513   case ARM::BI__builtin_arm_mrc2:
2514   case ARM::BI__builtin_arm_mcrr:
2515   case ARM::BI__builtin_arm_mcrr2:
2516   case ARM::BI__builtin_arm_mrrc:
2517   case ARM::BI__builtin_arm_mrrc2:
2518   case ARM::BI__builtin_arm_ldc:
2519   case ARM::BI__builtin_arm_ldcl:
2520   case ARM::BI__builtin_arm_ldc2:
2521   case ARM::BI__builtin_arm_ldc2l:
2522   case ARM::BI__builtin_arm_stc:
2523   case ARM::BI__builtin_arm_stcl:
2524   case ARM::BI__builtin_arm_stc2:
2525   case ARM::BI__builtin_arm_stc2l:
2526     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2527            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2528                                         /*WantCDE*/ false);
2529   }
2530 }
2531 
2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2533                                            unsigned BuiltinID,
2534                                            CallExpr *TheCall) {
2535   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2536       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2537       BuiltinID == AArch64::BI__builtin_arm_strex ||
2538       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2539     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2540   }
2541 
2542   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2543     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2544       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2545       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2546       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2550       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2551     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2552 
2553   // Memory Tagging Extensions (MTE) Intrinsics
2554   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2555       BuiltinID == AArch64::BI__builtin_arm_addg ||
2556       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2557       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2558       BuiltinID == AArch64::BI__builtin_arm_stg ||
2559       BuiltinID == AArch64::BI__builtin_arm_subp) {
2560     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2561   }
2562 
2563   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2564       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2565       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2566       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2567     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2568 
2569   // Only check the valid encoding range. Any constant in this range would be
2570   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2571   // an exception for incorrect registers. This matches MSVC behavior.
2572   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2573       BuiltinID == AArch64::BI_WriteStatusReg)
2574     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2575 
2576   if (BuiltinID == AArch64::BI__getReg)
2577     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2578 
2579   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2580     return true;
2581 
2582   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2583     return true;
2584 
2585   // For intrinsics which take an immediate value as part of the instruction,
2586   // range check them here.
2587   unsigned i = 0, l = 0, u = 0;
2588   switch (BuiltinID) {
2589   default: return false;
2590   case AArch64::BI__builtin_arm_dmb:
2591   case AArch64::BI__builtin_arm_dsb:
2592   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2593   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2594   }
2595 
2596   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2597 }
2598 
2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2600   if (Arg->getType()->getAsPlaceholderType())
2601     return false;
2602 
2603   // The first argument needs to be a record field access.
2604   // If it is an array element access, we delay decision
2605   // to BPF backend to check whether the access is a
2606   // field access or not.
2607   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2608           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2609           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2610 }
2611 
2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2613                             QualType VectorTy, QualType EltTy) {
2614   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2615   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2616     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2617         << Call->getSourceRange() << VectorEltTy << EltTy;
2618     return false;
2619   }
2620   return true;
2621 }
2622 
2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2624   QualType ArgType = Arg->getType();
2625   if (ArgType->getAsPlaceholderType())
2626     return false;
2627 
2628   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2629   // format:
2630   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2631   //   2. <type> var;
2632   //      __builtin_preserve_type_info(var, flag);
2633   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2634       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2635     return false;
2636 
2637   // Typedef type.
2638   if (ArgType->getAs<TypedefType>())
2639     return true;
2640 
2641   // Record type or Enum type.
2642   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2643   if (const auto *RT = Ty->getAs<RecordType>()) {
2644     if (!RT->getDecl()->getDeclName().isEmpty())
2645       return true;
2646   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2647     if (!ET->getDecl()->getDeclName().isEmpty())
2648       return true;
2649   }
2650 
2651   return false;
2652 }
2653 
2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2655   QualType ArgType = Arg->getType();
2656   if (ArgType->getAsPlaceholderType())
2657     return false;
2658 
2659   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2660   // format:
2661   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2662   //                                 flag);
2663   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2664   if (!UO)
2665     return false;
2666 
2667   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2668   if (!CE)
2669     return false;
2670   if (CE->getCastKind() != CK_IntegralToPointer &&
2671       CE->getCastKind() != CK_NullToPointer)
2672     return false;
2673 
2674   // The integer must be from an EnumConstantDecl.
2675   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2676   if (!DR)
2677     return false;
2678 
2679   const EnumConstantDecl *Enumerator =
2680       dyn_cast<EnumConstantDecl>(DR->getDecl());
2681   if (!Enumerator)
2682     return false;
2683 
2684   // The type must be EnumType.
2685   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2686   const auto *ET = Ty->getAs<EnumType>();
2687   if (!ET)
2688     return false;
2689 
2690   // The enum value must be supported.
2691   for (auto *EDI : ET->getDecl()->enumerators()) {
2692     if (EDI == Enumerator)
2693       return true;
2694   }
2695 
2696   return false;
2697 }
2698 
2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2700                                        CallExpr *TheCall) {
2701   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2702           BuiltinID == BPF::BI__builtin_btf_type_id ||
2703           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2704           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2705          "unexpected BPF builtin");
2706 
2707   if (checkArgCount(*this, TheCall, 2))
2708     return true;
2709 
2710   // The second argument needs to be a constant int
2711   Expr *Arg = TheCall->getArg(1);
2712   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2713   diag::kind kind;
2714   if (!Value) {
2715     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2716       kind = diag::err_preserve_field_info_not_const;
2717     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2718       kind = diag::err_btf_type_id_not_const;
2719     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2720       kind = diag::err_preserve_type_info_not_const;
2721     else
2722       kind = diag::err_preserve_enum_value_not_const;
2723     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2724     return true;
2725   }
2726 
2727   // The first argument
2728   Arg = TheCall->getArg(0);
2729   bool InvalidArg = false;
2730   bool ReturnUnsignedInt = true;
2731   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2732     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2733       InvalidArg = true;
2734       kind = diag::err_preserve_field_info_not_field;
2735     }
2736   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2737     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2738       InvalidArg = true;
2739       kind = diag::err_preserve_type_info_invalid;
2740     }
2741   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2742     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2743       InvalidArg = true;
2744       kind = diag::err_preserve_enum_value_invalid;
2745     }
2746     ReturnUnsignedInt = false;
2747   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2748     ReturnUnsignedInt = false;
2749   }
2750 
2751   if (InvalidArg) {
2752     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2753     return true;
2754   }
2755 
2756   if (ReturnUnsignedInt)
2757     TheCall->setType(Context.UnsignedIntTy);
2758   else
2759     TheCall->setType(Context.UnsignedLongTy);
2760   return false;
2761 }
2762 
2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2764   struct ArgInfo {
2765     uint8_t OpNum;
2766     bool IsSigned;
2767     uint8_t BitWidth;
2768     uint8_t Align;
2769   };
2770   struct BuiltinInfo {
2771     unsigned BuiltinID;
2772     ArgInfo Infos[2];
2773   };
2774 
2775   static BuiltinInfo Infos[] = {
2776     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2777     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2778     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2780     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2782     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2783     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2785     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2786     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2787 
2788     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2791     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2792     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2793     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2799 
2800     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2852                                                       {{ 1, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2860                                                       {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2867                                                        { 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2869                                                        { 2, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2871                                                        { 3, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2873                                                        { 3, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2890                                                       {{ 2, false, 4,  0 },
2891                                                        { 3, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2893                                                       {{ 2, false, 4,  0 },
2894                                                        { 3, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2896                                                       {{ 2, false, 4,  0 },
2897                                                        { 3, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2899                                                       {{ 2, false, 4,  0 },
2900                                                        { 3, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2912                                                        { 2, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2914                                                        { 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2924                                                       {{ 1, false, 4,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2927                                                       {{ 1, false, 4,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2948                                                       {{ 3, false, 1,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2953                                                       {{ 3, false, 1,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2958                                                       {{ 3, false, 1,  0 }} },
2959   };
2960 
2961   // Use a dynamically initialized static to sort the table exactly once on
2962   // first run.
2963   static const bool SortOnce =
2964       (llvm::sort(Infos,
2965                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2966                    return LHS.BuiltinID < RHS.BuiltinID;
2967                  }),
2968        true);
2969   (void)SortOnce;
2970 
2971   const BuiltinInfo *F = llvm::partition_point(
2972       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2973   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2974     return false;
2975 
2976   bool Error = false;
2977 
2978   for (const ArgInfo &A : F->Infos) {
2979     // Ignore empty ArgInfo elements.
2980     if (A.BitWidth == 0)
2981       continue;
2982 
2983     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2984     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2985     if (!A.Align) {
2986       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2987     } else {
2988       unsigned M = 1 << A.Align;
2989       Min *= M;
2990       Max *= M;
2991       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2992                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2993     }
2994   }
2995   return Error;
2996 }
2997 
2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2999                                            CallExpr *TheCall) {
3000   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3001 }
3002 
3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3004                                         unsigned BuiltinID, CallExpr *TheCall) {
3005   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3006          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3007 }
3008 
3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3010                                CallExpr *TheCall) {
3011 
3012   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3013       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3014     if (!TI.hasFeature("dsp"))
3015       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3016   }
3017 
3018   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3019       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3020     if (!TI.hasFeature("dspr2"))
3021       return Diag(TheCall->getBeginLoc(),
3022                   diag::err_mips_builtin_requires_dspr2);
3023   }
3024 
3025   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3026       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3027     if (!TI.hasFeature("msa"))
3028       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3029   }
3030 
3031   return false;
3032 }
3033 
3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3036 // ordering for DSP is unspecified. MSA is ordered by the data format used
3037 // by the underlying instruction i.e., df/m, df/n and then by size.
3038 //
3039 // FIXME: The size tests here should instead be tablegen'd along with the
3040 //        definitions from include/clang/Basic/BuiltinsMips.def.
3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3042 //        be too.
3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3044   unsigned i = 0, l = 0, u = 0, m = 0;
3045   switch (BuiltinID) {
3046   default: return false;
3047   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3048   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3049   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3050   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3051   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3052   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3053   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3054   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3055   // df/m field.
3056   // These intrinsics take an unsigned 3 bit immediate.
3057   case Mips::BI__builtin_msa_bclri_b:
3058   case Mips::BI__builtin_msa_bnegi_b:
3059   case Mips::BI__builtin_msa_bseti_b:
3060   case Mips::BI__builtin_msa_sat_s_b:
3061   case Mips::BI__builtin_msa_sat_u_b:
3062   case Mips::BI__builtin_msa_slli_b:
3063   case Mips::BI__builtin_msa_srai_b:
3064   case Mips::BI__builtin_msa_srari_b:
3065   case Mips::BI__builtin_msa_srli_b:
3066   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3067   case Mips::BI__builtin_msa_binsli_b:
3068   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3069   // These intrinsics take an unsigned 4 bit immediate.
3070   case Mips::BI__builtin_msa_bclri_h:
3071   case Mips::BI__builtin_msa_bnegi_h:
3072   case Mips::BI__builtin_msa_bseti_h:
3073   case Mips::BI__builtin_msa_sat_s_h:
3074   case Mips::BI__builtin_msa_sat_u_h:
3075   case Mips::BI__builtin_msa_slli_h:
3076   case Mips::BI__builtin_msa_srai_h:
3077   case Mips::BI__builtin_msa_srari_h:
3078   case Mips::BI__builtin_msa_srli_h:
3079   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3080   case Mips::BI__builtin_msa_binsli_h:
3081   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3082   // These intrinsics take an unsigned 5 bit immediate.
3083   // The first block of intrinsics actually have an unsigned 5 bit field,
3084   // not a df/n field.
3085   case Mips::BI__builtin_msa_cfcmsa:
3086   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3087   case Mips::BI__builtin_msa_clei_u_b:
3088   case Mips::BI__builtin_msa_clei_u_h:
3089   case Mips::BI__builtin_msa_clei_u_w:
3090   case Mips::BI__builtin_msa_clei_u_d:
3091   case Mips::BI__builtin_msa_clti_u_b:
3092   case Mips::BI__builtin_msa_clti_u_h:
3093   case Mips::BI__builtin_msa_clti_u_w:
3094   case Mips::BI__builtin_msa_clti_u_d:
3095   case Mips::BI__builtin_msa_maxi_u_b:
3096   case Mips::BI__builtin_msa_maxi_u_h:
3097   case Mips::BI__builtin_msa_maxi_u_w:
3098   case Mips::BI__builtin_msa_maxi_u_d:
3099   case Mips::BI__builtin_msa_mini_u_b:
3100   case Mips::BI__builtin_msa_mini_u_h:
3101   case Mips::BI__builtin_msa_mini_u_w:
3102   case Mips::BI__builtin_msa_mini_u_d:
3103   case Mips::BI__builtin_msa_addvi_b:
3104   case Mips::BI__builtin_msa_addvi_h:
3105   case Mips::BI__builtin_msa_addvi_w:
3106   case Mips::BI__builtin_msa_addvi_d:
3107   case Mips::BI__builtin_msa_bclri_w:
3108   case Mips::BI__builtin_msa_bnegi_w:
3109   case Mips::BI__builtin_msa_bseti_w:
3110   case Mips::BI__builtin_msa_sat_s_w:
3111   case Mips::BI__builtin_msa_sat_u_w:
3112   case Mips::BI__builtin_msa_slli_w:
3113   case Mips::BI__builtin_msa_srai_w:
3114   case Mips::BI__builtin_msa_srari_w:
3115   case Mips::BI__builtin_msa_srli_w:
3116   case Mips::BI__builtin_msa_srlri_w:
3117   case Mips::BI__builtin_msa_subvi_b:
3118   case Mips::BI__builtin_msa_subvi_h:
3119   case Mips::BI__builtin_msa_subvi_w:
3120   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3121   case Mips::BI__builtin_msa_binsli_w:
3122   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3123   // These intrinsics take an unsigned 6 bit immediate.
3124   case Mips::BI__builtin_msa_bclri_d:
3125   case Mips::BI__builtin_msa_bnegi_d:
3126   case Mips::BI__builtin_msa_bseti_d:
3127   case Mips::BI__builtin_msa_sat_s_d:
3128   case Mips::BI__builtin_msa_sat_u_d:
3129   case Mips::BI__builtin_msa_slli_d:
3130   case Mips::BI__builtin_msa_srai_d:
3131   case Mips::BI__builtin_msa_srari_d:
3132   case Mips::BI__builtin_msa_srli_d:
3133   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3134   case Mips::BI__builtin_msa_binsli_d:
3135   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3136   // These intrinsics take a signed 5 bit immediate.
3137   case Mips::BI__builtin_msa_ceqi_b:
3138   case Mips::BI__builtin_msa_ceqi_h:
3139   case Mips::BI__builtin_msa_ceqi_w:
3140   case Mips::BI__builtin_msa_ceqi_d:
3141   case Mips::BI__builtin_msa_clti_s_b:
3142   case Mips::BI__builtin_msa_clti_s_h:
3143   case Mips::BI__builtin_msa_clti_s_w:
3144   case Mips::BI__builtin_msa_clti_s_d:
3145   case Mips::BI__builtin_msa_clei_s_b:
3146   case Mips::BI__builtin_msa_clei_s_h:
3147   case Mips::BI__builtin_msa_clei_s_w:
3148   case Mips::BI__builtin_msa_clei_s_d:
3149   case Mips::BI__builtin_msa_maxi_s_b:
3150   case Mips::BI__builtin_msa_maxi_s_h:
3151   case Mips::BI__builtin_msa_maxi_s_w:
3152   case Mips::BI__builtin_msa_maxi_s_d:
3153   case Mips::BI__builtin_msa_mini_s_b:
3154   case Mips::BI__builtin_msa_mini_s_h:
3155   case Mips::BI__builtin_msa_mini_s_w:
3156   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3157   // These intrinsics take an unsigned 8 bit immediate.
3158   case Mips::BI__builtin_msa_andi_b:
3159   case Mips::BI__builtin_msa_nori_b:
3160   case Mips::BI__builtin_msa_ori_b:
3161   case Mips::BI__builtin_msa_shf_b:
3162   case Mips::BI__builtin_msa_shf_h:
3163   case Mips::BI__builtin_msa_shf_w:
3164   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3165   case Mips::BI__builtin_msa_bseli_b:
3166   case Mips::BI__builtin_msa_bmnzi_b:
3167   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3168   // df/n format
3169   // These intrinsics take an unsigned 4 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_b:
3171   case Mips::BI__builtin_msa_copy_u_b:
3172   case Mips::BI__builtin_msa_insve_b:
3173   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3174   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3175   // These intrinsics take an unsigned 3 bit immediate.
3176   case Mips::BI__builtin_msa_copy_s_h:
3177   case Mips::BI__builtin_msa_copy_u_h:
3178   case Mips::BI__builtin_msa_insve_h:
3179   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3180   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3181   // These intrinsics take an unsigned 2 bit immediate.
3182   case Mips::BI__builtin_msa_copy_s_w:
3183   case Mips::BI__builtin_msa_copy_u_w:
3184   case Mips::BI__builtin_msa_insve_w:
3185   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3186   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3187   // These intrinsics take an unsigned 1 bit immediate.
3188   case Mips::BI__builtin_msa_copy_s_d:
3189   case Mips::BI__builtin_msa_copy_u_d:
3190   case Mips::BI__builtin_msa_insve_d:
3191   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3192   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3193   // Memory offsets and immediate loads.
3194   // These intrinsics take a signed 10 bit immediate.
3195   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3196   case Mips::BI__builtin_msa_ldi_h:
3197   case Mips::BI__builtin_msa_ldi_w:
3198   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3199   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3200   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3201   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3202   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3203   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3204   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3205   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3206   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3207   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3208   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3209   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3210   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3211   }
3212 
3213   if (!m)
3214     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3215 
3216   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3217          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3218 }
3219 
3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3221 /// advancing the pointer over the consumed characters. The decoded type is
3222 /// returned. If the decoded type represents a constant integer with a
3223 /// constraint on its value then Mask is set to that value. The type descriptors
3224 /// used in Str are specific to PPC MMA builtins and are documented in the file
3225 /// defining the PPC builtins.
3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3227                                         unsigned &Mask) {
3228   bool RequireICE = false;
3229   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3230   switch (*Str++) {
3231   case 'V':
3232     return Context.getVectorType(Context.UnsignedCharTy, 16,
3233                                  VectorType::VectorKind::AltiVecVector);
3234   case 'i': {
3235     char *End;
3236     unsigned size = strtoul(Str, &End, 10);
3237     assert(End != Str && "Missing constant parameter constraint");
3238     Str = End;
3239     Mask = size;
3240     return Context.IntTy;
3241   }
3242   case 'W': {
3243     char *End;
3244     unsigned size = strtoul(Str, &End, 10);
3245     assert(End != Str && "Missing PowerPC MMA type size");
3246     Str = End;
3247     QualType Type;
3248     switch (size) {
3249   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3250     case size: Type = Context.Id##Ty; break;
3251   #include "clang/Basic/PPCTypes.def"
3252     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3253     }
3254     bool CheckVectorArgs = false;
3255     while (!CheckVectorArgs) {
3256       switch (*Str++) {
3257       case '*':
3258         Type = Context.getPointerType(Type);
3259         break;
3260       case 'C':
3261         Type = Type.withConst();
3262         break;
3263       default:
3264         CheckVectorArgs = true;
3265         --Str;
3266         break;
3267       }
3268     }
3269     return Type;
3270   }
3271   default:
3272     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3273   }
3274 }
3275 
3276 static bool isPPC_64Builtin(unsigned BuiltinID) {
3277   // These builtins only work on PPC 64bit targets.
3278   switch (BuiltinID) {
3279   case PPC::BI__builtin_divde:
3280   case PPC::BI__builtin_divdeu:
3281   case PPC::BI__builtin_bpermd:
3282   case PPC::BI__builtin_ppc_ldarx:
3283   case PPC::BI__builtin_ppc_stdcx:
3284   case PPC::BI__builtin_ppc_tdw:
3285   case PPC::BI__builtin_ppc_trapd:
3286   case PPC::BI__builtin_ppc_cmpeqb:
3287   case PPC::BI__builtin_ppc_setb:
3288   case PPC::BI__builtin_ppc_mulhd:
3289   case PPC::BI__builtin_ppc_mulhdu:
3290   case PPC::BI__builtin_ppc_maddhd:
3291   case PPC::BI__builtin_ppc_maddhdu:
3292   case PPC::BI__builtin_ppc_maddld:
3293   case PPC::BI__builtin_ppc_load8r:
3294   case PPC::BI__builtin_ppc_store8r:
3295   case PPC::BI__builtin_ppc_insert_exp:
3296   case PPC::BI__builtin_ppc_extract_sig:
3297   case PPC::BI__builtin_ppc_addex:
3298     return true;
3299   }
3300   return false;
3301 }
3302 
3303 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3304                              StringRef FeatureToCheck, unsigned DiagID,
3305                              StringRef DiagArg = "") {
3306   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3307     return false;
3308 
3309   if (DiagArg.empty())
3310     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3311   else
3312     S.Diag(TheCall->getBeginLoc(), DiagID)
3313         << DiagArg << TheCall->getSourceRange();
3314 
3315   return true;
3316 }
3317 
3318 /// Returns true if the argument consists of one contiguous run of 1s with any
3319 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3320 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3321 /// since all 1s are not contiguous.
3322 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3323   llvm::APSInt Result;
3324   // We can't check the value of a dependent argument.
3325   Expr *Arg = TheCall->getArg(ArgNum);
3326   if (Arg->isTypeDependent() || Arg->isValueDependent())
3327     return false;
3328 
3329   // Check constant-ness first.
3330   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3331     return true;
3332 
3333   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3334   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3335     return false;
3336 
3337   return Diag(TheCall->getBeginLoc(),
3338               diag::err_argument_not_contiguous_bit_field)
3339          << ArgNum << Arg->getSourceRange();
3340 }
3341 
3342 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3343                                        CallExpr *TheCall) {
3344   unsigned i = 0, l = 0, u = 0;
3345   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3346   llvm::APSInt Result;
3347 
3348   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3349     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3350            << TheCall->getSourceRange();
3351 
3352   switch (BuiltinID) {
3353   default: return false;
3354   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3355   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3356     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3357            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3358   case PPC::BI__builtin_altivec_dss:
3359     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3360   case PPC::BI__builtin_tbegin:
3361   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3362   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3363   case PPC::BI__builtin_tabortwc:
3364   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3365   case PPC::BI__builtin_tabortwci:
3366   case PPC::BI__builtin_tabortdci:
3367     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3368            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3369   case PPC::BI__builtin_altivec_dst:
3370   case PPC::BI__builtin_altivec_dstt:
3371   case PPC::BI__builtin_altivec_dstst:
3372   case PPC::BI__builtin_altivec_dststt:
3373     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3374   case PPC::BI__builtin_vsx_xxpermdi:
3375   case PPC::BI__builtin_vsx_xxsldwi:
3376     return SemaBuiltinVSX(TheCall);
3377   case PPC::BI__builtin_divwe:
3378   case PPC::BI__builtin_divweu:
3379   case PPC::BI__builtin_divde:
3380   case PPC::BI__builtin_divdeu:
3381     return SemaFeatureCheck(*this, TheCall, "extdiv",
3382                             diag::err_ppc_builtin_only_on_arch, "7");
3383   case PPC::BI__builtin_bpermd:
3384     return SemaFeatureCheck(*this, TheCall, "bpermd",
3385                             diag::err_ppc_builtin_only_on_arch, "7");
3386   case PPC::BI__builtin_unpack_vector_int128:
3387     return SemaFeatureCheck(*this, TheCall, "vsx",
3388                             diag::err_ppc_builtin_only_on_arch, "7") ||
3389            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3390   case PPC::BI__builtin_pack_vector_int128:
3391     return SemaFeatureCheck(*this, TheCall, "vsx",
3392                             diag::err_ppc_builtin_only_on_arch, "7");
3393   case PPC::BI__builtin_altivec_vgnb:
3394      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3395   case PPC::BI__builtin_altivec_vec_replace_elt:
3396   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3397     QualType VecTy = TheCall->getArg(0)->getType();
3398     QualType EltTy = TheCall->getArg(1)->getType();
3399     unsigned Width = Context.getIntWidth(EltTy);
3400     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3401            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3402   }
3403   case PPC::BI__builtin_vsx_xxeval:
3404      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3405   case PPC::BI__builtin_altivec_vsldbi:
3406      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3407   case PPC::BI__builtin_altivec_vsrdbi:
3408      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3409   case PPC::BI__builtin_vsx_xxpermx:
3410      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3411   case PPC::BI__builtin_ppc_tw:
3412   case PPC::BI__builtin_ppc_tdw:
3413     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3414   case PPC::BI__builtin_ppc_cmpeqb:
3415   case PPC::BI__builtin_ppc_setb:
3416   case PPC::BI__builtin_ppc_maddhd:
3417   case PPC::BI__builtin_ppc_maddhdu:
3418   case PPC::BI__builtin_ppc_maddld:
3419     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3420                             diag::err_ppc_builtin_only_on_arch, "9");
3421   case PPC::BI__builtin_ppc_cmprb:
3422     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3423                             diag::err_ppc_builtin_only_on_arch, "9") ||
3424            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3425   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3426   // be a constant that represents a contiguous bit field.
3427   case PPC::BI__builtin_ppc_rlwnm:
3428     return SemaBuiltinConstantArg(TheCall, 1, Result) ||
3429            SemaValueIsRunOfOnes(TheCall, 2);
3430   case PPC::BI__builtin_ppc_rlwimi:
3431   case PPC::BI__builtin_ppc_rldimi:
3432     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3433            SemaValueIsRunOfOnes(TheCall, 3);
3434   case PPC::BI__builtin_ppc_extract_exp:
3435   case PPC::BI__builtin_ppc_extract_sig:
3436   case PPC::BI__builtin_ppc_insert_exp:
3437     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3438                             diag::err_ppc_builtin_only_on_arch, "9");
3439   case PPC::BI__builtin_ppc_addex: {
3440     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3441                          diag::err_ppc_builtin_only_on_arch, "9") ||
3442         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3443       return true;
3444     // Output warning for reserved values 1 to 3.
3445     int ArgValue =
3446         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3447     if (ArgValue != 0)
3448       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3449           << ArgValue;
3450     return false;
3451   }
3452   case PPC::BI__builtin_ppc_mtfsb0:
3453   case PPC::BI__builtin_ppc_mtfsb1:
3454     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3455   case PPC::BI__builtin_ppc_mtfsf:
3456     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3457   case PPC::BI__builtin_ppc_mtfsfi:
3458     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3459            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3460   case PPC::BI__builtin_ppc_alignx:
3461     return SemaBuiltinConstantArgPower2(TheCall, 0);
3462   case PPC::BI__builtin_ppc_rdlam:
3463     return SemaValueIsRunOfOnes(TheCall, 2);
3464   case PPC::BI__builtin_ppc_icbt:
3465   case PPC::BI__builtin_ppc_sthcx:
3466   case PPC::BI__builtin_ppc_stbcx:
3467   case PPC::BI__builtin_ppc_lharx:
3468   case PPC::BI__builtin_ppc_lbarx:
3469     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3470                             diag::err_ppc_builtin_only_on_arch, "8");
3471   case PPC::BI__builtin_vsx_ldrmb:
3472   case PPC::BI__builtin_vsx_strmb:
3473     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3474                             diag::err_ppc_builtin_only_on_arch, "8") ||
3475            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3476 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3477   case PPC::BI__builtin_##Name: \
3478     return SemaBuiltinPPCMMACall(TheCall, Types);
3479 #include "clang/Basic/BuiltinsPPC.def"
3480   }
3481   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3482 }
3483 
3484 // Check if the given type is a non-pointer PPC MMA type. This function is used
3485 // in Sema to prevent invalid uses of restricted PPC MMA types.
3486 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3487   if (Type->isPointerType() || Type->isArrayType())
3488     return false;
3489 
3490   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3491 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3492   if (false
3493 #include "clang/Basic/PPCTypes.def"
3494      ) {
3495     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3496     return true;
3497   }
3498   return false;
3499 }
3500 
3501 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3502                                           CallExpr *TheCall) {
3503   // position of memory order and scope arguments in the builtin
3504   unsigned OrderIndex, ScopeIndex;
3505   switch (BuiltinID) {
3506   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3507   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3508   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3509   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3510     OrderIndex = 2;
3511     ScopeIndex = 3;
3512     break;
3513   case AMDGPU::BI__builtin_amdgcn_fence:
3514     OrderIndex = 0;
3515     ScopeIndex = 1;
3516     break;
3517   default:
3518     return false;
3519   }
3520 
3521   ExprResult Arg = TheCall->getArg(OrderIndex);
3522   auto ArgExpr = Arg.get();
3523   Expr::EvalResult ArgResult;
3524 
3525   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3526     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3527            << ArgExpr->getType();
3528   auto Ord = ArgResult.Val.getInt().getZExtValue();
3529 
3530   // Check validity of memory ordering as per C11 / C++11's memody model.
3531   // Only fence needs check. Atomic dec/inc allow all memory orders.
3532   if (!llvm::isValidAtomicOrderingCABI(Ord))
3533     return Diag(ArgExpr->getBeginLoc(),
3534                 diag::warn_atomic_op_has_invalid_memory_order)
3535            << ArgExpr->getSourceRange();
3536   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3537   case llvm::AtomicOrderingCABI::relaxed:
3538   case llvm::AtomicOrderingCABI::consume:
3539     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3540       return Diag(ArgExpr->getBeginLoc(),
3541                   diag::warn_atomic_op_has_invalid_memory_order)
3542              << ArgExpr->getSourceRange();
3543     break;
3544   case llvm::AtomicOrderingCABI::acquire:
3545   case llvm::AtomicOrderingCABI::release:
3546   case llvm::AtomicOrderingCABI::acq_rel:
3547   case llvm::AtomicOrderingCABI::seq_cst:
3548     break;
3549   }
3550 
3551   Arg = TheCall->getArg(ScopeIndex);
3552   ArgExpr = Arg.get();
3553   Expr::EvalResult ArgResult1;
3554   // Check that sync scope is a constant literal
3555   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3556     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3557            << ArgExpr->getType();
3558 
3559   return false;
3560 }
3561 
3562 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3563   llvm::APSInt Result;
3564 
3565   // We can't check the value of a dependent argument.
3566   Expr *Arg = TheCall->getArg(ArgNum);
3567   if (Arg->isTypeDependent() || Arg->isValueDependent())
3568     return false;
3569 
3570   // Check constant-ness first.
3571   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3572     return true;
3573 
3574   int64_t Val = Result.getSExtValue();
3575   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3576     return false;
3577 
3578   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3579          << Arg->getSourceRange();
3580 }
3581 
3582 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3583                                          unsigned BuiltinID,
3584                                          CallExpr *TheCall) {
3585   // CodeGenFunction can also detect this, but this gives a better error
3586   // message.
3587   bool FeatureMissing = false;
3588   SmallVector<StringRef> ReqFeatures;
3589   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3590   Features.split(ReqFeatures, ',');
3591 
3592   // Check if each required feature is included
3593   for (StringRef F : ReqFeatures) {
3594     if (TI.hasFeature(F))
3595       continue;
3596 
3597     // If the feature is 64bit, alter the string so it will print better in
3598     // the diagnostic.
3599     if (F == "64bit")
3600       F = "RV64";
3601 
3602     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3603     F.consume_front("experimental-");
3604     std::string FeatureStr = F.str();
3605     FeatureStr[0] = std::toupper(FeatureStr[0]);
3606 
3607     // Error message
3608     FeatureMissing = true;
3609     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3610         << TheCall->getSourceRange() << StringRef(FeatureStr);
3611   }
3612 
3613   if (FeatureMissing)
3614     return true;
3615 
3616   switch (BuiltinID) {
3617   case RISCV::BI__builtin_rvv_vsetvli:
3618     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3619            CheckRISCVLMUL(TheCall, 2);
3620   case RISCV::BI__builtin_rvv_vsetvlimax:
3621     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3622            CheckRISCVLMUL(TheCall, 1);
3623   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3624   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3625   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3626   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3627   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3628   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3629   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3630   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3631   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3632   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3633   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3634   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3635   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3636   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3637   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3638   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3639   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3640   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3641   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3642   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3643   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3644   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3645   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3646   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3647   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3648   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3649   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3650   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3651   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3652   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3653     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3654   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3655   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3656   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3657   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3658   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3659   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3660   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3661   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3662   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3663   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3664   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3665   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3666   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3667   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3668   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3669   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3670   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3671   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3672   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3673   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3674     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3675   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3676   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3677   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3678   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3679   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3680   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3681   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3682   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3683   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3684   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3685     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3686   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3687   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3688   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3689   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3690   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3691   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3692   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3693   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3694   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3695   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3696   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3697   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3698   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3699   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3700   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3701   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3702   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3703   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3704   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3705   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3706   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3707   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3708   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3709   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3710   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3711   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3712   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3713   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3714   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3715   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3716     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3717   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3718   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3719   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3720   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3721   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3722   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3723   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3724   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3725   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3726   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3727   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3728   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3729   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3730   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3731   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3732   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3733   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3734   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3735   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3736   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3737     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3738   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3739   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3740   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3741   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3742   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3743   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3744   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3745   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3746   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3747   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3748     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3749   }
3750 
3751   return false;
3752 }
3753 
3754 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3755                                            CallExpr *TheCall) {
3756   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3757     Expr *Arg = TheCall->getArg(0);
3758     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3759       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3760         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3761                << Arg->getSourceRange();
3762   }
3763 
3764   // For intrinsics which take an immediate value as part of the instruction,
3765   // range check them here.
3766   unsigned i = 0, l = 0, u = 0;
3767   switch (BuiltinID) {
3768   default: return false;
3769   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3770   case SystemZ::BI__builtin_s390_verimb:
3771   case SystemZ::BI__builtin_s390_verimh:
3772   case SystemZ::BI__builtin_s390_verimf:
3773   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3774   case SystemZ::BI__builtin_s390_vfaeb:
3775   case SystemZ::BI__builtin_s390_vfaeh:
3776   case SystemZ::BI__builtin_s390_vfaef:
3777   case SystemZ::BI__builtin_s390_vfaebs:
3778   case SystemZ::BI__builtin_s390_vfaehs:
3779   case SystemZ::BI__builtin_s390_vfaefs:
3780   case SystemZ::BI__builtin_s390_vfaezb:
3781   case SystemZ::BI__builtin_s390_vfaezh:
3782   case SystemZ::BI__builtin_s390_vfaezf:
3783   case SystemZ::BI__builtin_s390_vfaezbs:
3784   case SystemZ::BI__builtin_s390_vfaezhs:
3785   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3786   case SystemZ::BI__builtin_s390_vfisb:
3787   case SystemZ::BI__builtin_s390_vfidb:
3788     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3789            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3790   case SystemZ::BI__builtin_s390_vftcisb:
3791   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3792   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3793   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3794   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3795   case SystemZ::BI__builtin_s390_vstrcb:
3796   case SystemZ::BI__builtin_s390_vstrch:
3797   case SystemZ::BI__builtin_s390_vstrcf:
3798   case SystemZ::BI__builtin_s390_vstrczb:
3799   case SystemZ::BI__builtin_s390_vstrczh:
3800   case SystemZ::BI__builtin_s390_vstrczf:
3801   case SystemZ::BI__builtin_s390_vstrcbs:
3802   case SystemZ::BI__builtin_s390_vstrchs:
3803   case SystemZ::BI__builtin_s390_vstrcfs:
3804   case SystemZ::BI__builtin_s390_vstrczbs:
3805   case SystemZ::BI__builtin_s390_vstrczhs:
3806   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3807   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3808   case SystemZ::BI__builtin_s390_vfminsb:
3809   case SystemZ::BI__builtin_s390_vfmaxsb:
3810   case SystemZ::BI__builtin_s390_vfmindb:
3811   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3812   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3813   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3814   case SystemZ::BI__builtin_s390_vclfnhs:
3815   case SystemZ::BI__builtin_s390_vclfnls:
3816   case SystemZ::BI__builtin_s390_vcfn:
3817   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3818   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3819   }
3820   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3821 }
3822 
3823 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3824 /// This checks that the target supports __builtin_cpu_supports and
3825 /// that the string argument is constant and valid.
3826 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3827                                    CallExpr *TheCall) {
3828   Expr *Arg = TheCall->getArg(0);
3829 
3830   // Check if the argument is a string literal.
3831   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3832     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3833            << Arg->getSourceRange();
3834 
3835   // Check the contents of the string.
3836   StringRef Feature =
3837       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3838   if (!TI.validateCpuSupports(Feature))
3839     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3840            << Arg->getSourceRange();
3841   return false;
3842 }
3843 
3844 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3845 /// This checks that the target supports __builtin_cpu_is and
3846 /// that the string argument is constant and valid.
3847 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3848   Expr *Arg = TheCall->getArg(0);
3849 
3850   // Check if the argument is a string literal.
3851   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3852     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3853            << Arg->getSourceRange();
3854 
3855   // Check the contents of the string.
3856   StringRef Feature =
3857       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3858   if (!TI.validateCpuIs(Feature))
3859     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3860            << Arg->getSourceRange();
3861   return false;
3862 }
3863 
3864 // Check if the rounding mode is legal.
3865 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3866   // Indicates if this instruction has rounding control or just SAE.
3867   bool HasRC = false;
3868 
3869   unsigned ArgNum = 0;
3870   switch (BuiltinID) {
3871   default:
3872     return false;
3873   case X86::BI__builtin_ia32_vcvttsd2si32:
3874   case X86::BI__builtin_ia32_vcvttsd2si64:
3875   case X86::BI__builtin_ia32_vcvttsd2usi32:
3876   case X86::BI__builtin_ia32_vcvttsd2usi64:
3877   case X86::BI__builtin_ia32_vcvttss2si32:
3878   case X86::BI__builtin_ia32_vcvttss2si64:
3879   case X86::BI__builtin_ia32_vcvttss2usi32:
3880   case X86::BI__builtin_ia32_vcvttss2usi64:
3881   case X86::BI__builtin_ia32_vcvttsh2si32:
3882   case X86::BI__builtin_ia32_vcvttsh2si64:
3883   case X86::BI__builtin_ia32_vcvttsh2usi32:
3884   case X86::BI__builtin_ia32_vcvttsh2usi64:
3885     ArgNum = 1;
3886     break;
3887   case X86::BI__builtin_ia32_maxpd512:
3888   case X86::BI__builtin_ia32_maxps512:
3889   case X86::BI__builtin_ia32_minpd512:
3890   case X86::BI__builtin_ia32_minps512:
3891   case X86::BI__builtin_ia32_maxph512:
3892   case X86::BI__builtin_ia32_minph512:
3893     ArgNum = 2;
3894     break;
3895   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3896   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3897   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3898   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3899   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3900   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3901   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3902   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3903   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3904   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3905   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3906   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3907   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3908   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3909   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3910   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3911   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3912   case X86::BI__builtin_ia32_exp2pd_mask:
3913   case X86::BI__builtin_ia32_exp2ps_mask:
3914   case X86::BI__builtin_ia32_getexppd512_mask:
3915   case X86::BI__builtin_ia32_getexpps512_mask:
3916   case X86::BI__builtin_ia32_getexpph512_mask:
3917   case X86::BI__builtin_ia32_rcp28pd_mask:
3918   case X86::BI__builtin_ia32_rcp28ps_mask:
3919   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3920   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3921   case X86::BI__builtin_ia32_vcomisd:
3922   case X86::BI__builtin_ia32_vcomiss:
3923   case X86::BI__builtin_ia32_vcomish:
3924   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3925     ArgNum = 3;
3926     break;
3927   case X86::BI__builtin_ia32_cmppd512_mask:
3928   case X86::BI__builtin_ia32_cmpps512_mask:
3929   case X86::BI__builtin_ia32_cmpsd_mask:
3930   case X86::BI__builtin_ia32_cmpss_mask:
3931   case X86::BI__builtin_ia32_cmpsh_mask:
3932   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3933   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3934   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3935   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3936   case X86::BI__builtin_ia32_getexpss128_round_mask:
3937   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3938   case X86::BI__builtin_ia32_getmantpd512_mask:
3939   case X86::BI__builtin_ia32_getmantps512_mask:
3940   case X86::BI__builtin_ia32_getmantph512_mask:
3941   case X86::BI__builtin_ia32_maxsd_round_mask:
3942   case X86::BI__builtin_ia32_maxss_round_mask:
3943   case X86::BI__builtin_ia32_maxsh_round_mask:
3944   case X86::BI__builtin_ia32_minsd_round_mask:
3945   case X86::BI__builtin_ia32_minss_round_mask:
3946   case X86::BI__builtin_ia32_minsh_round_mask:
3947   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3948   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3949   case X86::BI__builtin_ia32_reducepd512_mask:
3950   case X86::BI__builtin_ia32_reduceps512_mask:
3951   case X86::BI__builtin_ia32_reduceph512_mask:
3952   case X86::BI__builtin_ia32_rndscalepd_mask:
3953   case X86::BI__builtin_ia32_rndscaleps_mask:
3954   case X86::BI__builtin_ia32_rndscaleph_mask:
3955   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3956   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3957     ArgNum = 4;
3958     break;
3959   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3960   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3961   case X86::BI__builtin_ia32_fixupimmps512_mask:
3962   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3963   case X86::BI__builtin_ia32_fixupimmsd_mask:
3964   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3965   case X86::BI__builtin_ia32_fixupimmss_mask:
3966   case X86::BI__builtin_ia32_fixupimmss_maskz:
3967   case X86::BI__builtin_ia32_getmantsd_round_mask:
3968   case X86::BI__builtin_ia32_getmantss_round_mask:
3969   case X86::BI__builtin_ia32_getmantsh_round_mask:
3970   case X86::BI__builtin_ia32_rangepd512_mask:
3971   case X86::BI__builtin_ia32_rangeps512_mask:
3972   case X86::BI__builtin_ia32_rangesd128_round_mask:
3973   case X86::BI__builtin_ia32_rangess128_round_mask:
3974   case X86::BI__builtin_ia32_reducesd_mask:
3975   case X86::BI__builtin_ia32_reducess_mask:
3976   case X86::BI__builtin_ia32_reducesh_mask:
3977   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3978   case X86::BI__builtin_ia32_rndscaless_round_mask:
3979   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3980     ArgNum = 5;
3981     break;
3982   case X86::BI__builtin_ia32_vcvtsd2si64:
3983   case X86::BI__builtin_ia32_vcvtsd2si32:
3984   case X86::BI__builtin_ia32_vcvtsd2usi32:
3985   case X86::BI__builtin_ia32_vcvtsd2usi64:
3986   case X86::BI__builtin_ia32_vcvtss2si32:
3987   case X86::BI__builtin_ia32_vcvtss2si64:
3988   case X86::BI__builtin_ia32_vcvtss2usi32:
3989   case X86::BI__builtin_ia32_vcvtss2usi64:
3990   case X86::BI__builtin_ia32_vcvtsh2si32:
3991   case X86::BI__builtin_ia32_vcvtsh2si64:
3992   case X86::BI__builtin_ia32_vcvtsh2usi32:
3993   case X86::BI__builtin_ia32_vcvtsh2usi64:
3994   case X86::BI__builtin_ia32_sqrtpd512:
3995   case X86::BI__builtin_ia32_sqrtps512:
3996   case X86::BI__builtin_ia32_sqrtph512:
3997     ArgNum = 1;
3998     HasRC = true;
3999     break;
4000   case X86::BI__builtin_ia32_addph512:
4001   case X86::BI__builtin_ia32_divph512:
4002   case X86::BI__builtin_ia32_mulph512:
4003   case X86::BI__builtin_ia32_subph512:
4004   case X86::BI__builtin_ia32_addpd512:
4005   case X86::BI__builtin_ia32_addps512:
4006   case X86::BI__builtin_ia32_divpd512:
4007   case X86::BI__builtin_ia32_divps512:
4008   case X86::BI__builtin_ia32_mulpd512:
4009   case X86::BI__builtin_ia32_mulps512:
4010   case X86::BI__builtin_ia32_subpd512:
4011   case X86::BI__builtin_ia32_subps512:
4012   case X86::BI__builtin_ia32_cvtsi2sd64:
4013   case X86::BI__builtin_ia32_cvtsi2ss32:
4014   case X86::BI__builtin_ia32_cvtsi2ss64:
4015   case X86::BI__builtin_ia32_cvtusi2sd64:
4016   case X86::BI__builtin_ia32_cvtusi2ss32:
4017   case X86::BI__builtin_ia32_cvtusi2ss64:
4018   case X86::BI__builtin_ia32_vcvtusi2sh:
4019   case X86::BI__builtin_ia32_vcvtusi642sh:
4020   case X86::BI__builtin_ia32_vcvtsi2sh:
4021   case X86::BI__builtin_ia32_vcvtsi642sh:
4022     ArgNum = 2;
4023     HasRC = true;
4024     break;
4025   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4026   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4027   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4028   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4029   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4030   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4031   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4032   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4033   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4034   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4035   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4036   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4037   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4038   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4039   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4040   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4041   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4042   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4043   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4044   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4045   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4046   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4047   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4048   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4049   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4050   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4051   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4052   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4053   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4054     ArgNum = 3;
4055     HasRC = true;
4056     break;
4057   case X86::BI__builtin_ia32_addsh_round_mask:
4058   case X86::BI__builtin_ia32_addss_round_mask:
4059   case X86::BI__builtin_ia32_addsd_round_mask:
4060   case X86::BI__builtin_ia32_divsh_round_mask:
4061   case X86::BI__builtin_ia32_divss_round_mask:
4062   case X86::BI__builtin_ia32_divsd_round_mask:
4063   case X86::BI__builtin_ia32_mulsh_round_mask:
4064   case X86::BI__builtin_ia32_mulss_round_mask:
4065   case X86::BI__builtin_ia32_mulsd_round_mask:
4066   case X86::BI__builtin_ia32_subsh_round_mask:
4067   case X86::BI__builtin_ia32_subss_round_mask:
4068   case X86::BI__builtin_ia32_subsd_round_mask:
4069   case X86::BI__builtin_ia32_scalefph512_mask:
4070   case X86::BI__builtin_ia32_scalefpd512_mask:
4071   case X86::BI__builtin_ia32_scalefps512_mask:
4072   case X86::BI__builtin_ia32_scalefsd_round_mask:
4073   case X86::BI__builtin_ia32_scalefss_round_mask:
4074   case X86::BI__builtin_ia32_scalefsh_round_mask:
4075   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4076   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4077   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4078   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4079   case X86::BI__builtin_ia32_sqrtss_round_mask:
4080   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4081   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4082   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4083   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4084   case X86::BI__builtin_ia32_vfmaddss3_mask:
4085   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4086   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4087   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4088   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4089   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4090   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4091   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4092   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4093   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4094   case X86::BI__builtin_ia32_vfmaddps512_mask:
4095   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4096   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4097   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4098   case X86::BI__builtin_ia32_vfmaddph512_mask:
4099   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4100   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4101   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4102   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4103   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4104   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4105   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4106   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4107   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4108   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4109   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4110   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4111   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4112   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4113   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4114   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4115   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4116   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4117   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4118   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4119   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4120   case X86::BI__builtin_ia32_vfmulcsh_mask:
4121   case X86::BI__builtin_ia32_vfmulcph512_mask:
4122   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4123   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4124     ArgNum = 4;
4125     HasRC = true;
4126     break;
4127   }
4128 
4129   llvm::APSInt Result;
4130 
4131   // We can't check the value of a dependent argument.
4132   Expr *Arg = TheCall->getArg(ArgNum);
4133   if (Arg->isTypeDependent() || Arg->isValueDependent())
4134     return false;
4135 
4136   // Check constant-ness first.
4137   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4138     return true;
4139 
4140   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4141   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4142   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4143   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4144   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4145       Result == 8/*ROUND_NO_EXC*/ ||
4146       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4147       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4148     return false;
4149 
4150   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4151          << Arg->getSourceRange();
4152 }
4153 
4154 // Check if the gather/scatter scale is legal.
4155 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4156                                              CallExpr *TheCall) {
4157   unsigned ArgNum = 0;
4158   switch (BuiltinID) {
4159   default:
4160     return false;
4161   case X86::BI__builtin_ia32_gatherpfdpd:
4162   case X86::BI__builtin_ia32_gatherpfdps:
4163   case X86::BI__builtin_ia32_gatherpfqpd:
4164   case X86::BI__builtin_ia32_gatherpfqps:
4165   case X86::BI__builtin_ia32_scatterpfdpd:
4166   case X86::BI__builtin_ia32_scatterpfdps:
4167   case X86::BI__builtin_ia32_scatterpfqpd:
4168   case X86::BI__builtin_ia32_scatterpfqps:
4169     ArgNum = 3;
4170     break;
4171   case X86::BI__builtin_ia32_gatherd_pd:
4172   case X86::BI__builtin_ia32_gatherd_pd256:
4173   case X86::BI__builtin_ia32_gatherq_pd:
4174   case X86::BI__builtin_ia32_gatherq_pd256:
4175   case X86::BI__builtin_ia32_gatherd_ps:
4176   case X86::BI__builtin_ia32_gatherd_ps256:
4177   case X86::BI__builtin_ia32_gatherq_ps:
4178   case X86::BI__builtin_ia32_gatherq_ps256:
4179   case X86::BI__builtin_ia32_gatherd_q:
4180   case X86::BI__builtin_ia32_gatherd_q256:
4181   case X86::BI__builtin_ia32_gatherq_q:
4182   case X86::BI__builtin_ia32_gatherq_q256:
4183   case X86::BI__builtin_ia32_gatherd_d:
4184   case X86::BI__builtin_ia32_gatherd_d256:
4185   case X86::BI__builtin_ia32_gatherq_d:
4186   case X86::BI__builtin_ia32_gatherq_d256:
4187   case X86::BI__builtin_ia32_gather3div2df:
4188   case X86::BI__builtin_ia32_gather3div2di:
4189   case X86::BI__builtin_ia32_gather3div4df:
4190   case X86::BI__builtin_ia32_gather3div4di:
4191   case X86::BI__builtin_ia32_gather3div4sf:
4192   case X86::BI__builtin_ia32_gather3div4si:
4193   case X86::BI__builtin_ia32_gather3div8sf:
4194   case X86::BI__builtin_ia32_gather3div8si:
4195   case X86::BI__builtin_ia32_gather3siv2df:
4196   case X86::BI__builtin_ia32_gather3siv2di:
4197   case X86::BI__builtin_ia32_gather3siv4df:
4198   case X86::BI__builtin_ia32_gather3siv4di:
4199   case X86::BI__builtin_ia32_gather3siv4sf:
4200   case X86::BI__builtin_ia32_gather3siv4si:
4201   case X86::BI__builtin_ia32_gather3siv8sf:
4202   case X86::BI__builtin_ia32_gather3siv8si:
4203   case X86::BI__builtin_ia32_gathersiv8df:
4204   case X86::BI__builtin_ia32_gathersiv16sf:
4205   case X86::BI__builtin_ia32_gatherdiv8df:
4206   case X86::BI__builtin_ia32_gatherdiv16sf:
4207   case X86::BI__builtin_ia32_gathersiv8di:
4208   case X86::BI__builtin_ia32_gathersiv16si:
4209   case X86::BI__builtin_ia32_gatherdiv8di:
4210   case X86::BI__builtin_ia32_gatherdiv16si:
4211   case X86::BI__builtin_ia32_scatterdiv2df:
4212   case X86::BI__builtin_ia32_scatterdiv2di:
4213   case X86::BI__builtin_ia32_scatterdiv4df:
4214   case X86::BI__builtin_ia32_scatterdiv4di:
4215   case X86::BI__builtin_ia32_scatterdiv4sf:
4216   case X86::BI__builtin_ia32_scatterdiv4si:
4217   case X86::BI__builtin_ia32_scatterdiv8sf:
4218   case X86::BI__builtin_ia32_scatterdiv8si:
4219   case X86::BI__builtin_ia32_scattersiv2df:
4220   case X86::BI__builtin_ia32_scattersiv2di:
4221   case X86::BI__builtin_ia32_scattersiv4df:
4222   case X86::BI__builtin_ia32_scattersiv4di:
4223   case X86::BI__builtin_ia32_scattersiv4sf:
4224   case X86::BI__builtin_ia32_scattersiv4si:
4225   case X86::BI__builtin_ia32_scattersiv8sf:
4226   case X86::BI__builtin_ia32_scattersiv8si:
4227   case X86::BI__builtin_ia32_scattersiv8df:
4228   case X86::BI__builtin_ia32_scattersiv16sf:
4229   case X86::BI__builtin_ia32_scatterdiv8df:
4230   case X86::BI__builtin_ia32_scatterdiv16sf:
4231   case X86::BI__builtin_ia32_scattersiv8di:
4232   case X86::BI__builtin_ia32_scattersiv16si:
4233   case X86::BI__builtin_ia32_scatterdiv8di:
4234   case X86::BI__builtin_ia32_scatterdiv16si:
4235     ArgNum = 4;
4236     break;
4237   }
4238 
4239   llvm::APSInt Result;
4240 
4241   // We can't check the value of a dependent argument.
4242   Expr *Arg = TheCall->getArg(ArgNum);
4243   if (Arg->isTypeDependent() || Arg->isValueDependent())
4244     return false;
4245 
4246   // Check constant-ness first.
4247   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4248     return true;
4249 
4250   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4251     return false;
4252 
4253   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4254          << Arg->getSourceRange();
4255 }
4256 
4257 enum { TileRegLow = 0, TileRegHigh = 7 };
4258 
4259 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4260                                              ArrayRef<int> ArgNums) {
4261   for (int ArgNum : ArgNums) {
4262     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4263       return true;
4264   }
4265   return false;
4266 }
4267 
4268 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4269                                         ArrayRef<int> ArgNums) {
4270   // Because the max number of tile register is TileRegHigh + 1, so here we use
4271   // each bit to represent the usage of them in bitset.
4272   std::bitset<TileRegHigh + 1> ArgValues;
4273   for (int ArgNum : ArgNums) {
4274     Expr *Arg = TheCall->getArg(ArgNum);
4275     if (Arg->isTypeDependent() || Arg->isValueDependent())
4276       continue;
4277 
4278     llvm::APSInt Result;
4279     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4280       return true;
4281     int ArgExtValue = Result.getExtValue();
4282     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4283            "Incorrect tile register num.");
4284     if (ArgValues.test(ArgExtValue))
4285       return Diag(TheCall->getBeginLoc(),
4286                   diag::err_x86_builtin_tile_arg_duplicate)
4287              << TheCall->getArg(ArgNum)->getSourceRange();
4288     ArgValues.set(ArgExtValue);
4289   }
4290   return false;
4291 }
4292 
4293 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4294                                                 ArrayRef<int> ArgNums) {
4295   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4296          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4297 }
4298 
4299 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4300   switch (BuiltinID) {
4301   default:
4302     return false;
4303   case X86::BI__builtin_ia32_tileloadd64:
4304   case X86::BI__builtin_ia32_tileloaddt164:
4305   case X86::BI__builtin_ia32_tilestored64:
4306   case X86::BI__builtin_ia32_tilezero:
4307     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4308   case X86::BI__builtin_ia32_tdpbssd:
4309   case X86::BI__builtin_ia32_tdpbsud:
4310   case X86::BI__builtin_ia32_tdpbusd:
4311   case X86::BI__builtin_ia32_tdpbuud:
4312   case X86::BI__builtin_ia32_tdpbf16ps:
4313     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4314   }
4315 }
4316 static bool isX86_32Builtin(unsigned BuiltinID) {
4317   // These builtins only work on x86-32 targets.
4318   switch (BuiltinID) {
4319   case X86::BI__builtin_ia32_readeflags_u32:
4320   case X86::BI__builtin_ia32_writeeflags_u32:
4321     return true;
4322   }
4323 
4324   return false;
4325 }
4326 
4327 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4328                                        CallExpr *TheCall) {
4329   if (BuiltinID == X86::BI__builtin_cpu_supports)
4330     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4331 
4332   if (BuiltinID == X86::BI__builtin_cpu_is)
4333     return SemaBuiltinCpuIs(*this, TI, TheCall);
4334 
4335   // Check for 32-bit only builtins on a 64-bit target.
4336   const llvm::Triple &TT = TI.getTriple();
4337   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4338     return Diag(TheCall->getCallee()->getBeginLoc(),
4339                 diag::err_32_bit_builtin_64_bit_tgt);
4340 
4341   // If the intrinsic has rounding or SAE make sure its valid.
4342   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4343     return true;
4344 
4345   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4346   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4347     return true;
4348 
4349   // If the intrinsic has a tile arguments, make sure they are valid.
4350   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4351     return true;
4352 
4353   // For intrinsics which take an immediate value as part of the instruction,
4354   // range check them here.
4355   int i = 0, l = 0, u = 0;
4356   switch (BuiltinID) {
4357   default:
4358     return false;
4359   case X86::BI__builtin_ia32_vec_ext_v2si:
4360   case X86::BI__builtin_ia32_vec_ext_v2di:
4361   case X86::BI__builtin_ia32_vextractf128_pd256:
4362   case X86::BI__builtin_ia32_vextractf128_ps256:
4363   case X86::BI__builtin_ia32_vextractf128_si256:
4364   case X86::BI__builtin_ia32_extract128i256:
4365   case X86::BI__builtin_ia32_extractf64x4_mask:
4366   case X86::BI__builtin_ia32_extracti64x4_mask:
4367   case X86::BI__builtin_ia32_extractf32x8_mask:
4368   case X86::BI__builtin_ia32_extracti32x8_mask:
4369   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4370   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4371   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4372   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4373     i = 1; l = 0; u = 1;
4374     break;
4375   case X86::BI__builtin_ia32_vec_set_v2di:
4376   case X86::BI__builtin_ia32_vinsertf128_pd256:
4377   case X86::BI__builtin_ia32_vinsertf128_ps256:
4378   case X86::BI__builtin_ia32_vinsertf128_si256:
4379   case X86::BI__builtin_ia32_insert128i256:
4380   case X86::BI__builtin_ia32_insertf32x8:
4381   case X86::BI__builtin_ia32_inserti32x8:
4382   case X86::BI__builtin_ia32_insertf64x4:
4383   case X86::BI__builtin_ia32_inserti64x4:
4384   case X86::BI__builtin_ia32_insertf64x2_256:
4385   case X86::BI__builtin_ia32_inserti64x2_256:
4386   case X86::BI__builtin_ia32_insertf32x4_256:
4387   case X86::BI__builtin_ia32_inserti32x4_256:
4388     i = 2; l = 0; u = 1;
4389     break;
4390   case X86::BI__builtin_ia32_vpermilpd:
4391   case X86::BI__builtin_ia32_vec_ext_v4hi:
4392   case X86::BI__builtin_ia32_vec_ext_v4si:
4393   case X86::BI__builtin_ia32_vec_ext_v4sf:
4394   case X86::BI__builtin_ia32_vec_ext_v4di:
4395   case X86::BI__builtin_ia32_extractf32x4_mask:
4396   case X86::BI__builtin_ia32_extracti32x4_mask:
4397   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4398   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4399     i = 1; l = 0; u = 3;
4400     break;
4401   case X86::BI_mm_prefetch:
4402   case X86::BI__builtin_ia32_vec_ext_v8hi:
4403   case X86::BI__builtin_ia32_vec_ext_v8si:
4404     i = 1; l = 0; u = 7;
4405     break;
4406   case X86::BI__builtin_ia32_sha1rnds4:
4407   case X86::BI__builtin_ia32_blendpd:
4408   case X86::BI__builtin_ia32_shufpd:
4409   case X86::BI__builtin_ia32_vec_set_v4hi:
4410   case X86::BI__builtin_ia32_vec_set_v4si:
4411   case X86::BI__builtin_ia32_vec_set_v4di:
4412   case X86::BI__builtin_ia32_shuf_f32x4_256:
4413   case X86::BI__builtin_ia32_shuf_f64x2_256:
4414   case X86::BI__builtin_ia32_shuf_i32x4_256:
4415   case X86::BI__builtin_ia32_shuf_i64x2_256:
4416   case X86::BI__builtin_ia32_insertf64x2_512:
4417   case X86::BI__builtin_ia32_inserti64x2_512:
4418   case X86::BI__builtin_ia32_insertf32x4:
4419   case X86::BI__builtin_ia32_inserti32x4:
4420     i = 2; l = 0; u = 3;
4421     break;
4422   case X86::BI__builtin_ia32_vpermil2pd:
4423   case X86::BI__builtin_ia32_vpermil2pd256:
4424   case X86::BI__builtin_ia32_vpermil2ps:
4425   case X86::BI__builtin_ia32_vpermil2ps256:
4426     i = 3; l = 0; u = 3;
4427     break;
4428   case X86::BI__builtin_ia32_cmpb128_mask:
4429   case X86::BI__builtin_ia32_cmpw128_mask:
4430   case X86::BI__builtin_ia32_cmpd128_mask:
4431   case X86::BI__builtin_ia32_cmpq128_mask:
4432   case X86::BI__builtin_ia32_cmpb256_mask:
4433   case X86::BI__builtin_ia32_cmpw256_mask:
4434   case X86::BI__builtin_ia32_cmpd256_mask:
4435   case X86::BI__builtin_ia32_cmpq256_mask:
4436   case X86::BI__builtin_ia32_cmpb512_mask:
4437   case X86::BI__builtin_ia32_cmpw512_mask:
4438   case X86::BI__builtin_ia32_cmpd512_mask:
4439   case X86::BI__builtin_ia32_cmpq512_mask:
4440   case X86::BI__builtin_ia32_ucmpb128_mask:
4441   case X86::BI__builtin_ia32_ucmpw128_mask:
4442   case X86::BI__builtin_ia32_ucmpd128_mask:
4443   case X86::BI__builtin_ia32_ucmpq128_mask:
4444   case X86::BI__builtin_ia32_ucmpb256_mask:
4445   case X86::BI__builtin_ia32_ucmpw256_mask:
4446   case X86::BI__builtin_ia32_ucmpd256_mask:
4447   case X86::BI__builtin_ia32_ucmpq256_mask:
4448   case X86::BI__builtin_ia32_ucmpb512_mask:
4449   case X86::BI__builtin_ia32_ucmpw512_mask:
4450   case X86::BI__builtin_ia32_ucmpd512_mask:
4451   case X86::BI__builtin_ia32_ucmpq512_mask:
4452   case X86::BI__builtin_ia32_vpcomub:
4453   case X86::BI__builtin_ia32_vpcomuw:
4454   case X86::BI__builtin_ia32_vpcomud:
4455   case X86::BI__builtin_ia32_vpcomuq:
4456   case X86::BI__builtin_ia32_vpcomb:
4457   case X86::BI__builtin_ia32_vpcomw:
4458   case X86::BI__builtin_ia32_vpcomd:
4459   case X86::BI__builtin_ia32_vpcomq:
4460   case X86::BI__builtin_ia32_vec_set_v8hi:
4461   case X86::BI__builtin_ia32_vec_set_v8si:
4462     i = 2; l = 0; u = 7;
4463     break;
4464   case X86::BI__builtin_ia32_vpermilpd256:
4465   case X86::BI__builtin_ia32_roundps:
4466   case X86::BI__builtin_ia32_roundpd:
4467   case X86::BI__builtin_ia32_roundps256:
4468   case X86::BI__builtin_ia32_roundpd256:
4469   case X86::BI__builtin_ia32_getmantpd128_mask:
4470   case X86::BI__builtin_ia32_getmantpd256_mask:
4471   case X86::BI__builtin_ia32_getmantps128_mask:
4472   case X86::BI__builtin_ia32_getmantps256_mask:
4473   case X86::BI__builtin_ia32_getmantpd512_mask:
4474   case X86::BI__builtin_ia32_getmantps512_mask:
4475   case X86::BI__builtin_ia32_getmantph128_mask:
4476   case X86::BI__builtin_ia32_getmantph256_mask:
4477   case X86::BI__builtin_ia32_getmantph512_mask:
4478   case X86::BI__builtin_ia32_vec_ext_v16qi:
4479   case X86::BI__builtin_ia32_vec_ext_v16hi:
4480     i = 1; l = 0; u = 15;
4481     break;
4482   case X86::BI__builtin_ia32_pblendd128:
4483   case X86::BI__builtin_ia32_blendps:
4484   case X86::BI__builtin_ia32_blendpd256:
4485   case X86::BI__builtin_ia32_shufpd256:
4486   case X86::BI__builtin_ia32_roundss:
4487   case X86::BI__builtin_ia32_roundsd:
4488   case X86::BI__builtin_ia32_rangepd128_mask:
4489   case X86::BI__builtin_ia32_rangepd256_mask:
4490   case X86::BI__builtin_ia32_rangepd512_mask:
4491   case X86::BI__builtin_ia32_rangeps128_mask:
4492   case X86::BI__builtin_ia32_rangeps256_mask:
4493   case X86::BI__builtin_ia32_rangeps512_mask:
4494   case X86::BI__builtin_ia32_getmantsd_round_mask:
4495   case X86::BI__builtin_ia32_getmantss_round_mask:
4496   case X86::BI__builtin_ia32_getmantsh_round_mask:
4497   case X86::BI__builtin_ia32_vec_set_v16qi:
4498   case X86::BI__builtin_ia32_vec_set_v16hi:
4499     i = 2; l = 0; u = 15;
4500     break;
4501   case X86::BI__builtin_ia32_vec_ext_v32qi:
4502     i = 1; l = 0; u = 31;
4503     break;
4504   case X86::BI__builtin_ia32_cmpps:
4505   case X86::BI__builtin_ia32_cmpss:
4506   case X86::BI__builtin_ia32_cmppd:
4507   case X86::BI__builtin_ia32_cmpsd:
4508   case X86::BI__builtin_ia32_cmpps256:
4509   case X86::BI__builtin_ia32_cmppd256:
4510   case X86::BI__builtin_ia32_cmpps128_mask:
4511   case X86::BI__builtin_ia32_cmppd128_mask:
4512   case X86::BI__builtin_ia32_cmpps256_mask:
4513   case X86::BI__builtin_ia32_cmppd256_mask:
4514   case X86::BI__builtin_ia32_cmpps512_mask:
4515   case X86::BI__builtin_ia32_cmppd512_mask:
4516   case X86::BI__builtin_ia32_cmpsd_mask:
4517   case X86::BI__builtin_ia32_cmpss_mask:
4518   case X86::BI__builtin_ia32_vec_set_v32qi:
4519     i = 2; l = 0; u = 31;
4520     break;
4521   case X86::BI__builtin_ia32_permdf256:
4522   case X86::BI__builtin_ia32_permdi256:
4523   case X86::BI__builtin_ia32_permdf512:
4524   case X86::BI__builtin_ia32_permdi512:
4525   case X86::BI__builtin_ia32_vpermilps:
4526   case X86::BI__builtin_ia32_vpermilps256:
4527   case X86::BI__builtin_ia32_vpermilpd512:
4528   case X86::BI__builtin_ia32_vpermilps512:
4529   case X86::BI__builtin_ia32_pshufd:
4530   case X86::BI__builtin_ia32_pshufd256:
4531   case X86::BI__builtin_ia32_pshufd512:
4532   case X86::BI__builtin_ia32_pshufhw:
4533   case X86::BI__builtin_ia32_pshufhw256:
4534   case X86::BI__builtin_ia32_pshufhw512:
4535   case X86::BI__builtin_ia32_pshuflw:
4536   case X86::BI__builtin_ia32_pshuflw256:
4537   case X86::BI__builtin_ia32_pshuflw512:
4538   case X86::BI__builtin_ia32_vcvtps2ph:
4539   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4540   case X86::BI__builtin_ia32_vcvtps2ph256:
4541   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4542   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4543   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4544   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4545   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4546   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4547   case X86::BI__builtin_ia32_rndscaleps_mask:
4548   case X86::BI__builtin_ia32_rndscalepd_mask:
4549   case X86::BI__builtin_ia32_rndscaleph_mask:
4550   case X86::BI__builtin_ia32_reducepd128_mask:
4551   case X86::BI__builtin_ia32_reducepd256_mask:
4552   case X86::BI__builtin_ia32_reducepd512_mask:
4553   case X86::BI__builtin_ia32_reduceps128_mask:
4554   case X86::BI__builtin_ia32_reduceps256_mask:
4555   case X86::BI__builtin_ia32_reduceps512_mask:
4556   case X86::BI__builtin_ia32_reduceph128_mask:
4557   case X86::BI__builtin_ia32_reduceph256_mask:
4558   case X86::BI__builtin_ia32_reduceph512_mask:
4559   case X86::BI__builtin_ia32_prold512:
4560   case X86::BI__builtin_ia32_prolq512:
4561   case X86::BI__builtin_ia32_prold128:
4562   case X86::BI__builtin_ia32_prold256:
4563   case X86::BI__builtin_ia32_prolq128:
4564   case X86::BI__builtin_ia32_prolq256:
4565   case X86::BI__builtin_ia32_prord512:
4566   case X86::BI__builtin_ia32_prorq512:
4567   case X86::BI__builtin_ia32_prord128:
4568   case X86::BI__builtin_ia32_prord256:
4569   case X86::BI__builtin_ia32_prorq128:
4570   case X86::BI__builtin_ia32_prorq256:
4571   case X86::BI__builtin_ia32_fpclasspd128_mask:
4572   case X86::BI__builtin_ia32_fpclasspd256_mask:
4573   case X86::BI__builtin_ia32_fpclassps128_mask:
4574   case X86::BI__builtin_ia32_fpclassps256_mask:
4575   case X86::BI__builtin_ia32_fpclassps512_mask:
4576   case X86::BI__builtin_ia32_fpclasspd512_mask:
4577   case X86::BI__builtin_ia32_fpclassph128_mask:
4578   case X86::BI__builtin_ia32_fpclassph256_mask:
4579   case X86::BI__builtin_ia32_fpclassph512_mask:
4580   case X86::BI__builtin_ia32_fpclasssd_mask:
4581   case X86::BI__builtin_ia32_fpclassss_mask:
4582   case X86::BI__builtin_ia32_fpclasssh_mask:
4583   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4584   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4585   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4586   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4587   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4588   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4589   case X86::BI__builtin_ia32_kshiftliqi:
4590   case X86::BI__builtin_ia32_kshiftlihi:
4591   case X86::BI__builtin_ia32_kshiftlisi:
4592   case X86::BI__builtin_ia32_kshiftlidi:
4593   case X86::BI__builtin_ia32_kshiftriqi:
4594   case X86::BI__builtin_ia32_kshiftrihi:
4595   case X86::BI__builtin_ia32_kshiftrisi:
4596   case X86::BI__builtin_ia32_kshiftridi:
4597     i = 1; l = 0; u = 255;
4598     break;
4599   case X86::BI__builtin_ia32_vperm2f128_pd256:
4600   case X86::BI__builtin_ia32_vperm2f128_ps256:
4601   case X86::BI__builtin_ia32_vperm2f128_si256:
4602   case X86::BI__builtin_ia32_permti256:
4603   case X86::BI__builtin_ia32_pblendw128:
4604   case X86::BI__builtin_ia32_pblendw256:
4605   case X86::BI__builtin_ia32_blendps256:
4606   case X86::BI__builtin_ia32_pblendd256:
4607   case X86::BI__builtin_ia32_palignr128:
4608   case X86::BI__builtin_ia32_palignr256:
4609   case X86::BI__builtin_ia32_palignr512:
4610   case X86::BI__builtin_ia32_alignq512:
4611   case X86::BI__builtin_ia32_alignd512:
4612   case X86::BI__builtin_ia32_alignd128:
4613   case X86::BI__builtin_ia32_alignd256:
4614   case X86::BI__builtin_ia32_alignq128:
4615   case X86::BI__builtin_ia32_alignq256:
4616   case X86::BI__builtin_ia32_vcomisd:
4617   case X86::BI__builtin_ia32_vcomiss:
4618   case X86::BI__builtin_ia32_shuf_f32x4:
4619   case X86::BI__builtin_ia32_shuf_f64x2:
4620   case X86::BI__builtin_ia32_shuf_i32x4:
4621   case X86::BI__builtin_ia32_shuf_i64x2:
4622   case X86::BI__builtin_ia32_shufpd512:
4623   case X86::BI__builtin_ia32_shufps:
4624   case X86::BI__builtin_ia32_shufps256:
4625   case X86::BI__builtin_ia32_shufps512:
4626   case X86::BI__builtin_ia32_dbpsadbw128:
4627   case X86::BI__builtin_ia32_dbpsadbw256:
4628   case X86::BI__builtin_ia32_dbpsadbw512:
4629   case X86::BI__builtin_ia32_vpshldd128:
4630   case X86::BI__builtin_ia32_vpshldd256:
4631   case X86::BI__builtin_ia32_vpshldd512:
4632   case X86::BI__builtin_ia32_vpshldq128:
4633   case X86::BI__builtin_ia32_vpshldq256:
4634   case X86::BI__builtin_ia32_vpshldq512:
4635   case X86::BI__builtin_ia32_vpshldw128:
4636   case X86::BI__builtin_ia32_vpshldw256:
4637   case X86::BI__builtin_ia32_vpshldw512:
4638   case X86::BI__builtin_ia32_vpshrdd128:
4639   case X86::BI__builtin_ia32_vpshrdd256:
4640   case X86::BI__builtin_ia32_vpshrdd512:
4641   case X86::BI__builtin_ia32_vpshrdq128:
4642   case X86::BI__builtin_ia32_vpshrdq256:
4643   case X86::BI__builtin_ia32_vpshrdq512:
4644   case X86::BI__builtin_ia32_vpshrdw128:
4645   case X86::BI__builtin_ia32_vpshrdw256:
4646   case X86::BI__builtin_ia32_vpshrdw512:
4647     i = 2; l = 0; u = 255;
4648     break;
4649   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4650   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4651   case X86::BI__builtin_ia32_fixupimmps512_mask:
4652   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4653   case X86::BI__builtin_ia32_fixupimmsd_mask:
4654   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4655   case X86::BI__builtin_ia32_fixupimmss_mask:
4656   case X86::BI__builtin_ia32_fixupimmss_maskz:
4657   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4658   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4659   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4660   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4661   case X86::BI__builtin_ia32_fixupimmps128_mask:
4662   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4663   case X86::BI__builtin_ia32_fixupimmps256_mask:
4664   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4665   case X86::BI__builtin_ia32_pternlogd512_mask:
4666   case X86::BI__builtin_ia32_pternlogd512_maskz:
4667   case X86::BI__builtin_ia32_pternlogq512_mask:
4668   case X86::BI__builtin_ia32_pternlogq512_maskz:
4669   case X86::BI__builtin_ia32_pternlogd128_mask:
4670   case X86::BI__builtin_ia32_pternlogd128_maskz:
4671   case X86::BI__builtin_ia32_pternlogd256_mask:
4672   case X86::BI__builtin_ia32_pternlogd256_maskz:
4673   case X86::BI__builtin_ia32_pternlogq128_mask:
4674   case X86::BI__builtin_ia32_pternlogq128_maskz:
4675   case X86::BI__builtin_ia32_pternlogq256_mask:
4676   case X86::BI__builtin_ia32_pternlogq256_maskz:
4677     i = 3; l = 0; u = 255;
4678     break;
4679   case X86::BI__builtin_ia32_gatherpfdpd:
4680   case X86::BI__builtin_ia32_gatherpfdps:
4681   case X86::BI__builtin_ia32_gatherpfqpd:
4682   case X86::BI__builtin_ia32_gatherpfqps:
4683   case X86::BI__builtin_ia32_scatterpfdpd:
4684   case X86::BI__builtin_ia32_scatterpfdps:
4685   case X86::BI__builtin_ia32_scatterpfqpd:
4686   case X86::BI__builtin_ia32_scatterpfqps:
4687     i = 4; l = 2; u = 3;
4688     break;
4689   case X86::BI__builtin_ia32_reducesd_mask:
4690   case X86::BI__builtin_ia32_reducess_mask:
4691   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4692   case X86::BI__builtin_ia32_rndscaless_round_mask:
4693   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4694   case X86::BI__builtin_ia32_reducesh_mask:
4695     i = 4; l = 0; u = 255;
4696     break;
4697   }
4698 
4699   // Note that we don't force a hard error on the range check here, allowing
4700   // template-generated or macro-generated dead code to potentially have out-of-
4701   // range values. These need to code generate, but don't need to necessarily
4702   // make any sense. We use a warning that defaults to an error.
4703   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4704 }
4705 
4706 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4707 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4708 /// Returns true when the format fits the function and the FormatStringInfo has
4709 /// been populated.
4710 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4711                                FormatStringInfo *FSI) {
4712   FSI->HasVAListArg = Format->getFirstArg() == 0;
4713   FSI->FormatIdx = Format->getFormatIdx() - 1;
4714   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4715 
4716   // The way the format attribute works in GCC, the implicit this argument
4717   // of member functions is counted. However, it doesn't appear in our own
4718   // lists, so decrement format_idx in that case.
4719   if (IsCXXMember) {
4720     if(FSI->FormatIdx == 0)
4721       return false;
4722     --FSI->FormatIdx;
4723     if (FSI->FirstDataArg != 0)
4724       --FSI->FirstDataArg;
4725   }
4726   return true;
4727 }
4728 
4729 /// Checks if a the given expression evaluates to null.
4730 ///
4731 /// Returns true if the value evaluates to null.
4732 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4733   // If the expression has non-null type, it doesn't evaluate to null.
4734   if (auto nullability
4735         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4736     if (*nullability == NullabilityKind::NonNull)
4737       return false;
4738   }
4739 
4740   // As a special case, transparent unions initialized with zero are
4741   // considered null for the purposes of the nonnull attribute.
4742   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4743     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4744       if (const CompoundLiteralExpr *CLE =
4745           dyn_cast<CompoundLiteralExpr>(Expr))
4746         if (const InitListExpr *ILE =
4747             dyn_cast<InitListExpr>(CLE->getInitializer()))
4748           Expr = ILE->getInit(0);
4749   }
4750 
4751   bool Result;
4752   return (!Expr->isValueDependent() &&
4753           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4754           !Result);
4755 }
4756 
4757 static void CheckNonNullArgument(Sema &S,
4758                                  const Expr *ArgExpr,
4759                                  SourceLocation CallSiteLoc) {
4760   if (CheckNonNullExpr(S, ArgExpr))
4761     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4762                           S.PDiag(diag::warn_null_arg)
4763                               << ArgExpr->getSourceRange());
4764 }
4765 
4766 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4767   FormatStringInfo FSI;
4768   if ((GetFormatStringType(Format) == FST_NSString) &&
4769       getFormatStringInfo(Format, false, &FSI)) {
4770     Idx = FSI.FormatIdx;
4771     return true;
4772   }
4773   return false;
4774 }
4775 
4776 /// Diagnose use of %s directive in an NSString which is being passed
4777 /// as formatting string to formatting method.
4778 static void
4779 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4780                                         const NamedDecl *FDecl,
4781                                         Expr **Args,
4782                                         unsigned NumArgs) {
4783   unsigned Idx = 0;
4784   bool Format = false;
4785   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4786   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4787     Idx = 2;
4788     Format = true;
4789   }
4790   else
4791     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4792       if (S.GetFormatNSStringIdx(I, Idx)) {
4793         Format = true;
4794         break;
4795       }
4796     }
4797   if (!Format || NumArgs <= Idx)
4798     return;
4799   const Expr *FormatExpr = Args[Idx];
4800   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4801     FormatExpr = CSCE->getSubExpr();
4802   const StringLiteral *FormatString;
4803   if (const ObjCStringLiteral *OSL =
4804       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4805     FormatString = OSL->getString();
4806   else
4807     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4808   if (!FormatString)
4809     return;
4810   if (S.FormatStringHasSArg(FormatString)) {
4811     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4812       << "%s" << 1 << 1;
4813     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4814       << FDecl->getDeclName();
4815   }
4816 }
4817 
4818 /// Determine whether the given type has a non-null nullability annotation.
4819 static bool isNonNullType(ASTContext &ctx, QualType type) {
4820   if (auto nullability = type->getNullability(ctx))
4821     return *nullability == NullabilityKind::NonNull;
4822 
4823   return false;
4824 }
4825 
4826 static void CheckNonNullArguments(Sema &S,
4827                                   const NamedDecl *FDecl,
4828                                   const FunctionProtoType *Proto,
4829                                   ArrayRef<const Expr *> Args,
4830                                   SourceLocation CallSiteLoc) {
4831   assert((FDecl || Proto) && "Need a function declaration or prototype");
4832 
4833   // Already checked by by constant evaluator.
4834   if (S.isConstantEvaluated())
4835     return;
4836   // Check the attributes attached to the method/function itself.
4837   llvm::SmallBitVector NonNullArgs;
4838   if (FDecl) {
4839     // Handle the nonnull attribute on the function/method declaration itself.
4840     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4841       if (!NonNull->args_size()) {
4842         // Easy case: all pointer arguments are nonnull.
4843         for (const auto *Arg : Args)
4844           if (S.isValidPointerAttrType(Arg->getType()))
4845             CheckNonNullArgument(S, Arg, CallSiteLoc);
4846         return;
4847       }
4848 
4849       for (const ParamIdx &Idx : NonNull->args()) {
4850         unsigned IdxAST = Idx.getASTIndex();
4851         if (IdxAST >= Args.size())
4852           continue;
4853         if (NonNullArgs.empty())
4854           NonNullArgs.resize(Args.size());
4855         NonNullArgs.set(IdxAST);
4856       }
4857     }
4858   }
4859 
4860   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4861     // Handle the nonnull attribute on the parameters of the
4862     // function/method.
4863     ArrayRef<ParmVarDecl*> parms;
4864     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4865       parms = FD->parameters();
4866     else
4867       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4868 
4869     unsigned ParamIndex = 0;
4870     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4871          I != E; ++I, ++ParamIndex) {
4872       const ParmVarDecl *PVD = *I;
4873       if (PVD->hasAttr<NonNullAttr>() ||
4874           isNonNullType(S.Context, PVD->getType())) {
4875         if (NonNullArgs.empty())
4876           NonNullArgs.resize(Args.size());
4877 
4878         NonNullArgs.set(ParamIndex);
4879       }
4880     }
4881   } else {
4882     // If we have a non-function, non-method declaration but no
4883     // function prototype, try to dig out the function prototype.
4884     if (!Proto) {
4885       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4886         QualType type = VD->getType().getNonReferenceType();
4887         if (auto pointerType = type->getAs<PointerType>())
4888           type = pointerType->getPointeeType();
4889         else if (auto blockType = type->getAs<BlockPointerType>())
4890           type = blockType->getPointeeType();
4891         // FIXME: data member pointers?
4892 
4893         // Dig out the function prototype, if there is one.
4894         Proto = type->getAs<FunctionProtoType>();
4895       }
4896     }
4897 
4898     // Fill in non-null argument information from the nullability
4899     // information on the parameter types (if we have them).
4900     if (Proto) {
4901       unsigned Index = 0;
4902       for (auto paramType : Proto->getParamTypes()) {
4903         if (isNonNullType(S.Context, paramType)) {
4904           if (NonNullArgs.empty())
4905             NonNullArgs.resize(Args.size());
4906 
4907           NonNullArgs.set(Index);
4908         }
4909 
4910         ++Index;
4911       }
4912     }
4913   }
4914 
4915   // Check for non-null arguments.
4916   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4917        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4918     if (NonNullArgs[ArgIndex])
4919       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4920   }
4921 }
4922 
4923 /// Warn if a pointer or reference argument passed to a function points to an
4924 /// object that is less aligned than the parameter. This can happen when
4925 /// creating a typedef with a lower alignment than the original type and then
4926 /// calling functions defined in terms of the original type.
4927 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4928                              StringRef ParamName, QualType ArgTy,
4929                              QualType ParamTy) {
4930 
4931   // If a function accepts a pointer or reference type
4932   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4933     return;
4934 
4935   // If the parameter is a pointer type, get the pointee type for the
4936   // argument too. If the parameter is a reference type, don't try to get
4937   // the pointee type for the argument.
4938   if (ParamTy->isPointerType())
4939     ArgTy = ArgTy->getPointeeType();
4940 
4941   // Remove reference or pointer
4942   ParamTy = ParamTy->getPointeeType();
4943 
4944   // Find expected alignment, and the actual alignment of the passed object.
4945   // getTypeAlignInChars requires complete types
4946   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4947       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4948       ArgTy->isUndeducedType())
4949     return;
4950 
4951   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4952   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4953 
4954   // If the argument is less aligned than the parameter, there is a
4955   // potential alignment issue.
4956   if (ArgAlign < ParamAlign)
4957     Diag(Loc, diag::warn_param_mismatched_alignment)
4958         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4959         << ParamName << FDecl;
4960 }
4961 
4962 /// Handles the checks for format strings, non-POD arguments to vararg
4963 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4964 /// attributes.
4965 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4966                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4967                      bool IsMemberFunction, SourceLocation Loc,
4968                      SourceRange Range, VariadicCallType CallType) {
4969   // FIXME: We should check as much as we can in the template definition.
4970   if (CurContext->isDependentContext())
4971     return;
4972 
4973   // Printf and scanf checking.
4974   llvm::SmallBitVector CheckedVarArgs;
4975   if (FDecl) {
4976     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4977       // Only create vector if there are format attributes.
4978       CheckedVarArgs.resize(Args.size());
4979 
4980       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4981                            CheckedVarArgs);
4982     }
4983   }
4984 
4985   // Refuse POD arguments that weren't caught by the format string
4986   // checks above.
4987   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4988   if (CallType != VariadicDoesNotApply &&
4989       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4990     unsigned NumParams = Proto ? Proto->getNumParams()
4991                        : FDecl && isa<FunctionDecl>(FDecl)
4992                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4993                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4994                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4995                        : 0;
4996 
4997     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4998       // Args[ArgIdx] can be null in malformed code.
4999       if (const Expr *Arg = Args[ArgIdx]) {
5000         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5001           checkVariadicArgument(Arg, CallType);
5002       }
5003     }
5004   }
5005 
5006   if (FDecl || Proto) {
5007     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5008 
5009     // Type safety checking.
5010     if (FDecl) {
5011       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5012         CheckArgumentWithTypeTag(I, Args, Loc);
5013     }
5014   }
5015 
5016   // Check that passed arguments match the alignment of original arguments.
5017   // Try to get the missing prototype from the declaration.
5018   if (!Proto && FDecl) {
5019     const auto *FT = FDecl->getFunctionType();
5020     if (isa_and_nonnull<FunctionProtoType>(FT))
5021       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5022   }
5023   if (Proto) {
5024     // For variadic functions, we may have more args than parameters.
5025     // For some K&R functions, we may have less args than parameters.
5026     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5027     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5028       // Args[ArgIdx] can be null in malformed code.
5029       if (const Expr *Arg = Args[ArgIdx]) {
5030         if (Arg->containsErrors())
5031           continue;
5032 
5033         QualType ParamTy = Proto->getParamType(ArgIdx);
5034         QualType ArgTy = Arg->getType();
5035         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5036                           ArgTy, ParamTy);
5037       }
5038     }
5039   }
5040 
5041   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5042     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5043     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5044     if (!Arg->isValueDependent()) {
5045       Expr::EvalResult Align;
5046       if (Arg->EvaluateAsInt(Align, Context)) {
5047         const llvm::APSInt &I = Align.Val.getInt();
5048         if (!I.isPowerOf2())
5049           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5050               << Arg->getSourceRange();
5051 
5052         if (I > Sema::MaximumAlignment)
5053           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5054               << Arg->getSourceRange() << Sema::MaximumAlignment;
5055       }
5056     }
5057   }
5058 
5059   if (FD)
5060     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5061 }
5062 
5063 /// CheckConstructorCall - Check a constructor call for correctness and safety
5064 /// properties not enforced by the C type system.
5065 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5066                                 ArrayRef<const Expr *> Args,
5067                                 const FunctionProtoType *Proto,
5068                                 SourceLocation Loc) {
5069   VariadicCallType CallType =
5070       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5071 
5072   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5073   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5074                     Context.getPointerType(Ctor->getThisObjectType()));
5075 
5076   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5077             Loc, SourceRange(), CallType);
5078 }
5079 
5080 /// CheckFunctionCall - Check a direct function call for various correctness
5081 /// and safety properties not strictly enforced by the C type system.
5082 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5083                              const FunctionProtoType *Proto) {
5084   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5085                               isa<CXXMethodDecl>(FDecl);
5086   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5087                           IsMemberOperatorCall;
5088   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5089                                                   TheCall->getCallee());
5090   Expr** Args = TheCall->getArgs();
5091   unsigned NumArgs = TheCall->getNumArgs();
5092 
5093   Expr *ImplicitThis = nullptr;
5094   if (IsMemberOperatorCall) {
5095     // If this is a call to a member operator, hide the first argument
5096     // from checkCall.
5097     // FIXME: Our choice of AST representation here is less than ideal.
5098     ImplicitThis = Args[0];
5099     ++Args;
5100     --NumArgs;
5101   } else if (IsMemberFunction)
5102     ImplicitThis =
5103         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5104 
5105   if (ImplicitThis) {
5106     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5107     // used.
5108     QualType ThisType = ImplicitThis->getType();
5109     if (!ThisType->isPointerType()) {
5110       assert(!ThisType->isReferenceType());
5111       ThisType = Context.getPointerType(ThisType);
5112     }
5113 
5114     QualType ThisTypeFromDecl =
5115         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5116 
5117     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5118                       ThisTypeFromDecl);
5119   }
5120 
5121   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5122             IsMemberFunction, TheCall->getRParenLoc(),
5123             TheCall->getCallee()->getSourceRange(), CallType);
5124 
5125   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5126   // None of the checks below are needed for functions that don't have
5127   // simple names (e.g., C++ conversion functions).
5128   if (!FnInfo)
5129     return false;
5130 
5131   CheckTCBEnforcement(TheCall, FDecl);
5132 
5133   CheckAbsoluteValueFunction(TheCall, FDecl);
5134   CheckMaxUnsignedZero(TheCall, FDecl);
5135 
5136   if (getLangOpts().ObjC)
5137     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5138 
5139   unsigned CMId = FDecl->getMemoryFunctionKind();
5140 
5141   // Handle memory setting and copying functions.
5142   switch (CMId) {
5143   case 0:
5144     return false;
5145   case Builtin::BIstrlcpy: // fallthrough
5146   case Builtin::BIstrlcat:
5147     CheckStrlcpycatArguments(TheCall, FnInfo);
5148     break;
5149   case Builtin::BIstrncat:
5150     CheckStrncatArguments(TheCall, FnInfo);
5151     break;
5152   case Builtin::BIfree:
5153     CheckFreeArguments(TheCall);
5154     break;
5155   default:
5156     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5157   }
5158 
5159   return false;
5160 }
5161 
5162 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5163                                ArrayRef<const Expr *> Args) {
5164   VariadicCallType CallType =
5165       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5166 
5167   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5168             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5169             CallType);
5170 
5171   return false;
5172 }
5173 
5174 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5175                             const FunctionProtoType *Proto) {
5176   QualType Ty;
5177   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5178     Ty = V->getType().getNonReferenceType();
5179   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5180     Ty = F->getType().getNonReferenceType();
5181   else
5182     return false;
5183 
5184   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5185       !Ty->isFunctionProtoType())
5186     return false;
5187 
5188   VariadicCallType CallType;
5189   if (!Proto || !Proto->isVariadic()) {
5190     CallType = VariadicDoesNotApply;
5191   } else if (Ty->isBlockPointerType()) {
5192     CallType = VariadicBlock;
5193   } else { // Ty->isFunctionPointerType()
5194     CallType = VariadicFunction;
5195   }
5196 
5197   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5198             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5199             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5200             TheCall->getCallee()->getSourceRange(), CallType);
5201 
5202   return false;
5203 }
5204 
5205 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5206 /// such as function pointers returned from functions.
5207 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5208   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5209                                                   TheCall->getCallee());
5210   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5211             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5212             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5213             TheCall->getCallee()->getSourceRange(), CallType);
5214 
5215   return false;
5216 }
5217 
5218 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5219   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5220     return false;
5221 
5222   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5223   switch (Op) {
5224   case AtomicExpr::AO__c11_atomic_init:
5225   case AtomicExpr::AO__opencl_atomic_init:
5226     llvm_unreachable("There is no ordering argument for an init");
5227 
5228   case AtomicExpr::AO__c11_atomic_load:
5229   case AtomicExpr::AO__opencl_atomic_load:
5230   case AtomicExpr::AO__atomic_load_n:
5231   case AtomicExpr::AO__atomic_load:
5232     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5233            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5234 
5235   case AtomicExpr::AO__c11_atomic_store:
5236   case AtomicExpr::AO__opencl_atomic_store:
5237   case AtomicExpr::AO__atomic_store:
5238   case AtomicExpr::AO__atomic_store_n:
5239     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5240            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5241            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5242 
5243   default:
5244     return true;
5245   }
5246 }
5247 
5248 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5249                                          AtomicExpr::AtomicOp Op) {
5250   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5251   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5252   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5253   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5254                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5255                          Op);
5256 }
5257 
5258 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5259                                  SourceLocation RParenLoc, MultiExprArg Args,
5260                                  AtomicExpr::AtomicOp Op,
5261                                  AtomicArgumentOrder ArgOrder) {
5262   // All the non-OpenCL operations take one of the following forms.
5263   // The OpenCL operations take the __c11 forms with one extra argument for
5264   // synchronization scope.
5265   enum {
5266     // C    __c11_atomic_init(A *, C)
5267     Init,
5268 
5269     // C    __c11_atomic_load(A *, int)
5270     Load,
5271 
5272     // void __atomic_load(A *, CP, int)
5273     LoadCopy,
5274 
5275     // void __atomic_store(A *, CP, int)
5276     Copy,
5277 
5278     // C    __c11_atomic_add(A *, M, int)
5279     Arithmetic,
5280 
5281     // C    __atomic_exchange_n(A *, CP, int)
5282     Xchg,
5283 
5284     // void __atomic_exchange(A *, C *, CP, int)
5285     GNUXchg,
5286 
5287     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5288     C11CmpXchg,
5289 
5290     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5291     GNUCmpXchg
5292   } Form = Init;
5293 
5294   const unsigned NumForm = GNUCmpXchg + 1;
5295   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5296   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5297   // where:
5298   //   C is an appropriate type,
5299   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5300   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5301   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5302   //   the int parameters are for orderings.
5303 
5304   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5305       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5306       "need to update code for modified forms");
5307   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5308                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5309                         AtomicExpr::AO__atomic_load,
5310                 "need to update code for modified C11 atomics");
5311   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5312                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5313   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5314                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5315                IsOpenCL;
5316   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5317              Op == AtomicExpr::AO__atomic_store_n ||
5318              Op == AtomicExpr::AO__atomic_exchange_n ||
5319              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5320   bool IsAddSub = false;
5321 
5322   switch (Op) {
5323   case AtomicExpr::AO__c11_atomic_init:
5324   case AtomicExpr::AO__opencl_atomic_init:
5325     Form = Init;
5326     break;
5327 
5328   case AtomicExpr::AO__c11_atomic_load:
5329   case AtomicExpr::AO__opencl_atomic_load:
5330   case AtomicExpr::AO__atomic_load_n:
5331     Form = Load;
5332     break;
5333 
5334   case AtomicExpr::AO__atomic_load:
5335     Form = LoadCopy;
5336     break;
5337 
5338   case AtomicExpr::AO__c11_atomic_store:
5339   case AtomicExpr::AO__opencl_atomic_store:
5340   case AtomicExpr::AO__atomic_store:
5341   case AtomicExpr::AO__atomic_store_n:
5342     Form = Copy;
5343     break;
5344 
5345   case AtomicExpr::AO__c11_atomic_fetch_add:
5346   case AtomicExpr::AO__c11_atomic_fetch_sub:
5347   case AtomicExpr::AO__opencl_atomic_fetch_add:
5348   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5349   case AtomicExpr::AO__atomic_fetch_add:
5350   case AtomicExpr::AO__atomic_fetch_sub:
5351   case AtomicExpr::AO__atomic_add_fetch:
5352   case AtomicExpr::AO__atomic_sub_fetch:
5353     IsAddSub = true;
5354     Form = Arithmetic;
5355     break;
5356   case AtomicExpr::AO__c11_atomic_fetch_and:
5357   case AtomicExpr::AO__c11_atomic_fetch_or:
5358   case AtomicExpr::AO__c11_atomic_fetch_xor:
5359   case AtomicExpr::AO__opencl_atomic_fetch_and:
5360   case AtomicExpr::AO__opencl_atomic_fetch_or:
5361   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5362   case AtomicExpr::AO__atomic_fetch_and:
5363   case AtomicExpr::AO__atomic_fetch_or:
5364   case AtomicExpr::AO__atomic_fetch_xor:
5365   case AtomicExpr::AO__atomic_fetch_nand:
5366   case AtomicExpr::AO__atomic_and_fetch:
5367   case AtomicExpr::AO__atomic_or_fetch:
5368   case AtomicExpr::AO__atomic_xor_fetch:
5369   case AtomicExpr::AO__atomic_nand_fetch:
5370     Form = Arithmetic;
5371     break;
5372   case AtomicExpr::AO__c11_atomic_fetch_min:
5373   case AtomicExpr::AO__c11_atomic_fetch_max:
5374   case AtomicExpr::AO__opencl_atomic_fetch_min:
5375   case AtomicExpr::AO__opencl_atomic_fetch_max:
5376   case AtomicExpr::AO__atomic_min_fetch:
5377   case AtomicExpr::AO__atomic_max_fetch:
5378   case AtomicExpr::AO__atomic_fetch_min:
5379   case AtomicExpr::AO__atomic_fetch_max:
5380     Form = Arithmetic;
5381     break;
5382 
5383   case AtomicExpr::AO__c11_atomic_exchange:
5384   case AtomicExpr::AO__opencl_atomic_exchange:
5385   case AtomicExpr::AO__atomic_exchange_n:
5386     Form = Xchg;
5387     break;
5388 
5389   case AtomicExpr::AO__atomic_exchange:
5390     Form = GNUXchg;
5391     break;
5392 
5393   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5394   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5395   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5396   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5397     Form = C11CmpXchg;
5398     break;
5399 
5400   case AtomicExpr::AO__atomic_compare_exchange:
5401   case AtomicExpr::AO__atomic_compare_exchange_n:
5402     Form = GNUCmpXchg;
5403     break;
5404   }
5405 
5406   unsigned AdjustedNumArgs = NumArgs[Form];
5407   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5408     ++AdjustedNumArgs;
5409   // Check we have the right number of arguments.
5410   if (Args.size() < AdjustedNumArgs) {
5411     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5412         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5413         << ExprRange;
5414     return ExprError();
5415   } else if (Args.size() > AdjustedNumArgs) {
5416     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5417          diag::err_typecheck_call_too_many_args)
5418         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5419         << ExprRange;
5420     return ExprError();
5421   }
5422 
5423   // Inspect the first argument of the atomic operation.
5424   Expr *Ptr = Args[0];
5425   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5426   if (ConvertedPtr.isInvalid())
5427     return ExprError();
5428 
5429   Ptr = ConvertedPtr.get();
5430   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5431   if (!pointerType) {
5432     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5433         << Ptr->getType() << Ptr->getSourceRange();
5434     return ExprError();
5435   }
5436 
5437   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5438   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5439   QualType ValType = AtomTy; // 'C'
5440   if (IsC11) {
5441     if (!AtomTy->isAtomicType()) {
5442       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5443           << Ptr->getType() << Ptr->getSourceRange();
5444       return ExprError();
5445     }
5446     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5447         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5448       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5449           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5450           << Ptr->getSourceRange();
5451       return ExprError();
5452     }
5453     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5454   } else if (Form != Load && Form != LoadCopy) {
5455     if (ValType.isConstQualified()) {
5456       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5457           << Ptr->getType() << Ptr->getSourceRange();
5458       return ExprError();
5459     }
5460   }
5461 
5462   // For an arithmetic operation, the implied arithmetic must be well-formed.
5463   if (Form == Arithmetic) {
5464     // gcc does not enforce these rules for GNU atomics, but we do so for
5465     // sanity.
5466     auto IsAllowedValueType = [&](QualType ValType) {
5467       if (ValType->isIntegerType())
5468         return true;
5469       if (ValType->isPointerType())
5470         return true;
5471       if (!ValType->isFloatingType())
5472         return false;
5473       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5474       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5475           &Context.getTargetInfo().getLongDoubleFormat() ==
5476               &llvm::APFloat::x87DoubleExtended())
5477         return false;
5478       return true;
5479     };
5480     if (IsAddSub && !IsAllowedValueType(ValType)) {
5481       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5482           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5483       return ExprError();
5484     }
5485     if (!IsAddSub && !ValType->isIntegerType()) {
5486       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5487           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5488       return ExprError();
5489     }
5490     if (IsC11 && ValType->isPointerType() &&
5491         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5492                             diag::err_incomplete_type)) {
5493       return ExprError();
5494     }
5495   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5496     // For __atomic_*_n operations, the value type must be a scalar integral or
5497     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5498     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5499         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5500     return ExprError();
5501   }
5502 
5503   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5504       !AtomTy->isScalarType()) {
5505     // For GNU atomics, require a trivially-copyable type. This is not part of
5506     // the GNU atomics specification, but we enforce it for sanity.
5507     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5508         << Ptr->getType() << Ptr->getSourceRange();
5509     return ExprError();
5510   }
5511 
5512   switch (ValType.getObjCLifetime()) {
5513   case Qualifiers::OCL_None:
5514   case Qualifiers::OCL_ExplicitNone:
5515     // okay
5516     break;
5517 
5518   case Qualifiers::OCL_Weak:
5519   case Qualifiers::OCL_Strong:
5520   case Qualifiers::OCL_Autoreleasing:
5521     // FIXME: Can this happen? By this point, ValType should be known
5522     // to be trivially copyable.
5523     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5524         << ValType << Ptr->getSourceRange();
5525     return ExprError();
5526   }
5527 
5528   // All atomic operations have an overload which takes a pointer to a volatile
5529   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5530   // into the result or the other operands. Similarly atomic_load takes a
5531   // pointer to a const 'A'.
5532   ValType.removeLocalVolatile();
5533   ValType.removeLocalConst();
5534   QualType ResultType = ValType;
5535   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5536       Form == Init)
5537     ResultType = Context.VoidTy;
5538   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5539     ResultType = Context.BoolTy;
5540 
5541   // The type of a parameter passed 'by value'. In the GNU atomics, such
5542   // arguments are actually passed as pointers.
5543   QualType ByValType = ValType; // 'CP'
5544   bool IsPassedByAddress = false;
5545   if (!IsC11 && !IsN) {
5546     ByValType = Ptr->getType();
5547     IsPassedByAddress = true;
5548   }
5549 
5550   SmallVector<Expr *, 5> APIOrderedArgs;
5551   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5552     APIOrderedArgs.push_back(Args[0]);
5553     switch (Form) {
5554     case Init:
5555     case Load:
5556       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5557       break;
5558     case LoadCopy:
5559     case Copy:
5560     case Arithmetic:
5561     case Xchg:
5562       APIOrderedArgs.push_back(Args[2]); // Val1
5563       APIOrderedArgs.push_back(Args[1]); // Order
5564       break;
5565     case GNUXchg:
5566       APIOrderedArgs.push_back(Args[2]); // Val1
5567       APIOrderedArgs.push_back(Args[3]); // Val2
5568       APIOrderedArgs.push_back(Args[1]); // Order
5569       break;
5570     case C11CmpXchg:
5571       APIOrderedArgs.push_back(Args[2]); // Val1
5572       APIOrderedArgs.push_back(Args[4]); // Val2
5573       APIOrderedArgs.push_back(Args[1]); // Order
5574       APIOrderedArgs.push_back(Args[3]); // OrderFail
5575       break;
5576     case GNUCmpXchg:
5577       APIOrderedArgs.push_back(Args[2]); // Val1
5578       APIOrderedArgs.push_back(Args[4]); // Val2
5579       APIOrderedArgs.push_back(Args[5]); // Weak
5580       APIOrderedArgs.push_back(Args[1]); // Order
5581       APIOrderedArgs.push_back(Args[3]); // OrderFail
5582       break;
5583     }
5584   } else
5585     APIOrderedArgs.append(Args.begin(), Args.end());
5586 
5587   // The first argument's non-CV pointer type is used to deduce the type of
5588   // subsequent arguments, except for:
5589   //  - weak flag (always converted to bool)
5590   //  - memory order (always converted to int)
5591   //  - scope  (always converted to int)
5592   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5593     QualType Ty;
5594     if (i < NumVals[Form] + 1) {
5595       switch (i) {
5596       case 0:
5597         // The first argument is always a pointer. It has a fixed type.
5598         // It is always dereferenced, a nullptr is undefined.
5599         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5600         // Nothing else to do: we already know all we want about this pointer.
5601         continue;
5602       case 1:
5603         // The second argument is the non-atomic operand. For arithmetic, this
5604         // is always passed by value, and for a compare_exchange it is always
5605         // passed by address. For the rest, GNU uses by-address and C11 uses
5606         // by-value.
5607         assert(Form != Load);
5608         if (Form == Arithmetic && ValType->isPointerType())
5609           Ty = Context.getPointerDiffType();
5610         else if (Form == Init || Form == Arithmetic)
5611           Ty = ValType;
5612         else if (Form == Copy || Form == Xchg) {
5613           if (IsPassedByAddress) {
5614             // The value pointer is always dereferenced, a nullptr is undefined.
5615             CheckNonNullArgument(*this, APIOrderedArgs[i],
5616                                  ExprRange.getBegin());
5617           }
5618           Ty = ByValType;
5619         } else {
5620           Expr *ValArg = APIOrderedArgs[i];
5621           // The value pointer is always dereferenced, a nullptr is undefined.
5622           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5623           LangAS AS = LangAS::Default;
5624           // Keep address space of non-atomic pointer type.
5625           if (const PointerType *PtrTy =
5626                   ValArg->getType()->getAs<PointerType>()) {
5627             AS = PtrTy->getPointeeType().getAddressSpace();
5628           }
5629           Ty = Context.getPointerType(
5630               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5631         }
5632         break;
5633       case 2:
5634         // The third argument to compare_exchange / GNU exchange is the desired
5635         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5636         if (IsPassedByAddress)
5637           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5638         Ty = ByValType;
5639         break;
5640       case 3:
5641         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5642         Ty = Context.BoolTy;
5643         break;
5644       }
5645     } else {
5646       // The order(s) and scope are always converted to int.
5647       Ty = Context.IntTy;
5648     }
5649 
5650     InitializedEntity Entity =
5651         InitializedEntity::InitializeParameter(Context, Ty, false);
5652     ExprResult Arg = APIOrderedArgs[i];
5653     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5654     if (Arg.isInvalid())
5655       return true;
5656     APIOrderedArgs[i] = Arg.get();
5657   }
5658 
5659   // Permute the arguments into a 'consistent' order.
5660   SmallVector<Expr*, 5> SubExprs;
5661   SubExprs.push_back(Ptr);
5662   switch (Form) {
5663   case Init:
5664     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5665     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5666     break;
5667   case Load:
5668     SubExprs.push_back(APIOrderedArgs[1]); // Order
5669     break;
5670   case LoadCopy:
5671   case Copy:
5672   case Arithmetic:
5673   case Xchg:
5674     SubExprs.push_back(APIOrderedArgs[2]); // Order
5675     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5676     break;
5677   case GNUXchg:
5678     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5679     SubExprs.push_back(APIOrderedArgs[3]); // Order
5680     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5681     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5682     break;
5683   case C11CmpXchg:
5684     SubExprs.push_back(APIOrderedArgs[3]); // Order
5685     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5686     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5687     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5688     break;
5689   case GNUCmpXchg:
5690     SubExprs.push_back(APIOrderedArgs[4]); // Order
5691     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5692     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5693     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5694     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5695     break;
5696   }
5697 
5698   if (SubExprs.size() >= 2 && Form != Init) {
5699     if (Optional<llvm::APSInt> Result =
5700             SubExprs[1]->getIntegerConstantExpr(Context))
5701       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5702         Diag(SubExprs[1]->getBeginLoc(),
5703              diag::warn_atomic_op_has_invalid_memory_order)
5704             << SubExprs[1]->getSourceRange();
5705   }
5706 
5707   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5708     auto *Scope = Args[Args.size() - 1];
5709     if (Optional<llvm::APSInt> Result =
5710             Scope->getIntegerConstantExpr(Context)) {
5711       if (!ScopeModel->isValid(Result->getZExtValue()))
5712         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5713             << Scope->getSourceRange();
5714     }
5715     SubExprs.push_back(Scope);
5716   }
5717 
5718   AtomicExpr *AE = new (Context)
5719       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5720 
5721   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5722        Op == AtomicExpr::AO__c11_atomic_store ||
5723        Op == AtomicExpr::AO__opencl_atomic_load ||
5724        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5725       Context.AtomicUsesUnsupportedLibcall(AE))
5726     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5727         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5728              Op == AtomicExpr::AO__opencl_atomic_load)
5729                 ? 0
5730                 : 1);
5731 
5732   if (ValType->isExtIntType()) {
5733     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5734     return ExprError();
5735   }
5736 
5737   return AE;
5738 }
5739 
5740 /// checkBuiltinArgument - Given a call to a builtin function, perform
5741 /// normal type-checking on the given argument, updating the call in
5742 /// place.  This is useful when a builtin function requires custom
5743 /// type-checking for some of its arguments but not necessarily all of
5744 /// them.
5745 ///
5746 /// Returns true on error.
5747 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5748   FunctionDecl *Fn = E->getDirectCallee();
5749   assert(Fn && "builtin call without direct callee!");
5750 
5751   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5752   InitializedEntity Entity =
5753     InitializedEntity::InitializeParameter(S.Context, Param);
5754 
5755   ExprResult Arg = E->getArg(0);
5756   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5757   if (Arg.isInvalid())
5758     return true;
5759 
5760   E->setArg(ArgIndex, Arg.get());
5761   return false;
5762 }
5763 
5764 /// We have a call to a function like __sync_fetch_and_add, which is an
5765 /// overloaded function based on the pointer type of its first argument.
5766 /// The main BuildCallExpr routines have already promoted the types of
5767 /// arguments because all of these calls are prototyped as void(...).
5768 ///
5769 /// This function goes through and does final semantic checking for these
5770 /// builtins, as well as generating any warnings.
5771 ExprResult
5772 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5773   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5774   Expr *Callee = TheCall->getCallee();
5775   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5776   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5777 
5778   // Ensure that we have at least one argument to do type inference from.
5779   if (TheCall->getNumArgs() < 1) {
5780     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5781         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5782     return ExprError();
5783   }
5784 
5785   // Inspect the first argument of the atomic builtin.  This should always be
5786   // a pointer type, whose element is an integral scalar or pointer type.
5787   // Because it is a pointer type, we don't have to worry about any implicit
5788   // casts here.
5789   // FIXME: We don't allow floating point scalars as input.
5790   Expr *FirstArg = TheCall->getArg(0);
5791   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5792   if (FirstArgResult.isInvalid())
5793     return ExprError();
5794   FirstArg = FirstArgResult.get();
5795   TheCall->setArg(0, FirstArg);
5796 
5797   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5798   if (!pointerType) {
5799     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5800         << FirstArg->getType() << FirstArg->getSourceRange();
5801     return ExprError();
5802   }
5803 
5804   QualType ValType = pointerType->getPointeeType();
5805   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5806       !ValType->isBlockPointerType()) {
5807     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5808         << FirstArg->getType() << FirstArg->getSourceRange();
5809     return ExprError();
5810   }
5811 
5812   if (ValType.isConstQualified()) {
5813     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5814         << FirstArg->getType() << FirstArg->getSourceRange();
5815     return ExprError();
5816   }
5817 
5818   switch (ValType.getObjCLifetime()) {
5819   case Qualifiers::OCL_None:
5820   case Qualifiers::OCL_ExplicitNone:
5821     // okay
5822     break;
5823 
5824   case Qualifiers::OCL_Weak:
5825   case Qualifiers::OCL_Strong:
5826   case Qualifiers::OCL_Autoreleasing:
5827     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5828         << ValType << FirstArg->getSourceRange();
5829     return ExprError();
5830   }
5831 
5832   // Strip any qualifiers off ValType.
5833   ValType = ValType.getUnqualifiedType();
5834 
5835   // The majority of builtins return a value, but a few have special return
5836   // types, so allow them to override appropriately below.
5837   QualType ResultType = ValType;
5838 
5839   // We need to figure out which concrete builtin this maps onto.  For example,
5840   // __sync_fetch_and_add with a 2 byte object turns into
5841   // __sync_fetch_and_add_2.
5842 #define BUILTIN_ROW(x) \
5843   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5844     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5845 
5846   static const unsigned BuiltinIndices[][5] = {
5847     BUILTIN_ROW(__sync_fetch_and_add),
5848     BUILTIN_ROW(__sync_fetch_and_sub),
5849     BUILTIN_ROW(__sync_fetch_and_or),
5850     BUILTIN_ROW(__sync_fetch_and_and),
5851     BUILTIN_ROW(__sync_fetch_and_xor),
5852     BUILTIN_ROW(__sync_fetch_and_nand),
5853 
5854     BUILTIN_ROW(__sync_add_and_fetch),
5855     BUILTIN_ROW(__sync_sub_and_fetch),
5856     BUILTIN_ROW(__sync_and_and_fetch),
5857     BUILTIN_ROW(__sync_or_and_fetch),
5858     BUILTIN_ROW(__sync_xor_and_fetch),
5859     BUILTIN_ROW(__sync_nand_and_fetch),
5860 
5861     BUILTIN_ROW(__sync_val_compare_and_swap),
5862     BUILTIN_ROW(__sync_bool_compare_and_swap),
5863     BUILTIN_ROW(__sync_lock_test_and_set),
5864     BUILTIN_ROW(__sync_lock_release),
5865     BUILTIN_ROW(__sync_swap)
5866   };
5867 #undef BUILTIN_ROW
5868 
5869   // Determine the index of the size.
5870   unsigned SizeIndex;
5871   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5872   case 1: SizeIndex = 0; break;
5873   case 2: SizeIndex = 1; break;
5874   case 4: SizeIndex = 2; break;
5875   case 8: SizeIndex = 3; break;
5876   case 16: SizeIndex = 4; break;
5877   default:
5878     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5879         << FirstArg->getType() << FirstArg->getSourceRange();
5880     return ExprError();
5881   }
5882 
5883   // Each of these builtins has one pointer argument, followed by some number of
5884   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5885   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5886   // as the number of fixed args.
5887   unsigned BuiltinID = FDecl->getBuiltinID();
5888   unsigned BuiltinIndex, NumFixed = 1;
5889   bool WarnAboutSemanticsChange = false;
5890   switch (BuiltinID) {
5891   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5892   case Builtin::BI__sync_fetch_and_add:
5893   case Builtin::BI__sync_fetch_and_add_1:
5894   case Builtin::BI__sync_fetch_and_add_2:
5895   case Builtin::BI__sync_fetch_and_add_4:
5896   case Builtin::BI__sync_fetch_and_add_8:
5897   case Builtin::BI__sync_fetch_and_add_16:
5898     BuiltinIndex = 0;
5899     break;
5900 
5901   case Builtin::BI__sync_fetch_and_sub:
5902   case Builtin::BI__sync_fetch_and_sub_1:
5903   case Builtin::BI__sync_fetch_and_sub_2:
5904   case Builtin::BI__sync_fetch_and_sub_4:
5905   case Builtin::BI__sync_fetch_and_sub_8:
5906   case Builtin::BI__sync_fetch_and_sub_16:
5907     BuiltinIndex = 1;
5908     break;
5909 
5910   case Builtin::BI__sync_fetch_and_or:
5911   case Builtin::BI__sync_fetch_and_or_1:
5912   case Builtin::BI__sync_fetch_and_or_2:
5913   case Builtin::BI__sync_fetch_and_or_4:
5914   case Builtin::BI__sync_fetch_and_or_8:
5915   case Builtin::BI__sync_fetch_and_or_16:
5916     BuiltinIndex = 2;
5917     break;
5918 
5919   case Builtin::BI__sync_fetch_and_and:
5920   case Builtin::BI__sync_fetch_and_and_1:
5921   case Builtin::BI__sync_fetch_and_and_2:
5922   case Builtin::BI__sync_fetch_and_and_4:
5923   case Builtin::BI__sync_fetch_and_and_8:
5924   case Builtin::BI__sync_fetch_and_and_16:
5925     BuiltinIndex = 3;
5926     break;
5927 
5928   case Builtin::BI__sync_fetch_and_xor:
5929   case Builtin::BI__sync_fetch_and_xor_1:
5930   case Builtin::BI__sync_fetch_and_xor_2:
5931   case Builtin::BI__sync_fetch_and_xor_4:
5932   case Builtin::BI__sync_fetch_and_xor_8:
5933   case Builtin::BI__sync_fetch_and_xor_16:
5934     BuiltinIndex = 4;
5935     break;
5936 
5937   case Builtin::BI__sync_fetch_and_nand:
5938   case Builtin::BI__sync_fetch_and_nand_1:
5939   case Builtin::BI__sync_fetch_and_nand_2:
5940   case Builtin::BI__sync_fetch_and_nand_4:
5941   case Builtin::BI__sync_fetch_and_nand_8:
5942   case Builtin::BI__sync_fetch_and_nand_16:
5943     BuiltinIndex = 5;
5944     WarnAboutSemanticsChange = true;
5945     break;
5946 
5947   case Builtin::BI__sync_add_and_fetch:
5948   case Builtin::BI__sync_add_and_fetch_1:
5949   case Builtin::BI__sync_add_and_fetch_2:
5950   case Builtin::BI__sync_add_and_fetch_4:
5951   case Builtin::BI__sync_add_and_fetch_8:
5952   case Builtin::BI__sync_add_and_fetch_16:
5953     BuiltinIndex = 6;
5954     break;
5955 
5956   case Builtin::BI__sync_sub_and_fetch:
5957   case Builtin::BI__sync_sub_and_fetch_1:
5958   case Builtin::BI__sync_sub_and_fetch_2:
5959   case Builtin::BI__sync_sub_and_fetch_4:
5960   case Builtin::BI__sync_sub_and_fetch_8:
5961   case Builtin::BI__sync_sub_and_fetch_16:
5962     BuiltinIndex = 7;
5963     break;
5964 
5965   case Builtin::BI__sync_and_and_fetch:
5966   case Builtin::BI__sync_and_and_fetch_1:
5967   case Builtin::BI__sync_and_and_fetch_2:
5968   case Builtin::BI__sync_and_and_fetch_4:
5969   case Builtin::BI__sync_and_and_fetch_8:
5970   case Builtin::BI__sync_and_and_fetch_16:
5971     BuiltinIndex = 8;
5972     break;
5973 
5974   case Builtin::BI__sync_or_and_fetch:
5975   case Builtin::BI__sync_or_and_fetch_1:
5976   case Builtin::BI__sync_or_and_fetch_2:
5977   case Builtin::BI__sync_or_and_fetch_4:
5978   case Builtin::BI__sync_or_and_fetch_8:
5979   case Builtin::BI__sync_or_and_fetch_16:
5980     BuiltinIndex = 9;
5981     break;
5982 
5983   case Builtin::BI__sync_xor_and_fetch:
5984   case Builtin::BI__sync_xor_and_fetch_1:
5985   case Builtin::BI__sync_xor_and_fetch_2:
5986   case Builtin::BI__sync_xor_and_fetch_4:
5987   case Builtin::BI__sync_xor_and_fetch_8:
5988   case Builtin::BI__sync_xor_and_fetch_16:
5989     BuiltinIndex = 10;
5990     break;
5991 
5992   case Builtin::BI__sync_nand_and_fetch:
5993   case Builtin::BI__sync_nand_and_fetch_1:
5994   case Builtin::BI__sync_nand_and_fetch_2:
5995   case Builtin::BI__sync_nand_and_fetch_4:
5996   case Builtin::BI__sync_nand_and_fetch_8:
5997   case Builtin::BI__sync_nand_and_fetch_16:
5998     BuiltinIndex = 11;
5999     WarnAboutSemanticsChange = true;
6000     break;
6001 
6002   case Builtin::BI__sync_val_compare_and_swap:
6003   case Builtin::BI__sync_val_compare_and_swap_1:
6004   case Builtin::BI__sync_val_compare_and_swap_2:
6005   case Builtin::BI__sync_val_compare_and_swap_4:
6006   case Builtin::BI__sync_val_compare_and_swap_8:
6007   case Builtin::BI__sync_val_compare_and_swap_16:
6008     BuiltinIndex = 12;
6009     NumFixed = 2;
6010     break;
6011 
6012   case Builtin::BI__sync_bool_compare_and_swap:
6013   case Builtin::BI__sync_bool_compare_and_swap_1:
6014   case Builtin::BI__sync_bool_compare_and_swap_2:
6015   case Builtin::BI__sync_bool_compare_and_swap_4:
6016   case Builtin::BI__sync_bool_compare_and_swap_8:
6017   case Builtin::BI__sync_bool_compare_and_swap_16:
6018     BuiltinIndex = 13;
6019     NumFixed = 2;
6020     ResultType = Context.BoolTy;
6021     break;
6022 
6023   case Builtin::BI__sync_lock_test_and_set:
6024   case Builtin::BI__sync_lock_test_and_set_1:
6025   case Builtin::BI__sync_lock_test_and_set_2:
6026   case Builtin::BI__sync_lock_test_and_set_4:
6027   case Builtin::BI__sync_lock_test_and_set_8:
6028   case Builtin::BI__sync_lock_test_and_set_16:
6029     BuiltinIndex = 14;
6030     break;
6031 
6032   case Builtin::BI__sync_lock_release:
6033   case Builtin::BI__sync_lock_release_1:
6034   case Builtin::BI__sync_lock_release_2:
6035   case Builtin::BI__sync_lock_release_4:
6036   case Builtin::BI__sync_lock_release_8:
6037   case Builtin::BI__sync_lock_release_16:
6038     BuiltinIndex = 15;
6039     NumFixed = 0;
6040     ResultType = Context.VoidTy;
6041     break;
6042 
6043   case Builtin::BI__sync_swap:
6044   case Builtin::BI__sync_swap_1:
6045   case Builtin::BI__sync_swap_2:
6046   case Builtin::BI__sync_swap_4:
6047   case Builtin::BI__sync_swap_8:
6048   case Builtin::BI__sync_swap_16:
6049     BuiltinIndex = 16;
6050     break;
6051   }
6052 
6053   // Now that we know how many fixed arguments we expect, first check that we
6054   // have at least that many.
6055   if (TheCall->getNumArgs() < 1+NumFixed) {
6056     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6057         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6058         << Callee->getSourceRange();
6059     return ExprError();
6060   }
6061 
6062   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6063       << Callee->getSourceRange();
6064 
6065   if (WarnAboutSemanticsChange) {
6066     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6067         << Callee->getSourceRange();
6068   }
6069 
6070   // Get the decl for the concrete builtin from this, we can tell what the
6071   // concrete integer type we should convert to is.
6072   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6073   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6074   FunctionDecl *NewBuiltinDecl;
6075   if (NewBuiltinID == BuiltinID)
6076     NewBuiltinDecl = FDecl;
6077   else {
6078     // Perform builtin lookup to avoid redeclaring it.
6079     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6080     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6081     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6082     assert(Res.getFoundDecl());
6083     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6084     if (!NewBuiltinDecl)
6085       return ExprError();
6086   }
6087 
6088   // The first argument --- the pointer --- has a fixed type; we
6089   // deduce the types of the rest of the arguments accordingly.  Walk
6090   // the remaining arguments, converting them to the deduced value type.
6091   for (unsigned i = 0; i != NumFixed; ++i) {
6092     ExprResult Arg = TheCall->getArg(i+1);
6093 
6094     // GCC does an implicit conversion to the pointer or integer ValType.  This
6095     // can fail in some cases (1i -> int**), check for this error case now.
6096     // Initialize the argument.
6097     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6098                                                    ValType, /*consume*/ false);
6099     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6100     if (Arg.isInvalid())
6101       return ExprError();
6102 
6103     // Okay, we have something that *can* be converted to the right type.  Check
6104     // to see if there is a potentially weird extension going on here.  This can
6105     // happen when you do an atomic operation on something like an char* and
6106     // pass in 42.  The 42 gets converted to char.  This is even more strange
6107     // for things like 45.123 -> char, etc.
6108     // FIXME: Do this check.
6109     TheCall->setArg(i+1, Arg.get());
6110   }
6111 
6112   // Create a new DeclRefExpr to refer to the new decl.
6113   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6114       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6115       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6116       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6117 
6118   // Set the callee in the CallExpr.
6119   // FIXME: This loses syntactic information.
6120   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6121   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6122                                               CK_BuiltinFnToFnPtr);
6123   TheCall->setCallee(PromotedCall.get());
6124 
6125   // Change the result type of the call to match the original value type. This
6126   // is arbitrary, but the codegen for these builtins ins design to handle it
6127   // gracefully.
6128   TheCall->setType(ResultType);
6129 
6130   // Prohibit use of _ExtInt with atomic builtins.
6131   // The arguments would have already been converted to the first argument's
6132   // type, so only need to check the first argument.
6133   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6134   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6135     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6136     return ExprError();
6137   }
6138 
6139   return TheCallResult;
6140 }
6141 
6142 /// SemaBuiltinNontemporalOverloaded - We have a call to
6143 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6144 /// overloaded function based on the pointer type of its last argument.
6145 ///
6146 /// This function goes through and does final semantic checking for these
6147 /// builtins.
6148 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6149   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6150   DeclRefExpr *DRE =
6151       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6152   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6153   unsigned BuiltinID = FDecl->getBuiltinID();
6154   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6155           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6156          "Unexpected nontemporal load/store builtin!");
6157   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6158   unsigned numArgs = isStore ? 2 : 1;
6159 
6160   // Ensure that we have the proper number of arguments.
6161   if (checkArgCount(*this, TheCall, numArgs))
6162     return ExprError();
6163 
6164   // Inspect the last argument of the nontemporal builtin.  This should always
6165   // be a pointer type, from which we imply the type of the memory access.
6166   // Because it is a pointer type, we don't have to worry about any implicit
6167   // casts here.
6168   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6169   ExprResult PointerArgResult =
6170       DefaultFunctionArrayLvalueConversion(PointerArg);
6171 
6172   if (PointerArgResult.isInvalid())
6173     return ExprError();
6174   PointerArg = PointerArgResult.get();
6175   TheCall->setArg(numArgs - 1, PointerArg);
6176 
6177   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6178   if (!pointerType) {
6179     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6180         << PointerArg->getType() << PointerArg->getSourceRange();
6181     return ExprError();
6182   }
6183 
6184   QualType ValType = pointerType->getPointeeType();
6185 
6186   // Strip any qualifiers off ValType.
6187   ValType = ValType.getUnqualifiedType();
6188   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6189       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6190       !ValType->isVectorType()) {
6191     Diag(DRE->getBeginLoc(),
6192          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6193         << PointerArg->getType() << PointerArg->getSourceRange();
6194     return ExprError();
6195   }
6196 
6197   if (!isStore) {
6198     TheCall->setType(ValType);
6199     return TheCallResult;
6200   }
6201 
6202   ExprResult ValArg = TheCall->getArg(0);
6203   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6204       Context, ValType, /*consume*/ false);
6205   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6206   if (ValArg.isInvalid())
6207     return ExprError();
6208 
6209   TheCall->setArg(0, ValArg.get());
6210   TheCall->setType(Context.VoidTy);
6211   return TheCallResult;
6212 }
6213 
6214 /// CheckObjCString - Checks that the argument to the builtin
6215 /// CFString constructor is correct
6216 /// Note: It might also make sense to do the UTF-16 conversion here (would
6217 /// simplify the backend).
6218 bool Sema::CheckObjCString(Expr *Arg) {
6219   Arg = Arg->IgnoreParenCasts();
6220   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6221 
6222   if (!Literal || !Literal->isAscii()) {
6223     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6224         << Arg->getSourceRange();
6225     return true;
6226   }
6227 
6228   if (Literal->containsNonAsciiOrNull()) {
6229     StringRef String = Literal->getString();
6230     unsigned NumBytes = String.size();
6231     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6232     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6233     llvm::UTF16 *ToPtr = &ToBuf[0];
6234 
6235     llvm::ConversionResult Result =
6236         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6237                                  ToPtr + NumBytes, llvm::strictConversion);
6238     // Check for conversion failure.
6239     if (Result != llvm::conversionOK)
6240       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6241           << Arg->getSourceRange();
6242   }
6243   return false;
6244 }
6245 
6246 /// CheckObjCString - Checks that the format string argument to the os_log()
6247 /// and os_trace() functions is correct, and converts it to const char *.
6248 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6249   Arg = Arg->IgnoreParenCasts();
6250   auto *Literal = dyn_cast<StringLiteral>(Arg);
6251   if (!Literal) {
6252     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6253       Literal = ObjcLiteral->getString();
6254     }
6255   }
6256 
6257   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6258     return ExprError(
6259         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6260         << Arg->getSourceRange());
6261   }
6262 
6263   ExprResult Result(Literal);
6264   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6265   InitializedEntity Entity =
6266       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6267   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6268   return Result;
6269 }
6270 
6271 /// Check that the user is calling the appropriate va_start builtin for the
6272 /// target and calling convention.
6273 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6274   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6275   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6276   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6277                     TT.getArch() == llvm::Triple::aarch64_32);
6278   bool IsWindows = TT.isOSWindows();
6279   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6280   if (IsX64 || IsAArch64) {
6281     CallingConv CC = CC_C;
6282     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6283       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6284     if (IsMSVAStart) {
6285       // Don't allow this in System V ABI functions.
6286       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6287         return S.Diag(Fn->getBeginLoc(),
6288                       diag::err_ms_va_start_used_in_sysv_function);
6289     } else {
6290       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6291       // On x64 Windows, don't allow this in System V ABI functions.
6292       // (Yes, that means there's no corresponding way to support variadic
6293       // System V ABI functions on Windows.)
6294       if ((IsWindows && CC == CC_X86_64SysV) ||
6295           (!IsWindows && CC == CC_Win64))
6296         return S.Diag(Fn->getBeginLoc(),
6297                       diag::err_va_start_used_in_wrong_abi_function)
6298                << !IsWindows;
6299     }
6300     return false;
6301   }
6302 
6303   if (IsMSVAStart)
6304     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6305   return false;
6306 }
6307 
6308 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6309                                              ParmVarDecl **LastParam = nullptr) {
6310   // Determine whether the current function, block, or obj-c method is variadic
6311   // and get its parameter list.
6312   bool IsVariadic = false;
6313   ArrayRef<ParmVarDecl *> Params;
6314   DeclContext *Caller = S.CurContext;
6315   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6316     IsVariadic = Block->isVariadic();
6317     Params = Block->parameters();
6318   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6319     IsVariadic = FD->isVariadic();
6320     Params = FD->parameters();
6321   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6322     IsVariadic = MD->isVariadic();
6323     // FIXME: This isn't correct for methods (results in bogus warning).
6324     Params = MD->parameters();
6325   } else if (isa<CapturedDecl>(Caller)) {
6326     // We don't support va_start in a CapturedDecl.
6327     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6328     return true;
6329   } else {
6330     // This must be some other declcontext that parses exprs.
6331     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6332     return true;
6333   }
6334 
6335   if (!IsVariadic) {
6336     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6337     return true;
6338   }
6339 
6340   if (LastParam)
6341     *LastParam = Params.empty() ? nullptr : Params.back();
6342 
6343   return false;
6344 }
6345 
6346 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6347 /// for validity.  Emit an error and return true on failure; return false
6348 /// on success.
6349 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6350   Expr *Fn = TheCall->getCallee();
6351 
6352   if (checkVAStartABI(*this, BuiltinID, Fn))
6353     return true;
6354 
6355   if (checkArgCount(*this, TheCall, 2))
6356     return true;
6357 
6358   // Type-check the first argument normally.
6359   if (checkBuiltinArgument(*this, TheCall, 0))
6360     return true;
6361 
6362   // Check that the current function is variadic, and get its last parameter.
6363   ParmVarDecl *LastParam;
6364   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6365     return true;
6366 
6367   // Verify that the second argument to the builtin is the last argument of the
6368   // current function or method.
6369   bool SecondArgIsLastNamedArgument = false;
6370   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6371 
6372   // These are valid if SecondArgIsLastNamedArgument is false after the next
6373   // block.
6374   QualType Type;
6375   SourceLocation ParamLoc;
6376   bool IsCRegister = false;
6377 
6378   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6379     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6380       SecondArgIsLastNamedArgument = PV == LastParam;
6381 
6382       Type = PV->getType();
6383       ParamLoc = PV->getLocation();
6384       IsCRegister =
6385           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6386     }
6387   }
6388 
6389   if (!SecondArgIsLastNamedArgument)
6390     Diag(TheCall->getArg(1)->getBeginLoc(),
6391          diag::warn_second_arg_of_va_start_not_last_named_param);
6392   else if (IsCRegister || Type->isReferenceType() ||
6393            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6394              // Promotable integers are UB, but enumerations need a bit of
6395              // extra checking to see what their promotable type actually is.
6396              if (!Type->isPromotableIntegerType())
6397                return false;
6398              if (!Type->isEnumeralType())
6399                return true;
6400              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6401              return !(ED &&
6402                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6403            }()) {
6404     unsigned Reason = 0;
6405     if (Type->isReferenceType())  Reason = 1;
6406     else if (IsCRegister)         Reason = 2;
6407     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6408     Diag(ParamLoc, diag::note_parameter_type) << Type;
6409   }
6410 
6411   TheCall->setType(Context.VoidTy);
6412   return false;
6413 }
6414 
6415 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6416   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6417     const LangOptions &LO = getLangOpts();
6418 
6419     if (LO.CPlusPlus)
6420       return Arg->getType()
6421                  .getCanonicalType()
6422                  .getTypePtr()
6423                  ->getPointeeType()
6424                  .withoutLocalFastQualifiers() == Context.CharTy;
6425 
6426     // In C, allow aliasing through `char *`, this is required for AArch64 at
6427     // least.
6428     return true;
6429   };
6430 
6431   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6432   //                 const char *named_addr);
6433 
6434   Expr *Func = Call->getCallee();
6435 
6436   if (Call->getNumArgs() < 3)
6437     return Diag(Call->getEndLoc(),
6438                 diag::err_typecheck_call_too_few_args_at_least)
6439            << 0 /*function call*/ << 3 << Call->getNumArgs();
6440 
6441   // Type-check the first argument normally.
6442   if (checkBuiltinArgument(*this, Call, 0))
6443     return true;
6444 
6445   // Check that the current function is variadic.
6446   if (checkVAStartIsInVariadicFunction(*this, Func))
6447     return true;
6448 
6449   // __va_start on Windows does not validate the parameter qualifiers
6450 
6451   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6452   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6453 
6454   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6455   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6456 
6457   const QualType &ConstCharPtrTy =
6458       Context.getPointerType(Context.CharTy.withConst());
6459   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6460     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6461         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6462         << 0                                      /* qualifier difference */
6463         << 3                                      /* parameter mismatch */
6464         << 2 << Arg1->getType() << ConstCharPtrTy;
6465 
6466   const QualType SizeTy = Context.getSizeType();
6467   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6468     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6469         << Arg2->getType() << SizeTy << 1 /* different class */
6470         << 0                              /* qualifier difference */
6471         << 3                              /* parameter mismatch */
6472         << 3 << Arg2->getType() << SizeTy;
6473 
6474   return false;
6475 }
6476 
6477 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6478 /// friends.  This is declared to take (...), so we have to check everything.
6479 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6480   if (checkArgCount(*this, TheCall, 2))
6481     return true;
6482 
6483   ExprResult OrigArg0 = TheCall->getArg(0);
6484   ExprResult OrigArg1 = TheCall->getArg(1);
6485 
6486   // Do standard promotions between the two arguments, returning their common
6487   // type.
6488   QualType Res = UsualArithmeticConversions(
6489       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6490   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6491     return true;
6492 
6493   // Make sure any conversions are pushed back into the call; this is
6494   // type safe since unordered compare builtins are declared as "_Bool
6495   // foo(...)".
6496   TheCall->setArg(0, OrigArg0.get());
6497   TheCall->setArg(1, OrigArg1.get());
6498 
6499   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6500     return false;
6501 
6502   // If the common type isn't a real floating type, then the arguments were
6503   // invalid for this operation.
6504   if (Res.isNull() || !Res->isRealFloatingType())
6505     return Diag(OrigArg0.get()->getBeginLoc(),
6506                 diag::err_typecheck_call_invalid_ordered_compare)
6507            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6508            << SourceRange(OrigArg0.get()->getBeginLoc(),
6509                           OrigArg1.get()->getEndLoc());
6510 
6511   return false;
6512 }
6513 
6514 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6515 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6516 /// to check everything. We expect the last argument to be a floating point
6517 /// value.
6518 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6519   if (checkArgCount(*this, TheCall, NumArgs))
6520     return true;
6521 
6522   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6523   // on all preceding parameters just being int.  Try all of those.
6524   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6525     Expr *Arg = TheCall->getArg(i);
6526 
6527     if (Arg->isTypeDependent())
6528       return false;
6529 
6530     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6531 
6532     if (Res.isInvalid())
6533       return true;
6534     TheCall->setArg(i, Res.get());
6535   }
6536 
6537   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6538 
6539   if (OrigArg->isTypeDependent())
6540     return false;
6541 
6542   // Usual Unary Conversions will convert half to float, which we want for
6543   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6544   // type how it is, but do normal L->Rvalue conversions.
6545   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6546     OrigArg = UsualUnaryConversions(OrigArg).get();
6547   else
6548     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6549   TheCall->setArg(NumArgs - 1, OrigArg);
6550 
6551   // This operation requires a non-_Complex floating-point number.
6552   if (!OrigArg->getType()->isRealFloatingType())
6553     return Diag(OrigArg->getBeginLoc(),
6554                 diag::err_typecheck_call_invalid_unary_fp)
6555            << OrigArg->getType() << OrigArg->getSourceRange();
6556 
6557   return false;
6558 }
6559 
6560 /// Perform semantic analysis for a call to __builtin_complex.
6561 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6562   if (checkArgCount(*this, TheCall, 2))
6563     return true;
6564 
6565   bool Dependent = false;
6566   for (unsigned I = 0; I != 2; ++I) {
6567     Expr *Arg = TheCall->getArg(I);
6568     QualType T = Arg->getType();
6569     if (T->isDependentType()) {
6570       Dependent = true;
6571       continue;
6572     }
6573 
6574     // Despite supporting _Complex int, GCC requires a real floating point type
6575     // for the operands of __builtin_complex.
6576     if (!T->isRealFloatingType()) {
6577       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6578              << Arg->getType() << Arg->getSourceRange();
6579     }
6580 
6581     ExprResult Converted = DefaultLvalueConversion(Arg);
6582     if (Converted.isInvalid())
6583       return true;
6584     TheCall->setArg(I, Converted.get());
6585   }
6586 
6587   if (Dependent) {
6588     TheCall->setType(Context.DependentTy);
6589     return false;
6590   }
6591 
6592   Expr *Real = TheCall->getArg(0);
6593   Expr *Imag = TheCall->getArg(1);
6594   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6595     return Diag(Real->getBeginLoc(),
6596                 diag::err_typecheck_call_different_arg_types)
6597            << Real->getType() << Imag->getType()
6598            << Real->getSourceRange() << Imag->getSourceRange();
6599   }
6600 
6601   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6602   // don't allow this builtin to form those types either.
6603   // FIXME: Should we allow these types?
6604   if (Real->getType()->isFloat16Type())
6605     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6606            << "_Float16";
6607   if (Real->getType()->isHalfType())
6608     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6609            << "half";
6610 
6611   TheCall->setType(Context.getComplexType(Real->getType()));
6612   return false;
6613 }
6614 
6615 // Customized Sema Checking for VSX builtins that have the following signature:
6616 // vector [...] builtinName(vector [...], vector [...], const int);
6617 // Which takes the same type of vectors (any legal vector type) for the first
6618 // two arguments and takes compile time constant for the third argument.
6619 // Example builtins are :
6620 // vector double vec_xxpermdi(vector double, vector double, int);
6621 // vector short vec_xxsldwi(vector short, vector short, int);
6622 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6623   unsigned ExpectedNumArgs = 3;
6624   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6625     return true;
6626 
6627   // Check the third argument is a compile time constant
6628   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6629     return Diag(TheCall->getBeginLoc(),
6630                 diag::err_vsx_builtin_nonconstant_argument)
6631            << 3 /* argument index */ << TheCall->getDirectCallee()
6632            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6633                           TheCall->getArg(2)->getEndLoc());
6634 
6635   QualType Arg1Ty = TheCall->getArg(0)->getType();
6636   QualType Arg2Ty = TheCall->getArg(1)->getType();
6637 
6638   // Check the type of argument 1 and argument 2 are vectors.
6639   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6640   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6641       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6642     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6643            << TheCall->getDirectCallee()
6644            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6645                           TheCall->getArg(1)->getEndLoc());
6646   }
6647 
6648   // Check the first two arguments are the same type.
6649   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6650     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6651            << TheCall->getDirectCallee()
6652            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6653                           TheCall->getArg(1)->getEndLoc());
6654   }
6655 
6656   // When default clang type checking is turned off and the customized type
6657   // checking is used, the returning type of the function must be explicitly
6658   // set. Otherwise it is _Bool by default.
6659   TheCall->setType(Arg1Ty);
6660 
6661   return false;
6662 }
6663 
6664 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6665 // This is declared to take (...), so we have to check everything.
6666 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6667   if (TheCall->getNumArgs() < 2)
6668     return ExprError(Diag(TheCall->getEndLoc(),
6669                           diag::err_typecheck_call_too_few_args_at_least)
6670                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6671                      << TheCall->getSourceRange());
6672 
6673   // Determine which of the following types of shufflevector we're checking:
6674   // 1) unary, vector mask: (lhs, mask)
6675   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6676   QualType resType = TheCall->getArg(0)->getType();
6677   unsigned numElements = 0;
6678 
6679   if (!TheCall->getArg(0)->isTypeDependent() &&
6680       !TheCall->getArg(1)->isTypeDependent()) {
6681     QualType LHSType = TheCall->getArg(0)->getType();
6682     QualType RHSType = TheCall->getArg(1)->getType();
6683 
6684     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6685       return ExprError(
6686           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6687           << TheCall->getDirectCallee()
6688           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6689                          TheCall->getArg(1)->getEndLoc()));
6690 
6691     numElements = LHSType->castAs<VectorType>()->getNumElements();
6692     unsigned numResElements = TheCall->getNumArgs() - 2;
6693 
6694     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6695     // with mask.  If so, verify that RHS is an integer vector type with the
6696     // same number of elts as lhs.
6697     if (TheCall->getNumArgs() == 2) {
6698       if (!RHSType->hasIntegerRepresentation() ||
6699           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6700         return ExprError(Diag(TheCall->getBeginLoc(),
6701                               diag::err_vec_builtin_incompatible_vector)
6702                          << TheCall->getDirectCallee()
6703                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6704                                         TheCall->getArg(1)->getEndLoc()));
6705     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6706       return ExprError(Diag(TheCall->getBeginLoc(),
6707                             diag::err_vec_builtin_incompatible_vector)
6708                        << TheCall->getDirectCallee()
6709                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6710                                       TheCall->getArg(1)->getEndLoc()));
6711     } else if (numElements != numResElements) {
6712       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6713       resType = Context.getVectorType(eltType, numResElements,
6714                                       VectorType::GenericVector);
6715     }
6716   }
6717 
6718   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6719     if (TheCall->getArg(i)->isTypeDependent() ||
6720         TheCall->getArg(i)->isValueDependent())
6721       continue;
6722 
6723     Optional<llvm::APSInt> Result;
6724     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6725       return ExprError(Diag(TheCall->getBeginLoc(),
6726                             diag::err_shufflevector_nonconstant_argument)
6727                        << TheCall->getArg(i)->getSourceRange());
6728 
6729     // Allow -1 which will be translated to undef in the IR.
6730     if (Result->isSigned() && Result->isAllOnesValue())
6731       continue;
6732 
6733     if (Result->getActiveBits() > 64 ||
6734         Result->getZExtValue() >= numElements * 2)
6735       return ExprError(Diag(TheCall->getBeginLoc(),
6736                             diag::err_shufflevector_argument_too_large)
6737                        << TheCall->getArg(i)->getSourceRange());
6738   }
6739 
6740   SmallVector<Expr*, 32> exprs;
6741 
6742   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6743     exprs.push_back(TheCall->getArg(i));
6744     TheCall->setArg(i, nullptr);
6745   }
6746 
6747   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6748                                          TheCall->getCallee()->getBeginLoc(),
6749                                          TheCall->getRParenLoc());
6750 }
6751 
6752 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6753 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6754                                        SourceLocation BuiltinLoc,
6755                                        SourceLocation RParenLoc) {
6756   ExprValueKind VK = VK_PRValue;
6757   ExprObjectKind OK = OK_Ordinary;
6758   QualType DstTy = TInfo->getType();
6759   QualType SrcTy = E->getType();
6760 
6761   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6762     return ExprError(Diag(BuiltinLoc,
6763                           diag::err_convertvector_non_vector)
6764                      << E->getSourceRange());
6765   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6766     return ExprError(Diag(BuiltinLoc,
6767                           diag::err_convertvector_non_vector_type));
6768 
6769   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6770     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6771     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6772     if (SrcElts != DstElts)
6773       return ExprError(Diag(BuiltinLoc,
6774                             diag::err_convertvector_incompatible_vector)
6775                        << E->getSourceRange());
6776   }
6777 
6778   return new (Context)
6779       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6780 }
6781 
6782 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6783 // This is declared to take (const void*, ...) and can take two
6784 // optional constant int args.
6785 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6786   unsigned NumArgs = TheCall->getNumArgs();
6787 
6788   if (NumArgs > 3)
6789     return Diag(TheCall->getEndLoc(),
6790                 diag::err_typecheck_call_too_many_args_at_most)
6791            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6792 
6793   // Argument 0 is checked for us and the remaining arguments must be
6794   // constant integers.
6795   for (unsigned i = 1; i != NumArgs; ++i)
6796     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6797       return true;
6798 
6799   return false;
6800 }
6801 
6802 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6803 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6804   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6805     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6806            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6807   if (checkArgCount(*this, TheCall, 1))
6808     return true;
6809   Expr *Arg = TheCall->getArg(0);
6810   if (Arg->isInstantiationDependent())
6811     return false;
6812 
6813   QualType ArgTy = Arg->getType();
6814   if (!ArgTy->hasFloatingRepresentation())
6815     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6816            << ArgTy;
6817   if (Arg->isLValue()) {
6818     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6819     TheCall->setArg(0, FirstArg.get());
6820   }
6821   TheCall->setType(TheCall->getArg(0)->getType());
6822   return false;
6823 }
6824 
6825 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6826 // __assume does not evaluate its arguments, and should warn if its argument
6827 // has side effects.
6828 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6829   Expr *Arg = TheCall->getArg(0);
6830   if (Arg->isInstantiationDependent()) return false;
6831 
6832   if (Arg->HasSideEffects(Context))
6833     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6834         << Arg->getSourceRange()
6835         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6836 
6837   return false;
6838 }
6839 
6840 /// Handle __builtin_alloca_with_align. This is declared
6841 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6842 /// than 8.
6843 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6844   // The alignment must be a constant integer.
6845   Expr *Arg = TheCall->getArg(1);
6846 
6847   // We can't check the value of a dependent argument.
6848   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6849     if (const auto *UE =
6850             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6851       if (UE->getKind() == UETT_AlignOf ||
6852           UE->getKind() == UETT_PreferredAlignOf)
6853         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6854             << Arg->getSourceRange();
6855 
6856     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6857 
6858     if (!Result.isPowerOf2())
6859       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6860              << Arg->getSourceRange();
6861 
6862     if (Result < Context.getCharWidth())
6863       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6864              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6865 
6866     if (Result > std::numeric_limits<int32_t>::max())
6867       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6868              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6869   }
6870 
6871   return false;
6872 }
6873 
6874 /// Handle __builtin_assume_aligned. This is declared
6875 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6876 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6877   unsigned NumArgs = TheCall->getNumArgs();
6878 
6879   if (NumArgs > 3)
6880     return Diag(TheCall->getEndLoc(),
6881                 diag::err_typecheck_call_too_many_args_at_most)
6882            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6883 
6884   // The alignment must be a constant integer.
6885   Expr *Arg = TheCall->getArg(1);
6886 
6887   // We can't check the value of a dependent argument.
6888   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6889     llvm::APSInt Result;
6890     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6891       return true;
6892 
6893     if (!Result.isPowerOf2())
6894       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6895              << Arg->getSourceRange();
6896 
6897     if (Result > Sema::MaximumAlignment)
6898       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6899           << Arg->getSourceRange() << Sema::MaximumAlignment;
6900   }
6901 
6902   if (NumArgs > 2) {
6903     ExprResult Arg(TheCall->getArg(2));
6904     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6905       Context.getSizeType(), false);
6906     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6907     if (Arg.isInvalid()) return true;
6908     TheCall->setArg(2, Arg.get());
6909   }
6910 
6911   return false;
6912 }
6913 
6914 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6915   unsigned BuiltinID =
6916       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6917   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6918 
6919   unsigned NumArgs = TheCall->getNumArgs();
6920   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6921   if (NumArgs < NumRequiredArgs) {
6922     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6923            << 0 /* function call */ << NumRequiredArgs << NumArgs
6924            << TheCall->getSourceRange();
6925   }
6926   if (NumArgs >= NumRequiredArgs + 0x100) {
6927     return Diag(TheCall->getEndLoc(),
6928                 diag::err_typecheck_call_too_many_args_at_most)
6929            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6930            << TheCall->getSourceRange();
6931   }
6932   unsigned i = 0;
6933 
6934   // For formatting call, check buffer arg.
6935   if (!IsSizeCall) {
6936     ExprResult Arg(TheCall->getArg(i));
6937     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6938         Context, Context.VoidPtrTy, false);
6939     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6940     if (Arg.isInvalid())
6941       return true;
6942     TheCall->setArg(i, Arg.get());
6943     i++;
6944   }
6945 
6946   // Check string literal arg.
6947   unsigned FormatIdx = i;
6948   {
6949     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6950     if (Arg.isInvalid())
6951       return true;
6952     TheCall->setArg(i, Arg.get());
6953     i++;
6954   }
6955 
6956   // Make sure variadic args are scalar.
6957   unsigned FirstDataArg = i;
6958   while (i < NumArgs) {
6959     ExprResult Arg = DefaultVariadicArgumentPromotion(
6960         TheCall->getArg(i), VariadicFunction, nullptr);
6961     if (Arg.isInvalid())
6962       return true;
6963     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6964     if (ArgSize.getQuantity() >= 0x100) {
6965       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6966              << i << (int)ArgSize.getQuantity() << 0xff
6967              << TheCall->getSourceRange();
6968     }
6969     TheCall->setArg(i, Arg.get());
6970     i++;
6971   }
6972 
6973   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6974   // call to avoid duplicate diagnostics.
6975   if (!IsSizeCall) {
6976     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6977     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6978     bool Success = CheckFormatArguments(
6979         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6980         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6981         CheckedVarArgs);
6982     if (!Success)
6983       return true;
6984   }
6985 
6986   if (IsSizeCall) {
6987     TheCall->setType(Context.getSizeType());
6988   } else {
6989     TheCall->setType(Context.VoidPtrTy);
6990   }
6991   return false;
6992 }
6993 
6994 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6995 /// TheCall is a constant expression.
6996 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6997                                   llvm::APSInt &Result) {
6998   Expr *Arg = TheCall->getArg(ArgNum);
6999   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7000   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7001 
7002   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7003 
7004   Optional<llvm::APSInt> R;
7005   if (!(R = Arg->getIntegerConstantExpr(Context)))
7006     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7007            << FDecl->getDeclName() << Arg->getSourceRange();
7008   Result = *R;
7009   return false;
7010 }
7011 
7012 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7013 /// TheCall is a constant expression in the range [Low, High].
7014 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7015                                        int Low, int High, bool RangeIsError) {
7016   if (isConstantEvaluated())
7017     return false;
7018   llvm::APSInt Result;
7019 
7020   // We can't check the value of a dependent argument.
7021   Expr *Arg = TheCall->getArg(ArgNum);
7022   if (Arg->isTypeDependent() || Arg->isValueDependent())
7023     return false;
7024 
7025   // Check constant-ness first.
7026   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7027     return true;
7028 
7029   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7030     if (RangeIsError)
7031       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7032              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7033     else
7034       // Defer the warning until we know if the code will be emitted so that
7035       // dead code can ignore this.
7036       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7037                           PDiag(diag::warn_argument_invalid_range)
7038                               << toString(Result, 10) << Low << High
7039                               << Arg->getSourceRange());
7040   }
7041 
7042   return false;
7043 }
7044 
7045 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7046 /// TheCall is a constant expression is a multiple of Num..
7047 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7048                                           unsigned Num) {
7049   llvm::APSInt Result;
7050 
7051   // We can't check the value of a dependent argument.
7052   Expr *Arg = TheCall->getArg(ArgNum);
7053   if (Arg->isTypeDependent() || Arg->isValueDependent())
7054     return false;
7055 
7056   // Check constant-ness first.
7057   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7058     return true;
7059 
7060   if (Result.getSExtValue() % Num != 0)
7061     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7062            << Num << Arg->getSourceRange();
7063 
7064   return false;
7065 }
7066 
7067 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7068 /// constant expression representing a power of 2.
7069 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7070   llvm::APSInt Result;
7071 
7072   // We can't check the value of a dependent argument.
7073   Expr *Arg = TheCall->getArg(ArgNum);
7074   if (Arg->isTypeDependent() || Arg->isValueDependent())
7075     return false;
7076 
7077   // Check constant-ness first.
7078   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7079     return true;
7080 
7081   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7082   // and only if x is a power of 2.
7083   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7084     return false;
7085 
7086   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7087          << Arg->getSourceRange();
7088 }
7089 
7090 static bool IsShiftedByte(llvm::APSInt Value) {
7091   if (Value.isNegative())
7092     return false;
7093 
7094   // Check if it's a shifted byte, by shifting it down
7095   while (true) {
7096     // If the value fits in the bottom byte, the check passes.
7097     if (Value < 0x100)
7098       return true;
7099 
7100     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7101     // fails.
7102     if ((Value & 0xFF) != 0)
7103       return false;
7104 
7105     // If the bottom 8 bits are all 0, but something above that is nonzero,
7106     // then shifting the value right by 8 bits won't affect whether it's a
7107     // shifted byte or not. So do that, and go round again.
7108     Value >>= 8;
7109   }
7110 }
7111 
7112 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7113 /// a constant expression representing an arbitrary byte value shifted left by
7114 /// a multiple of 8 bits.
7115 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7116                                              unsigned ArgBits) {
7117   llvm::APSInt Result;
7118 
7119   // We can't check the value of a dependent argument.
7120   Expr *Arg = TheCall->getArg(ArgNum);
7121   if (Arg->isTypeDependent() || Arg->isValueDependent())
7122     return false;
7123 
7124   // Check constant-ness first.
7125   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7126     return true;
7127 
7128   // Truncate to the given size.
7129   Result = Result.getLoBits(ArgBits);
7130   Result.setIsUnsigned(true);
7131 
7132   if (IsShiftedByte(Result))
7133     return false;
7134 
7135   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7136          << Arg->getSourceRange();
7137 }
7138 
7139 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7140 /// TheCall is a constant expression representing either a shifted byte value,
7141 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7142 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7143 /// Arm MVE intrinsics.
7144 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7145                                                    int ArgNum,
7146                                                    unsigned ArgBits) {
7147   llvm::APSInt Result;
7148 
7149   // We can't check the value of a dependent argument.
7150   Expr *Arg = TheCall->getArg(ArgNum);
7151   if (Arg->isTypeDependent() || Arg->isValueDependent())
7152     return false;
7153 
7154   // Check constant-ness first.
7155   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7156     return true;
7157 
7158   // Truncate to the given size.
7159   Result = Result.getLoBits(ArgBits);
7160   Result.setIsUnsigned(true);
7161 
7162   // Check to see if it's in either of the required forms.
7163   if (IsShiftedByte(Result) ||
7164       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7165     return false;
7166 
7167   return Diag(TheCall->getBeginLoc(),
7168               diag::err_argument_not_shifted_byte_or_xxff)
7169          << Arg->getSourceRange();
7170 }
7171 
7172 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7173 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7174   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7175     if (checkArgCount(*this, TheCall, 2))
7176       return true;
7177     Expr *Arg0 = TheCall->getArg(0);
7178     Expr *Arg1 = TheCall->getArg(1);
7179 
7180     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7181     if (FirstArg.isInvalid())
7182       return true;
7183     QualType FirstArgType = FirstArg.get()->getType();
7184     if (!FirstArgType->isAnyPointerType())
7185       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7186                << "first" << FirstArgType << Arg0->getSourceRange();
7187     TheCall->setArg(0, FirstArg.get());
7188 
7189     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7190     if (SecArg.isInvalid())
7191       return true;
7192     QualType SecArgType = SecArg.get()->getType();
7193     if (!SecArgType->isIntegerType())
7194       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7195                << "second" << SecArgType << Arg1->getSourceRange();
7196 
7197     // Derive the return type from the pointer argument.
7198     TheCall->setType(FirstArgType);
7199     return false;
7200   }
7201 
7202   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7203     if (checkArgCount(*this, TheCall, 2))
7204       return true;
7205 
7206     Expr *Arg0 = TheCall->getArg(0);
7207     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7208     if (FirstArg.isInvalid())
7209       return true;
7210     QualType FirstArgType = FirstArg.get()->getType();
7211     if (!FirstArgType->isAnyPointerType())
7212       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7213                << "first" << FirstArgType << Arg0->getSourceRange();
7214     TheCall->setArg(0, FirstArg.get());
7215 
7216     // Derive the return type from the pointer argument.
7217     TheCall->setType(FirstArgType);
7218 
7219     // Second arg must be an constant in range [0,15]
7220     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7221   }
7222 
7223   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7224     if (checkArgCount(*this, TheCall, 2))
7225       return true;
7226     Expr *Arg0 = TheCall->getArg(0);
7227     Expr *Arg1 = TheCall->getArg(1);
7228 
7229     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7230     if (FirstArg.isInvalid())
7231       return true;
7232     QualType FirstArgType = FirstArg.get()->getType();
7233     if (!FirstArgType->isAnyPointerType())
7234       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7235                << "first" << FirstArgType << Arg0->getSourceRange();
7236 
7237     QualType SecArgType = Arg1->getType();
7238     if (!SecArgType->isIntegerType())
7239       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7240                << "second" << SecArgType << Arg1->getSourceRange();
7241     TheCall->setType(Context.IntTy);
7242     return false;
7243   }
7244 
7245   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7246       BuiltinID == AArch64::BI__builtin_arm_stg) {
7247     if (checkArgCount(*this, TheCall, 1))
7248       return true;
7249     Expr *Arg0 = TheCall->getArg(0);
7250     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7251     if (FirstArg.isInvalid())
7252       return true;
7253 
7254     QualType FirstArgType = FirstArg.get()->getType();
7255     if (!FirstArgType->isAnyPointerType())
7256       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7257                << "first" << FirstArgType << Arg0->getSourceRange();
7258     TheCall->setArg(0, FirstArg.get());
7259 
7260     // Derive the return type from the pointer argument.
7261     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7262       TheCall->setType(FirstArgType);
7263     return false;
7264   }
7265 
7266   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7267     Expr *ArgA = TheCall->getArg(0);
7268     Expr *ArgB = TheCall->getArg(1);
7269 
7270     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7271     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7272 
7273     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7274       return true;
7275 
7276     QualType ArgTypeA = ArgExprA.get()->getType();
7277     QualType ArgTypeB = ArgExprB.get()->getType();
7278 
7279     auto isNull = [&] (Expr *E) -> bool {
7280       return E->isNullPointerConstant(
7281                         Context, Expr::NPC_ValueDependentIsNotNull); };
7282 
7283     // argument should be either a pointer or null
7284     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7285       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7286         << "first" << ArgTypeA << ArgA->getSourceRange();
7287 
7288     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7289       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7290         << "second" << ArgTypeB << ArgB->getSourceRange();
7291 
7292     // Ensure Pointee types are compatible
7293     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7294         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7295       QualType pointeeA = ArgTypeA->getPointeeType();
7296       QualType pointeeB = ArgTypeB->getPointeeType();
7297       if (!Context.typesAreCompatible(
7298              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7299              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7300         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7301           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7302           << ArgB->getSourceRange();
7303       }
7304     }
7305 
7306     // at least one argument should be pointer type
7307     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7308       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7309         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7310 
7311     if (isNull(ArgA)) // adopt type of the other pointer
7312       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7313 
7314     if (isNull(ArgB))
7315       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7316 
7317     TheCall->setArg(0, ArgExprA.get());
7318     TheCall->setArg(1, ArgExprB.get());
7319     TheCall->setType(Context.LongLongTy);
7320     return false;
7321   }
7322   assert(false && "Unhandled ARM MTE intrinsic");
7323   return true;
7324 }
7325 
7326 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7327 /// TheCall is an ARM/AArch64 special register string literal.
7328 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7329                                     int ArgNum, unsigned ExpectedFieldNum,
7330                                     bool AllowName) {
7331   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7332                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7333                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7334                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7335                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7336                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7337   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7338                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7339                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7340                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7341                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7342                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7343   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7344 
7345   // We can't check the value of a dependent argument.
7346   Expr *Arg = TheCall->getArg(ArgNum);
7347   if (Arg->isTypeDependent() || Arg->isValueDependent())
7348     return false;
7349 
7350   // Check if the argument is a string literal.
7351   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7352     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7353            << Arg->getSourceRange();
7354 
7355   // Check the type of special register given.
7356   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7357   SmallVector<StringRef, 6> Fields;
7358   Reg.split(Fields, ":");
7359 
7360   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7361     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7362            << Arg->getSourceRange();
7363 
7364   // If the string is the name of a register then we cannot check that it is
7365   // valid here but if the string is of one the forms described in ACLE then we
7366   // can check that the supplied fields are integers and within the valid
7367   // ranges.
7368   if (Fields.size() > 1) {
7369     bool FiveFields = Fields.size() == 5;
7370 
7371     bool ValidString = true;
7372     if (IsARMBuiltin) {
7373       ValidString &= Fields[0].startswith_insensitive("cp") ||
7374                      Fields[0].startswith_insensitive("p");
7375       if (ValidString)
7376         Fields[0] = Fields[0].drop_front(
7377             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7378 
7379       ValidString &= Fields[2].startswith_insensitive("c");
7380       if (ValidString)
7381         Fields[2] = Fields[2].drop_front(1);
7382 
7383       if (FiveFields) {
7384         ValidString &= Fields[3].startswith_insensitive("c");
7385         if (ValidString)
7386           Fields[3] = Fields[3].drop_front(1);
7387       }
7388     }
7389 
7390     SmallVector<int, 5> Ranges;
7391     if (FiveFields)
7392       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7393     else
7394       Ranges.append({15, 7, 15});
7395 
7396     for (unsigned i=0; i<Fields.size(); ++i) {
7397       int IntField;
7398       ValidString &= !Fields[i].getAsInteger(10, IntField);
7399       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7400     }
7401 
7402     if (!ValidString)
7403       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7404              << Arg->getSourceRange();
7405   } else if (IsAArch64Builtin && Fields.size() == 1) {
7406     // If the register name is one of those that appear in the condition below
7407     // and the special register builtin being used is one of the write builtins,
7408     // then we require that the argument provided for writing to the register
7409     // is an integer constant expression. This is because it will be lowered to
7410     // an MSR (immediate) instruction, so we need to know the immediate at
7411     // compile time.
7412     if (TheCall->getNumArgs() != 2)
7413       return false;
7414 
7415     std::string RegLower = Reg.lower();
7416     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7417         RegLower != "pan" && RegLower != "uao")
7418       return false;
7419 
7420     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7421   }
7422 
7423   return false;
7424 }
7425 
7426 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7427 /// Emit an error and return true on failure; return false on success.
7428 /// TypeStr is a string containing the type descriptor of the value returned by
7429 /// the builtin and the descriptors of the expected type of the arguments.
7430 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7431 
7432   assert((TypeStr[0] != '\0') &&
7433          "Invalid types in PPC MMA builtin declaration");
7434 
7435   unsigned Mask = 0;
7436   unsigned ArgNum = 0;
7437 
7438   // The first type in TypeStr is the type of the value returned by the
7439   // builtin. So we first read that type and change the type of TheCall.
7440   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7441   TheCall->setType(type);
7442 
7443   while (*TypeStr != '\0') {
7444     Mask = 0;
7445     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7446     if (ArgNum >= TheCall->getNumArgs()) {
7447       ArgNum++;
7448       break;
7449     }
7450 
7451     Expr *Arg = TheCall->getArg(ArgNum);
7452     QualType ArgType = Arg->getType();
7453 
7454     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7455         (!ExpectedType->isVoidPointerType() &&
7456            ArgType.getCanonicalType() != ExpectedType))
7457       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7458              << ArgType << ExpectedType << 1 << 0 << 0;
7459 
7460     // If the value of the Mask is not 0, we have a constraint in the size of
7461     // the integer argument so here we ensure the argument is a constant that
7462     // is in the valid range.
7463     if (Mask != 0 &&
7464         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7465       return true;
7466 
7467     ArgNum++;
7468   }
7469 
7470   // In case we exited early from the previous loop, there are other types to
7471   // read from TypeStr. So we need to read them all to ensure we have the right
7472   // number of arguments in TheCall and if it is not the case, to display a
7473   // better error message.
7474   while (*TypeStr != '\0') {
7475     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7476     ArgNum++;
7477   }
7478   if (checkArgCount(*this, TheCall, ArgNum))
7479     return true;
7480 
7481   return false;
7482 }
7483 
7484 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7485 /// This checks that the target supports __builtin_longjmp and
7486 /// that val is a constant 1.
7487 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7488   if (!Context.getTargetInfo().hasSjLjLowering())
7489     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7490            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7491 
7492   Expr *Arg = TheCall->getArg(1);
7493   llvm::APSInt Result;
7494 
7495   // TODO: This is less than ideal. Overload this to take a value.
7496   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7497     return true;
7498 
7499   if (Result != 1)
7500     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7501            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7502 
7503   return false;
7504 }
7505 
7506 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7507 /// This checks that the target supports __builtin_setjmp.
7508 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7509   if (!Context.getTargetInfo().hasSjLjLowering())
7510     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7511            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7512   return false;
7513 }
7514 
7515 namespace {
7516 
7517 class UncoveredArgHandler {
7518   enum { Unknown = -1, AllCovered = -2 };
7519 
7520   signed FirstUncoveredArg = Unknown;
7521   SmallVector<const Expr *, 4> DiagnosticExprs;
7522 
7523 public:
7524   UncoveredArgHandler() = default;
7525 
7526   bool hasUncoveredArg() const {
7527     return (FirstUncoveredArg >= 0);
7528   }
7529 
7530   unsigned getUncoveredArg() const {
7531     assert(hasUncoveredArg() && "no uncovered argument");
7532     return FirstUncoveredArg;
7533   }
7534 
7535   void setAllCovered() {
7536     // A string has been found with all arguments covered, so clear out
7537     // the diagnostics.
7538     DiagnosticExprs.clear();
7539     FirstUncoveredArg = AllCovered;
7540   }
7541 
7542   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7543     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7544 
7545     // Don't update if a previous string covers all arguments.
7546     if (FirstUncoveredArg == AllCovered)
7547       return;
7548 
7549     // UncoveredArgHandler tracks the highest uncovered argument index
7550     // and with it all the strings that match this index.
7551     if (NewFirstUncoveredArg == FirstUncoveredArg)
7552       DiagnosticExprs.push_back(StrExpr);
7553     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7554       DiagnosticExprs.clear();
7555       DiagnosticExprs.push_back(StrExpr);
7556       FirstUncoveredArg = NewFirstUncoveredArg;
7557     }
7558   }
7559 
7560   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7561 };
7562 
7563 enum StringLiteralCheckType {
7564   SLCT_NotALiteral,
7565   SLCT_UncheckedLiteral,
7566   SLCT_CheckedLiteral
7567 };
7568 
7569 } // namespace
7570 
7571 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7572                                      BinaryOperatorKind BinOpKind,
7573                                      bool AddendIsRight) {
7574   unsigned BitWidth = Offset.getBitWidth();
7575   unsigned AddendBitWidth = Addend.getBitWidth();
7576   // There might be negative interim results.
7577   if (Addend.isUnsigned()) {
7578     Addend = Addend.zext(++AddendBitWidth);
7579     Addend.setIsSigned(true);
7580   }
7581   // Adjust the bit width of the APSInts.
7582   if (AddendBitWidth > BitWidth) {
7583     Offset = Offset.sext(AddendBitWidth);
7584     BitWidth = AddendBitWidth;
7585   } else if (BitWidth > AddendBitWidth) {
7586     Addend = Addend.sext(BitWidth);
7587   }
7588 
7589   bool Ov = false;
7590   llvm::APSInt ResOffset = Offset;
7591   if (BinOpKind == BO_Add)
7592     ResOffset = Offset.sadd_ov(Addend, Ov);
7593   else {
7594     assert(AddendIsRight && BinOpKind == BO_Sub &&
7595            "operator must be add or sub with addend on the right");
7596     ResOffset = Offset.ssub_ov(Addend, Ov);
7597   }
7598 
7599   // We add an offset to a pointer here so we should support an offset as big as
7600   // possible.
7601   if (Ov) {
7602     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7603            "index (intermediate) result too big");
7604     Offset = Offset.sext(2 * BitWidth);
7605     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7606     return;
7607   }
7608 
7609   Offset = ResOffset;
7610 }
7611 
7612 namespace {
7613 
7614 // This is a wrapper class around StringLiteral to support offsetted string
7615 // literals as format strings. It takes the offset into account when returning
7616 // the string and its length or the source locations to display notes correctly.
7617 class FormatStringLiteral {
7618   const StringLiteral *FExpr;
7619   int64_t Offset;
7620 
7621  public:
7622   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7623       : FExpr(fexpr), Offset(Offset) {}
7624 
7625   StringRef getString() const {
7626     return FExpr->getString().drop_front(Offset);
7627   }
7628 
7629   unsigned getByteLength() const {
7630     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7631   }
7632 
7633   unsigned getLength() const { return FExpr->getLength() - Offset; }
7634   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7635 
7636   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7637 
7638   QualType getType() const { return FExpr->getType(); }
7639 
7640   bool isAscii() const { return FExpr->isAscii(); }
7641   bool isWide() const { return FExpr->isWide(); }
7642   bool isUTF8() const { return FExpr->isUTF8(); }
7643   bool isUTF16() const { return FExpr->isUTF16(); }
7644   bool isUTF32() const { return FExpr->isUTF32(); }
7645   bool isPascal() const { return FExpr->isPascal(); }
7646 
7647   SourceLocation getLocationOfByte(
7648       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7649       const TargetInfo &Target, unsigned *StartToken = nullptr,
7650       unsigned *StartTokenByteOffset = nullptr) const {
7651     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7652                                     StartToken, StartTokenByteOffset);
7653   }
7654 
7655   SourceLocation getBeginLoc() const LLVM_READONLY {
7656     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7657   }
7658 
7659   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7660 };
7661 
7662 }  // namespace
7663 
7664 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7665                               const Expr *OrigFormatExpr,
7666                               ArrayRef<const Expr *> Args,
7667                               bool HasVAListArg, unsigned format_idx,
7668                               unsigned firstDataArg,
7669                               Sema::FormatStringType Type,
7670                               bool inFunctionCall,
7671                               Sema::VariadicCallType CallType,
7672                               llvm::SmallBitVector &CheckedVarArgs,
7673                               UncoveredArgHandler &UncoveredArg,
7674                               bool IgnoreStringsWithoutSpecifiers);
7675 
7676 // Determine if an expression is a string literal or constant string.
7677 // If this function returns false on the arguments to a function expecting a
7678 // format string, we will usually need to emit a warning.
7679 // True string literals are then checked by CheckFormatString.
7680 static StringLiteralCheckType
7681 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7682                       bool HasVAListArg, unsigned format_idx,
7683                       unsigned firstDataArg, Sema::FormatStringType Type,
7684                       Sema::VariadicCallType CallType, bool InFunctionCall,
7685                       llvm::SmallBitVector &CheckedVarArgs,
7686                       UncoveredArgHandler &UncoveredArg,
7687                       llvm::APSInt Offset,
7688                       bool IgnoreStringsWithoutSpecifiers = false) {
7689   if (S.isConstantEvaluated())
7690     return SLCT_NotALiteral;
7691  tryAgain:
7692   assert(Offset.isSigned() && "invalid offset");
7693 
7694   if (E->isTypeDependent() || E->isValueDependent())
7695     return SLCT_NotALiteral;
7696 
7697   E = E->IgnoreParenCasts();
7698 
7699   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7700     // Technically -Wformat-nonliteral does not warn about this case.
7701     // The behavior of printf and friends in this case is implementation
7702     // dependent.  Ideally if the format string cannot be null then
7703     // it should have a 'nonnull' attribute in the function prototype.
7704     return SLCT_UncheckedLiteral;
7705 
7706   switch (E->getStmtClass()) {
7707   case Stmt::BinaryConditionalOperatorClass:
7708   case Stmt::ConditionalOperatorClass: {
7709     // The expression is a literal if both sub-expressions were, and it was
7710     // completely checked only if both sub-expressions were checked.
7711     const AbstractConditionalOperator *C =
7712         cast<AbstractConditionalOperator>(E);
7713 
7714     // Determine whether it is necessary to check both sub-expressions, for
7715     // example, because the condition expression is a constant that can be
7716     // evaluated at compile time.
7717     bool CheckLeft = true, CheckRight = true;
7718 
7719     bool Cond;
7720     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7721                                                  S.isConstantEvaluated())) {
7722       if (Cond)
7723         CheckRight = false;
7724       else
7725         CheckLeft = false;
7726     }
7727 
7728     // We need to maintain the offsets for the right and the left hand side
7729     // separately to check if every possible indexed expression is a valid
7730     // string literal. They might have different offsets for different string
7731     // literals in the end.
7732     StringLiteralCheckType Left;
7733     if (!CheckLeft)
7734       Left = SLCT_UncheckedLiteral;
7735     else {
7736       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7737                                    HasVAListArg, format_idx, firstDataArg,
7738                                    Type, CallType, InFunctionCall,
7739                                    CheckedVarArgs, UncoveredArg, Offset,
7740                                    IgnoreStringsWithoutSpecifiers);
7741       if (Left == SLCT_NotALiteral || !CheckRight) {
7742         return Left;
7743       }
7744     }
7745 
7746     StringLiteralCheckType Right = checkFormatStringExpr(
7747         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7748         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7749         IgnoreStringsWithoutSpecifiers);
7750 
7751     return (CheckLeft && Left < Right) ? Left : Right;
7752   }
7753 
7754   case Stmt::ImplicitCastExprClass:
7755     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7756     goto tryAgain;
7757 
7758   case Stmt::OpaqueValueExprClass:
7759     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7760       E = src;
7761       goto tryAgain;
7762     }
7763     return SLCT_NotALiteral;
7764 
7765   case Stmt::PredefinedExprClass:
7766     // While __func__, etc., are technically not string literals, they
7767     // cannot contain format specifiers and thus are not a security
7768     // liability.
7769     return SLCT_UncheckedLiteral;
7770 
7771   case Stmt::DeclRefExprClass: {
7772     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7773 
7774     // As an exception, do not flag errors for variables binding to
7775     // const string literals.
7776     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7777       bool isConstant = false;
7778       QualType T = DR->getType();
7779 
7780       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7781         isConstant = AT->getElementType().isConstant(S.Context);
7782       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7783         isConstant = T.isConstant(S.Context) &&
7784                      PT->getPointeeType().isConstant(S.Context);
7785       } else if (T->isObjCObjectPointerType()) {
7786         // In ObjC, there is usually no "const ObjectPointer" type,
7787         // so don't check if the pointee type is constant.
7788         isConstant = T.isConstant(S.Context);
7789       }
7790 
7791       if (isConstant) {
7792         if (const Expr *Init = VD->getAnyInitializer()) {
7793           // Look through initializers like const char c[] = { "foo" }
7794           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7795             if (InitList->isStringLiteralInit())
7796               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7797           }
7798           return checkFormatStringExpr(S, Init, Args,
7799                                        HasVAListArg, format_idx,
7800                                        firstDataArg, Type, CallType,
7801                                        /*InFunctionCall*/ false, CheckedVarArgs,
7802                                        UncoveredArg, Offset);
7803         }
7804       }
7805 
7806       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7807       // special check to see if the format string is a function parameter
7808       // of the function calling the printf function.  If the function
7809       // has an attribute indicating it is a printf-like function, then we
7810       // should suppress warnings concerning non-literals being used in a call
7811       // to a vprintf function.  For example:
7812       //
7813       // void
7814       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7815       //      va_list ap;
7816       //      va_start(ap, fmt);
7817       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7818       //      ...
7819       // }
7820       if (HasVAListArg) {
7821         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7822           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7823             int PVIndex = PV->getFunctionScopeIndex() + 1;
7824             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7825               // adjust for implicit parameter
7826               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7827                 if (MD->isInstance())
7828                   ++PVIndex;
7829               // We also check if the formats are compatible.
7830               // We can't pass a 'scanf' string to a 'printf' function.
7831               if (PVIndex == PVFormat->getFormatIdx() &&
7832                   Type == S.GetFormatStringType(PVFormat))
7833                 return SLCT_UncheckedLiteral;
7834             }
7835           }
7836         }
7837       }
7838     }
7839 
7840     return SLCT_NotALiteral;
7841   }
7842 
7843   case Stmt::CallExprClass:
7844   case Stmt::CXXMemberCallExprClass: {
7845     const CallExpr *CE = cast<CallExpr>(E);
7846     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7847       bool IsFirst = true;
7848       StringLiteralCheckType CommonResult;
7849       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7850         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7851         StringLiteralCheckType Result = checkFormatStringExpr(
7852             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7853             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7854             IgnoreStringsWithoutSpecifiers);
7855         if (IsFirst) {
7856           CommonResult = Result;
7857           IsFirst = false;
7858         }
7859       }
7860       if (!IsFirst)
7861         return CommonResult;
7862 
7863       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7864         unsigned BuiltinID = FD->getBuiltinID();
7865         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7866             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7867           const Expr *Arg = CE->getArg(0);
7868           return checkFormatStringExpr(S, Arg, Args,
7869                                        HasVAListArg, format_idx,
7870                                        firstDataArg, Type, CallType,
7871                                        InFunctionCall, CheckedVarArgs,
7872                                        UncoveredArg, Offset,
7873                                        IgnoreStringsWithoutSpecifiers);
7874         }
7875       }
7876     }
7877 
7878     return SLCT_NotALiteral;
7879   }
7880   case Stmt::ObjCMessageExprClass: {
7881     const auto *ME = cast<ObjCMessageExpr>(E);
7882     if (const auto *MD = ME->getMethodDecl()) {
7883       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7884         // As a special case heuristic, if we're using the method -[NSBundle
7885         // localizedStringForKey:value:table:], ignore any key strings that lack
7886         // format specifiers. The idea is that if the key doesn't have any
7887         // format specifiers then its probably just a key to map to the
7888         // localized strings. If it does have format specifiers though, then its
7889         // likely that the text of the key is the format string in the
7890         // programmer's language, and should be checked.
7891         const ObjCInterfaceDecl *IFace;
7892         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7893             IFace->getIdentifier()->isStr("NSBundle") &&
7894             MD->getSelector().isKeywordSelector(
7895                 {"localizedStringForKey", "value", "table"})) {
7896           IgnoreStringsWithoutSpecifiers = true;
7897         }
7898 
7899         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7900         return checkFormatStringExpr(
7901             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7902             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7903             IgnoreStringsWithoutSpecifiers);
7904       }
7905     }
7906 
7907     return SLCT_NotALiteral;
7908   }
7909   case Stmt::ObjCStringLiteralClass:
7910   case Stmt::StringLiteralClass: {
7911     const StringLiteral *StrE = nullptr;
7912 
7913     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7914       StrE = ObjCFExpr->getString();
7915     else
7916       StrE = cast<StringLiteral>(E);
7917 
7918     if (StrE) {
7919       if (Offset.isNegative() || Offset > StrE->getLength()) {
7920         // TODO: It would be better to have an explicit warning for out of
7921         // bounds literals.
7922         return SLCT_NotALiteral;
7923       }
7924       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7925       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7926                         firstDataArg, Type, InFunctionCall, CallType,
7927                         CheckedVarArgs, UncoveredArg,
7928                         IgnoreStringsWithoutSpecifiers);
7929       return SLCT_CheckedLiteral;
7930     }
7931 
7932     return SLCT_NotALiteral;
7933   }
7934   case Stmt::BinaryOperatorClass: {
7935     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7936 
7937     // A string literal + an int offset is still a string literal.
7938     if (BinOp->isAdditiveOp()) {
7939       Expr::EvalResult LResult, RResult;
7940 
7941       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7942           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7943       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7944           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7945 
7946       if (LIsInt != RIsInt) {
7947         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7948 
7949         if (LIsInt) {
7950           if (BinOpKind == BO_Add) {
7951             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7952             E = BinOp->getRHS();
7953             goto tryAgain;
7954           }
7955         } else {
7956           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7957           E = BinOp->getLHS();
7958           goto tryAgain;
7959         }
7960       }
7961     }
7962 
7963     return SLCT_NotALiteral;
7964   }
7965   case Stmt::UnaryOperatorClass: {
7966     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7967     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7968     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7969       Expr::EvalResult IndexResult;
7970       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7971                                        Expr::SE_NoSideEffects,
7972                                        S.isConstantEvaluated())) {
7973         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7974                    /*RHS is int*/ true);
7975         E = ASE->getBase();
7976         goto tryAgain;
7977       }
7978     }
7979 
7980     return SLCT_NotALiteral;
7981   }
7982 
7983   default:
7984     return SLCT_NotALiteral;
7985   }
7986 }
7987 
7988 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7989   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7990       .Case("scanf", FST_Scanf)
7991       .Cases("printf", "printf0", FST_Printf)
7992       .Cases("NSString", "CFString", FST_NSString)
7993       .Case("strftime", FST_Strftime)
7994       .Case("strfmon", FST_Strfmon)
7995       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7996       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7997       .Case("os_trace", FST_OSLog)
7998       .Case("os_log", FST_OSLog)
7999       .Default(FST_Unknown);
8000 }
8001 
8002 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8003 /// functions) for correct use of format strings.
8004 /// Returns true if a format string has been fully checked.
8005 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8006                                 ArrayRef<const Expr *> Args,
8007                                 bool IsCXXMember,
8008                                 VariadicCallType CallType,
8009                                 SourceLocation Loc, SourceRange Range,
8010                                 llvm::SmallBitVector &CheckedVarArgs) {
8011   FormatStringInfo FSI;
8012   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8013     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8014                                 FSI.FirstDataArg, GetFormatStringType(Format),
8015                                 CallType, Loc, Range, CheckedVarArgs);
8016   return false;
8017 }
8018 
8019 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8020                                 bool HasVAListArg, unsigned format_idx,
8021                                 unsigned firstDataArg, FormatStringType Type,
8022                                 VariadicCallType CallType,
8023                                 SourceLocation Loc, SourceRange Range,
8024                                 llvm::SmallBitVector &CheckedVarArgs) {
8025   // CHECK: printf/scanf-like function is called with no format string.
8026   if (format_idx >= Args.size()) {
8027     Diag(Loc, diag::warn_missing_format_string) << Range;
8028     return false;
8029   }
8030 
8031   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8032 
8033   // CHECK: format string is not a string literal.
8034   //
8035   // Dynamically generated format strings are difficult to
8036   // automatically vet at compile time.  Requiring that format strings
8037   // are string literals: (1) permits the checking of format strings by
8038   // the compiler and thereby (2) can practically remove the source of
8039   // many format string exploits.
8040 
8041   // Format string can be either ObjC string (e.g. @"%d") or
8042   // C string (e.g. "%d")
8043   // ObjC string uses the same format specifiers as C string, so we can use
8044   // the same format string checking logic for both ObjC and C strings.
8045   UncoveredArgHandler UncoveredArg;
8046   StringLiteralCheckType CT =
8047       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8048                             format_idx, firstDataArg, Type, CallType,
8049                             /*IsFunctionCall*/ true, CheckedVarArgs,
8050                             UncoveredArg,
8051                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8052 
8053   // Generate a diagnostic where an uncovered argument is detected.
8054   if (UncoveredArg.hasUncoveredArg()) {
8055     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8056     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8057     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8058   }
8059 
8060   if (CT != SLCT_NotALiteral)
8061     // Literal format string found, check done!
8062     return CT == SLCT_CheckedLiteral;
8063 
8064   // Strftime is particular as it always uses a single 'time' argument,
8065   // so it is safe to pass a non-literal string.
8066   if (Type == FST_Strftime)
8067     return false;
8068 
8069   // Do not emit diag when the string param is a macro expansion and the
8070   // format is either NSString or CFString. This is a hack to prevent
8071   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8072   // which are usually used in place of NS and CF string literals.
8073   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8074   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8075     return false;
8076 
8077   // If there are no arguments specified, warn with -Wformat-security, otherwise
8078   // warn only with -Wformat-nonliteral.
8079   if (Args.size() == firstDataArg) {
8080     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8081       << OrigFormatExpr->getSourceRange();
8082     switch (Type) {
8083     default:
8084       break;
8085     case FST_Kprintf:
8086     case FST_FreeBSDKPrintf:
8087     case FST_Printf:
8088       Diag(FormatLoc, diag::note_format_security_fixit)
8089         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8090       break;
8091     case FST_NSString:
8092       Diag(FormatLoc, diag::note_format_security_fixit)
8093         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8094       break;
8095     }
8096   } else {
8097     Diag(FormatLoc, diag::warn_format_nonliteral)
8098       << OrigFormatExpr->getSourceRange();
8099   }
8100   return false;
8101 }
8102 
8103 namespace {
8104 
8105 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8106 protected:
8107   Sema &S;
8108   const FormatStringLiteral *FExpr;
8109   const Expr *OrigFormatExpr;
8110   const Sema::FormatStringType FSType;
8111   const unsigned FirstDataArg;
8112   const unsigned NumDataArgs;
8113   const char *Beg; // Start of format string.
8114   const bool HasVAListArg;
8115   ArrayRef<const Expr *> Args;
8116   unsigned FormatIdx;
8117   llvm::SmallBitVector CoveredArgs;
8118   bool usesPositionalArgs = false;
8119   bool atFirstArg = true;
8120   bool inFunctionCall;
8121   Sema::VariadicCallType CallType;
8122   llvm::SmallBitVector &CheckedVarArgs;
8123   UncoveredArgHandler &UncoveredArg;
8124 
8125 public:
8126   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8127                      const Expr *origFormatExpr,
8128                      const Sema::FormatStringType type, unsigned firstDataArg,
8129                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8130                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8131                      bool inFunctionCall, Sema::VariadicCallType callType,
8132                      llvm::SmallBitVector &CheckedVarArgs,
8133                      UncoveredArgHandler &UncoveredArg)
8134       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8135         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8136         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8137         inFunctionCall(inFunctionCall), CallType(callType),
8138         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8139     CoveredArgs.resize(numDataArgs);
8140     CoveredArgs.reset();
8141   }
8142 
8143   void DoneProcessing();
8144 
8145   void HandleIncompleteSpecifier(const char *startSpecifier,
8146                                  unsigned specifierLen) override;
8147 
8148   void HandleInvalidLengthModifier(
8149                            const analyze_format_string::FormatSpecifier &FS,
8150                            const analyze_format_string::ConversionSpecifier &CS,
8151                            const char *startSpecifier, unsigned specifierLen,
8152                            unsigned DiagID);
8153 
8154   void HandleNonStandardLengthModifier(
8155                     const analyze_format_string::FormatSpecifier &FS,
8156                     const char *startSpecifier, unsigned specifierLen);
8157 
8158   void HandleNonStandardConversionSpecifier(
8159                     const analyze_format_string::ConversionSpecifier &CS,
8160                     const char *startSpecifier, unsigned specifierLen);
8161 
8162   void HandlePosition(const char *startPos, unsigned posLen) override;
8163 
8164   void HandleInvalidPosition(const char *startSpecifier,
8165                              unsigned specifierLen,
8166                              analyze_format_string::PositionContext p) override;
8167 
8168   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8169 
8170   void HandleNullChar(const char *nullCharacter) override;
8171 
8172   template <typename Range>
8173   static void
8174   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8175                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8176                        bool IsStringLocation, Range StringRange,
8177                        ArrayRef<FixItHint> Fixit = None);
8178 
8179 protected:
8180   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8181                                         const char *startSpec,
8182                                         unsigned specifierLen,
8183                                         const char *csStart, unsigned csLen);
8184 
8185   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8186                                          const char *startSpec,
8187                                          unsigned specifierLen);
8188 
8189   SourceRange getFormatStringRange();
8190   CharSourceRange getSpecifierRange(const char *startSpecifier,
8191                                     unsigned specifierLen);
8192   SourceLocation getLocationOfByte(const char *x);
8193 
8194   const Expr *getDataArg(unsigned i) const;
8195 
8196   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8197                     const analyze_format_string::ConversionSpecifier &CS,
8198                     const char *startSpecifier, unsigned specifierLen,
8199                     unsigned argIndex);
8200 
8201   template <typename Range>
8202   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8203                             bool IsStringLocation, Range StringRange,
8204                             ArrayRef<FixItHint> Fixit = None);
8205 };
8206 
8207 } // namespace
8208 
8209 SourceRange CheckFormatHandler::getFormatStringRange() {
8210   return OrigFormatExpr->getSourceRange();
8211 }
8212 
8213 CharSourceRange CheckFormatHandler::
8214 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8215   SourceLocation Start = getLocationOfByte(startSpecifier);
8216   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8217 
8218   // Advance the end SourceLocation by one due to half-open ranges.
8219   End = End.getLocWithOffset(1);
8220 
8221   return CharSourceRange::getCharRange(Start, End);
8222 }
8223 
8224 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8225   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8226                                   S.getLangOpts(), S.Context.getTargetInfo());
8227 }
8228 
8229 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8230                                                    unsigned specifierLen){
8231   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8232                        getLocationOfByte(startSpecifier),
8233                        /*IsStringLocation*/true,
8234                        getSpecifierRange(startSpecifier, specifierLen));
8235 }
8236 
8237 void CheckFormatHandler::HandleInvalidLengthModifier(
8238     const analyze_format_string::FormatSpecifier &FS,
8239     const analyze_format_string::ConversionSpecifier &CS,
8240     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8241   using namespace analyze_format_string;
8242 
8243   const LengthModifier &LM = FS.getLengthModifier();
8244   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8245 
8246   // See if we know how to fix this length modifier.
8247   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8248   if (FixedLM) {
8249     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8250                          getLocationOfByte(LM.getStart()),
8251                          /*IsStringLocation*/true,
8252                          getSpecifierRange(startSpecifier, specifierLen));
8253 
8254     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8255       << FixedLM->toString()
8256       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8257 
8258   } else {
8259     FixItHint Hint;
8260     if (DiagID == diag::warn_format_nonsensical_length)
8261       Hint = FixItHint::CreateRemoval(LMRange);
8262 
8263     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8264                          getLocationOfByte(LM.getStart()),
8265                          /*IsStringLocation*/true,
8266                          getSpecifierRange(startSpecifier, specifierLen),
8267                          Hint);
8268   }
8269 }
8270 
8271 void CheckFormatHandler::HandleNonStandardLengthModifier(
8272     const analyze_format_string::FormatSpecifier &FS,
8273     const char *startSpecifier, unsigned specifierLen) {
8274   using namespace analyze_format_string;
8275 
8276   const LengthModifier &LM = FS.getLengthModifier();
8277   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8278 
8279   // See if we know how to fix this length modifier.
8280   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8281   if (FixedLM) {
8282     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8283                            << LM.toString() << 0,
8284                          getLocationOfByte(LM.getStart()),
8285                          /*IsStringLocation*/true,
8286                          getSpecifierRange(startSpecifier, specifierLen));
8287 
8288     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8289       << FixedLM->toString()
8290       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8291 
8292   } else {
8293     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8294                            << LM.toString() << 0,
8295                          getLocationOfByte(LM.getStart()),
8296                          /*IsStringLocation*/true,
8297                          getSpecifierRange(startSpecifier, specifierLen));
8298   }
8299 }
8300 
8301 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8302     const analyze_format_string::ConversionSpecifier &CS,
8303     const char *startSpecifier, unsigned specifierLen) {
8304   using namespace analyze_format_string;
8305 
8306   // See if we know how to fix this conversion specifier.
8307   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8308   if (FixedCS) {
8309     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8310                           << CS.toString() << /*conversion specifier*/1,
8311                          getLocationOfByte(CS.getStart()),
8312                          /*IsStringLocation*/true,
8313                          getSpecifierRange(startSpecifier, specifierLen));
8314 
8315     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8316     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8317       << FixedCS->toString()
8318       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8319   } else {
8320     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8321                           << CS.toString() << /*conversion specifier*/1,
8322                          getLocationOfByte(CS.getStart()),
8323                          /*IsStringLocation*/true,
8324                          getSpecifierRange(startSpecifier, specifierLen));
8325   }
8326 }
8327 
8328 void CheckFormatHandler::HandlePosition(const char *startPos,
8329                                         unsigned posLen) {
8330   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8331                                getLocationOfByte(startPos),
8332                                /*IsStringLocation*/true,
8333                                getSpecifierRange(startPos, posLen));
8334 }
8335 
8336 void
8337 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8338                                      analyze_format_string::PositionContext p) {
8339   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8340                          << (unsigned) p,
8341                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8342                        getSpecifierRange(startPos, posLen));
8343 }
8344 
8345 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8346                                             unsigned posLen) {
8347   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8348                                getLocationOfByte(startPos),
8349                                /*IsStringLocation*/true,
8350                                getSpecifierRange(startPos, posLen));
8351 }
8352 
8353 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8354   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8355     // The presence of a null character is likely an error.
8356     EmitFormatDiagnostic(
8357       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8358       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8359       getFormatStringRange());
8360   }
8361 }
8362 
8363 // Note that this may return NULL if there was an error parsing or building
8364 // one of the argument expressions.
8365 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8366   return Args[FirstDataArg + i];
8367 }
8368 
8369 void CheckFormatHandler::DoneProcessing() {
8370   // Does the number of data arguments exceed the number of
8371   // format conversions in the format string?
8372   if (!HasVAListArg) {
8373       // Find any arguments that weren't covered.
8374     CoveredArgs.flip();
8375     signed notCoveredArg = CoveredArgs.find_first();
8376     if (notCoveredArg >= 0) {
8377       assert((unsigned)notCoveredArg < NumDataArgs);
8378       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8379     } else {
8380       UncoveredArg.setAllCovered();
8381     }
8382   }
8383 }
8384 
8385 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8386                                    const Expr *ArgExpr) {
8387   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8388          "Invalid state");
8389 
8390   if (!ArgExpr)
8391     return;
8392 
8393   SourceLocation Loc = ArgExpr->getBeginLoc();
8394 
8395   if (S.getSourceManager().isInSystemMacro(Loc))
8396     return;
8397 
8398   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8399   for (auto E : DiagnosticExprs)
8400     PDiag << E->getSourceRange();
8401 
8402   CheckFormatHandler::EmitFormatDiagnostic(
8403                                   S, IsFunctionCall, DiagnosticExprs[0],
8404                                   PDiag, Loc, /*IsStringLocation*/false,
8405                                   DiagnosticExprs[0]->getSourceRange());
8406 }
8407 
8408 bool
8409 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8410                                                      SourceLocation Loc,
8411                                                      const char *startSpec,
8412                                                      unsigned specifierLen,
8413                                                      const char *csStart,
8414                                                      unsigned csLen) {
8415   bool keepGoing = true;
8416   if (argIndex < NumDataArgs) {
8417     // Consider the argument coverered, even though the specifier doesn't
8418     // make sense.
8419     CoveredArgs.set(argIndex);
8420   }
8421   else {
8422     // If argIndex exceeds the number of data arguments we
8423     // don't issue a warning because that is just a cascade of warnings (and
8424     // they may have intended '%%' anyway). We don't want to continue processing
8425     // the format string after this point, however, as we will like just get
8426     // gibberish when trying to match arguments.
8427     keepGoing = false;
8428   }
8429 
8430   StringRef Specifier(csStart, csLen);
8431 
8432   // If the specifier in non-printable, it could be the first byte of a UTF-8
8433   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8434   // hex value.
8435   std::string CodePointStr;
8436   if (!llvm::sys::locale::isPrint(*csStart)) {
8437     llvm::UTF32 CodePoint;
8438     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8439     const llvm::UTF8 *E =
8440         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8441     llvm::ConversionResult Result =
8442         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8443 
8444     if (Result != llvm::conversionOK) {
8445       unsigned char FirstChar = *csStart;
8446       CodePoint = (llvm::UTF32)FirstChar;
8447     }
8448 
8449     llvm::raw_string_ostream OS(CodePointStr);
8450     if (CodePoint < 256)
8451       OS << "\\x" << llvm::format("%02x", CodePoint);
8452     else if (CodePoint <= 0xFFFF)
8453       OS << "\\u" << llvm::format("%04x", CodePoint);
8454     else
8455       OS << "\\U" << llvm::format("%08x", CodePoint);
8456     OS.flush();
8457     Specifier = CodePointStr;
8458   }
8459 
8460   EmitFormatDiagnostic(
8461       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8462       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8463 
8464   return keepGoing;
8465 }
8466 
8467 void
8468 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8469                                                       const char *startSpec,
8470                                                       unsigned specifierLen) {
8471   EmitFormatDiagnostic(
8472     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8473     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8474 }
8475 
8476 bool
8477 CheckFormatHandler::CheckNumArgs(
8478   const analyze_format_string::FormatSpecifier &FS,
8479   const analyze_format_string::ConversionSpecifier &CS,
8480   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8481 
8482   if (argIndex >= NumDataArgs) {
8483     PartialDiagnostic PDiag = FS.usesPositionalArg()
8484       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8485            << (argIndex+1) << NumDataArgs)
8486       : S.PDiag(diag::warn_printf_insufficient_data_args);
8487     EmitFormatDiagnostic(
8488       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8489       getSpecifierRange(startSpecifier, specifierLen));
8490 
8491     // Since more arguments than conversion tokens are given, by extension
8492     // all arguments are covered, so mark this as so.
8493     UncoveredArg.setAllCovered();
8494     return false;
8495   }
8496   return true;
8497 }
8498 
8499 template<typename Range>
8500 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8501                                               SourceLocation Loc,
8502                                               bool IsStringLocation,
8503                                               Range StringRange,
8504                                               ArrayRef<FixItHint> FixIt) {
8505   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8506                        Loc, IsStringLocation, StringRange, FixIt);
8507 }
8508 
8509 /// If the format string is not within the function call, emit a note
8510 /// so that the function call and string are in diagnostic messages.
8511 ///
8512 /// \param InFunctionCall if true, the format string is within the function
8513 /// call and only one diagnostic message will be produced.  Otherwise, an
8514 /// extra note will be emitted pointing to location of the format string.
8515 ///
8516 /// \param ArgumentExpr the expression that is passed as the format string
8517 /// argument in the function call.  Used for getting locations when two
8518 /// diagnostics are emitted.
8519 ///
8520 /// \param PDiag the callee should already have provided any strings for the
8521 /// diagnostic message.  This function only adds locations and fixits
8522 /// to diagnostics.
8523 ///
8524 /// \param Loc primary location for diagnostic.  If two diagnostics are
8525 /// required, one will be at Loc and a new SourceLocation will be created for
8526 /// the other one.
8527 ///
8528 /// \param IsStringLocation if true, Loc points to the format string should be
8529 /// used for the note.  Otherwise, Loc points to the argument list and will
8530 /// be used with PDiag.
8531 ///
8532 /// \param StringRange some or all of the string to highlight.  This is
8533 /// templated so it can accept either a CharSourceRange or a SourceRange.
8534 ///
8535 /// \param FixIt optional fix it hint for the format string.
8536 template <typename Range>
8537 void CheckFormatHandler::EmitFormatDiagnostic(
8538     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8539     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8540     Range StringRange, ArrayRef<FixItHint> FixIt) {
8541   if (InFunctionCall) {
8542     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8543     D << StringRange;
8544     D << FixIt;
8545   } else {
8546     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8547       << ArgumentExpr->getSourceRange();
8548 
8549     const Sema::SemaDiagnosticBuilder &Note =
8550       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8551              diag::note_format_string_defined);
8552 
8553     Note << StringRange;
8554     Note << FixIt;
8555   }
8556 }
8557 
8558 //===--- CHECK: Printf format string checking ------------------------------===//
8559 
8560 namespace {
8561 
8562 class CheckPrintfHandler : public CheckFormatHandler {
8563 public:
8564   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8565                      const Expr *origFormatExpr,
8566                      const Sema::FormatStringType type, unsigned firstDataArg,
8567                      unsigned numDataArgs, bool isObjC, const char *beg,
8568                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8569                      unsigned formatIdx, bool inFunctionCall,
8570                      Sema::VariadicCallType CallType,
8571                      llvm::SmallBitVector &CheckedVarArgs,
8572                      UncoveredArgHandler &UncoveredArg)
8573       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8574                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8575                            inFunctionCall, CallType, CheckedVarArgs,
8576                            UncoveredArg) {}
8577 
8578   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8579 
8580   /// Returns true if '%@' specifiers are allowed in the format string.
8581   bool allowsObjCArg() const {
8582     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8583            FSType == Sema::FST_OSTrace;
8584   }
8585 
8586   bool HandleInvalidPrintfConversionSpecifier(
8587                                       const analyze_printf::PrintfSpecifier &FS,
8588                                       const char *startSpecifier,
8589                                       unsigned specifierLen) override;
8590 
8591   void handleInvalidMaskType(StringRef MaskType) override;
8592 
8593   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8594                              const char *startSpecifier,
8595                              unsigned specifierLen) override;
8596   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8597                        const char *StartSpecifier,
8598                        unsigned SpecifierLen,
8599                        const Expr *E);
8600 
8601   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8602                     const char *startSpecifier, unsigned specifierLen);
8603   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8604                            const analyze_printf::OptionalAmount &Amt,
8605                            unsigned type,
8606                            const char *startSpecifier, unsigned specifierLen);
8607   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8608                   const analyze_printf::OptionalFlag &flag,
8609                   const char *startSpecifier, unsigned specifierLen);
8610   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8611                          const analyze_printf::OptionalFlag &ignoredFlag,
8612                          const analyze_printf::OptionalFlag &flag,
8613                          const char *startSpecifier, unsigned specifierLen);
8614   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8615                            const Expr *E);
8616 
8617   void HandleEmptyObjCModifierFlag(const char *startFlag,
8618                                    unsigned flagLen) override;
8619 
8620   void HandleInvalidObjCModifierFlag(const char *startFlag,
8621                                             unsigned flagLen) override;
8622 
8623   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8624                                            const char *flagsEnd,
8625                                            const char *conversionPosition)
8626                                              override;
8627 };
8628 
8629 } // namespace
8630 
8631 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8632                                       const analyze_printf::PrintfSpecifier &FS,
8633                                       const char *startSpecifier,
8634                                       unsigned specifierLen) {
8635   const analyze_printf::PrintfConversionSpecifier &CS =
8636     FS.getConversionSpecifier();
8637 
8638   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8639                                           getLocationOfByte(CS.getStart()),
8640                                           startSpecifier, specifierLen,
8641                                           CS.getStart(), CS.getLength());
8642 }
8643 
8644 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8645   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8646 }
8647 
8648 bool CheckPrintfHandler::HandleAmount(
8649                                const analyze_format_string::OptionalAmount &Amt,
8650                                unsigned k, const char *startSpecifier,
8651                                unsigned specifierLen) {
8652   if (Amt.hasDataArgument()) {
8653     if (!HasVAListArg) {
8654       unsigned argIndex = Amt.getArgIndex();
8655       if (argIndex >= NumDataArgs) {
8656         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8657                                << k,
8658                              getLocationOfByte(Amt.getStart()),
8659                              /*IsStringLocation*/true,
8660                              getSpecifierRange(startSpecifier, specifierLen));
8661         // Don't do any more checking.  We will just emit
8662         // spurious errors.
8663         return false;
8664       }
8665 
8666       // Type check the data argument.  It should be an 'int'.
8667       // Although not in conformance with C99, we also allow the argument to be
8668       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8669       // doesn't emit a warning for that case.
8670       CoveredArgs.set(argIndex);
8671       const Expr *Arg = getDataArg(argIndex);
8672       if (!Arg)
8673         return false;
8674 
8675       QualType T = Arg->getType();
8676 
8677       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8678       assert(AT.isValid());
8679 
8680       if (!AT.matchesType(S.Context, T)) {
8681         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8682                                << k << AT.getRepresentativeTypeName(S.Context)
8683                                << T << Arg->getSourceRange(),
8684                              getLocationOfByte(Amt.getStart()),
8685                              /*IsStringLocation*/true,
8686                              getSpecifierRange(startSpecifier, specifierLen));
8687         // Don't do any more checking.  We will just emit
8688         // spurious errors.
8689         return false;
8690       }
8691     }
8692   }
8693   return true;
8694 }
8695 
8696 void CheckPrintfHandler::HandleInvalidAmount(
8697                                       const analyze_printf::PrintfSpecifier &FS,
8698                                       const analyze_printf::OptionalAmount &Amt,
8699                                       unsigned type,
8700                                       const char *startSpecifier,
8701                                       unsigned specifierLen) {
8702   const analyze_printf::PrintfConversionSpecifier &CS =
8703     FS.getConversionSpecifier();
8704 
8705   FixItHint fixit =
8706     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8707       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8708                                  Amt.getConstantLength()))
8709       : FixItHint();
8710 
8711   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8712                          << type << CS.toString(),
8713                        getLocationOfByte(Amt.getStart()),
8714                        /*IsStringLocation*/true,
8715                        getSpecifierRange(startSpecifier, specifierLen),
8716                        fixit);
8717 }
8718 
8719 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8720                                     const analyze_printf::OptionalFlag &flag,
8721                                     const char *startSpecifier,
8722                                     unsigned specifierLen) {
8723   // Warn about pointless flag with a fixit removal.
8724   const analyze_printf::PrintfConversionSpecifier &CS =
8725     FS.getConversionSpecifier();
8726   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8727                          << flag.toString() << CS.toString(),
8728                        getLocationOfByte(flag.getPosition()),
8729                        /*IsStringLocation*/true,
8730                        getSpecifierRange(startSpecifier, specifierLen),
8731                        FixItHint::CreateRemoval(
8732                          getSpecifierRange(flag.getPosition(), 1)));
8733 }
8734 
8735 void CheckPrintfHandler::HandleIgnoredFlag(
8736                                 const analyze_printf::PrintfSpecifier &FS,
8737                                 const analyze_printf::OptionalFlag &ignoredFlag,
8738                                 const analyze_printf::OptionalFlag &flag,
8739                                 const char *startSpecifier,
8740                                 unsigned specifierLen) {
8741   // Warn about ignored flag with a fixit removal.
8742   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8743                          << ignoredFlag.toString() << flag.toString(),
8744                        getLocationOfByte(ignoredFlag.getPosition()),
8745                        /*IsStringLocation*/true,
8746                        getSpecifierRange(startSpecifier, specifierLen),
8747                        FixItHint::CreateRemoval(
8748                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8749 }
8750 
8751 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8752                                                      unsigned flagLen) {
8753   // Warn about an empty flag.
8754   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8755                        getLocationOfByte(startFlag),
8756                        /*IsStringLocation*/true,
8757                        getSpecifierRange(startFlag, flagLen));
8758 }
8759 
8760 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8761                                                        unsigned flagLen) {
8762   // Warn about an invalid flag.
8763   auto Range = getSpecifierRange(startFlag, flagLen);
8764   StringRef flag(startFlag, flagLen);
8765   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8766                       getLocationOfByte(startFlag),
8767                       /*IsStringLocation*/true,
8768                       Range, FixItHint::CreateRemoval(Range));
8769 }
8770 
8771 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8772     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8773     // Warn about using '[...]' without a '@' conversion.
8774     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8775     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8776     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8777                          getLocationOfByte(conversionPosition),
8778                          /*IsStringLocation*/true,
8779                          Range, FixItHint::CreateRemoval(Range));
8780 }
8781 
8782 // Determines if the specified is a C++ class or struct containing
8783 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8784 // "c_str()").
8785 template<typename MemberKind>
8786 static llvm::SmallPtrSet<MemberKind*, 1>
8787 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8788   const RecordType *RT = Ty->getAs<RecordType>();
8789   llvm::SmallPtrSet<MemberKind*, 1> Results;
8790 
8791   if (!RT)
8792     return Results;
8793   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8794   if (!RD || !RD->getDefinition())
8795     return Results;
8796 
8797   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8798                  Sema::LookupMemberName);
8799   R.suppressDiagnostics();
8800 
8801   // We just need to include all members of the right kind turned up by the
8802   // filter, at this point.
8803   if (S.LookupQualifiedName(R, RT->getDecl()))
8804     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8805       NamedDecl *decl = (*I)->getUnderlyingDecl();
8806       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8807         Results.insert(FK);
8808     }
8809   return Results;
8810 }
8811 
8812 /// Check if we could call '.c_str()' on an object.
8813 ///
8814 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8815 /// allow the call, or if it would be ambiguous).
8816 bool Sema::hasCStrMethod(const Expr *E) {
8817   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8818 
8819   MethodSet Results =
8820       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8821   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8822        MI != ME; ++MI)
8823     if ((*MI)->getMinRequiredArguments() == 0)
8824       return true;
8825   return false;
8826 }
8827 
8828 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8829 // better diagnostic if so. AT is assumed to be valid.
8830 // Returns true when a c_str() conversion method is found.
8831 bool CheckPrintfHandler::checkForCStrMembers(
8832     const analyze_printf::ArgType &AT, const Expr *E) {
8833   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8834 
8835   MethodSet Results =
8836       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8837 
8838   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8839        MI != ME; ++MI) {
8840     const CXXMethodDecl *Method = *MI;
8841     if (Method->getMinRequiredArguments() == 0 &&
8842         AT.matchesType(S.Context, Method->getReturnType())) {
8843       // FIXME: Suggest parens if the expression needs them.
8844       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8845       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8846           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8847       return true;
8848     }
8849   }
8850 
8851   return false;
8852 }
8853 
8854 bool
8855 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8856                                             &FS,
8857                                           const char *startSpecifier,
8858                                           unsigned specifierLen) {
8859   using namespace analyze_format_string;
8860   using namespace analyze_printf;
8861 
8862   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8863 
8864   if (FS.consumesDataArgument()) {
8865     if (atFirstArg) {
8866         atFirstArg = false;
8867         usesPositionalArgs = FS.usesPositionalArg();
8868     }
8869     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8870       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8871                                         startSpecifier, specifierLen);
8872       return false;
8873     }
8874   }
8875 
8876   // First check if the field width, precision, and conversion specifier
8877   // have matching data arguments.
8878   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8879                     startSpecifier, specifierLen)) {
8880     return false;
8881   }
8882 
8883   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8884                     startSpecifier, specifierLen)) {
8885     return false;
8886   }
8887 
8888   if (!CS.consumesDataArgument()) {
8889     // FIXME: Technically specifying a precision or field width here
8890     // makes no sense.  Worth issuing a warning at some point.
8891     return true;
8892   }
8893 
8894   // Consume the argument.
8895   unsigned argIndex = FS.getArgIndex();
8896   if (argIndex < NumDataArgs) {
8897     // The check to see if the argIndex is valid will come later.
8898     // We set the bit here because we may exit early from this
8899     // function if we encounter some other error.
8900     CoveredArgs.set(argIndex);
8901   }
8902 
8903   // FreeBSD kernel extensions.
8904   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8905       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8906     // We need at least two arguments.
8907     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8908       return false;
8909 
8910     // Claim the second argument.
8911     CoveredArgs.set(argIndex + 1);
8912 
8913     // Type check the first argument (int for %b, pointer for %D)
8914     const Expr *Ex = getDataArg(argIndex);
8915     const analyze_printf::ArgType &AT =
8916       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8917         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8918     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8919       EmitFormatDiagnostic(
8920           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8921               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8922               << false << Ex->getSourceRange(),
8923           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8924           getSpecifierRange(startSpecifier, specifierLen));
8925 
8926     // Type check the second argument (char * for both %b and %D)
8927     Ex = getDataArg(argIndex + 1);
8928     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8929     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8930       EmitFormatDiagnostic(
8931           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8932               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8933               << false << Ex->getSourceRange(),
8934           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8935           getSpecifierRange(startSpecifier, specifierLen));
8936 
8937      return true;
8938   }
8939 
8940   // Check for using an Objective-C specific conversion specifier
8941   // in a non-ObjC literal.
8942   if (!allowsObjCArg() && CS.isObjCArg()) {
8943     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8944                                                   specifierLen);
8945   }
8946 
8947   // %P can only be used with os_log.
8948   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8949     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8950                                                   specifierLen);
8951   }
8952 
8953   // %n is not allowed with os_log.
8954   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8955     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8956                          getLocationOfByte(CS.getStart()),
8957                          /*IsStringLocation*/ false,
8958                          getSpecifierRange(startSpecifier, specifierLen));
8959 
8960     return true;
8961   }
8962 
8963   // Only scalars are allowed for os_trace.
8964   if (FSType == Sema::FST_OSTrace &&
8965       (CS.getKind() == ConversionSpecifier::PArg ||
8966        CS.getKind() == ConversionSpecifier::sArg ||
8967        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8968     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8969                                                   specifierLen);
8970   }
8971 
8972   // Check for use of public/private annotation outside of os_log().
8973   if (FSType != Sema::FST_OSLog) {
8974     if (FS.isPublic().isSet()) {
8975       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8976                                << "public",
8977                            getLocationOfByte(FS.isPublic().getPosition()),
8978                            /*IsStringLocation*/ false,
8979                            getSpecifierRange(startSpecifier, specifierLen));
8980     }
8981     if (FS.isPrivate().isSet()) {
8982       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8983                                << "private",
8984                            getLocationOfByte(FS.isPrivate().getPosition()),
8985                            /*IsStringLocation*/ false,
8986                            getSpecifierRange(startSpecifier, specifierLen));
8987     }
8988   }
8989 
8990   // Check for invalid use of field width
8991   if (!FS.hasValidFieldWidth()) {
8992     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8993         startSpecifier, specifierLen);
8994   }
8995 
8996   // Check for invalid use of precision
8997   if (!FS.hasValidPrecision()) {
8998     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8999         startSpecifier, specifierLen);
9000   }
9001 
9002   // Precision is mandatory for %P specifier.
9003   if (CS.getKind() == ConversionSpecifier::PArg &&
9004       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9005     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9006                          getLocationOfByte(startSpecifier),
9007                          /*IsStringLocation*/ false,
9008                          getSpecifierRange(startSpecifier, specifierLen));
9009   }
9010 
9011   // Check each flag does not conflict with any other component.
9012   if (!FS.hasValidThousandsGroupingPrefix())
9013     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9014   if (!FS.hasValidLeadingZeros())
9015     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9016   if (!FS.hasValidPlusPrefix())
9017     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9018   if (!FS.hasValidSpacePrefix())
9019     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9020   if (!FS.hasValidAlternativeForm())
9021     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9022   if (!FS.hasValidLeftJustified())
9023     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9024 
9025   // Check that flags are not ignored by another flag
9026   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9027     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9028         startSpecifier, specifierLen);
9029   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9030     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9031             startSpecifier, specifierLen);
9032 
9033   // Check the length modifier is valid with the given conversion specifier.
9034   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9035                                  S.getLangOpts()))
9036     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9037                                 diag::warn_format_nonsensical_length);
9038   else if (!FS.hasStandardLengthModifier())
9039     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9040   else if (!FS.hasStandardLengthConversionCombination())
9041     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9042                                 diag::warn_format_non_standard_conversion_spec);
9043 
9044   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9045     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9046 
9047   // The remaining checks depend on the data arguments.
9048   if (HasVAListArg)
9049     return true;
9050 
9051   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9052     return false;
9053 
9054   const Expr *Arg = getDataArg(argIndex);
9055   if (!Arg)
9056     return true;
9057 
9058   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9059 }
9060 
9061 static bool requiresParensToAddCast(const Expr *E) {
9062   // FIXME: We should have a general way to reason about operator
9063   // precedence and whether parens are actually needed here.
9064   // Take care of a few common cases where they aren't.
9065   const Expr *Inside = E->IgnoreImpCasts();
9066   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9067     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9068 
9069   switch (Inside->getStmtClass()) {
9070   case Stmt::ArraySubscriptExprClass:
9071   case Stmt::CallExprClass:
9072   case Stmt::CharacterLiteralClass:
9073   case Stmt::CXXBoolLiteralExprClass:
9074   case Stmt::DeclRefExprClass:
9075   case Stmt::FloatingLiteralClass:
9076   case Stmt::IntegerLiteralClass:
9077   case Stmt::MemberExprClass:
9078   case Stmt::ObjCArrayLiteralClass:
9079   case Stmt::ObjCBoolLiteralExprClass:
9080   case Stmt::ObjCBoxedExprClass:
9081   case Stmt::ObjCDictionaryLiteralClass:
9082   case Stmt::ObjCEncodeExprClass:
9083   case Stmt::ObjCIvarRefExprClass:
9084   case Stmt::ObjCMessageExprClass:
9085   case Stmt::ObjCPropertyRefExprClass:
9086   case Stmt::ObjCStringLiteralClass:
9087   case Stmt::ObjCSubscriptRefExprClass:
9088   case Stmt::ParenExprClass:
9089   case Stmt::StringLiteralClass:
9090   case Stmt::UnaryOperatorClass:
9091     return false;
9092   default:
9093     return true;
9094   }
9095 }
9096 
9097 static std::pair<QualType, StringRef>
9098 shouldNotPrintDirectly(const ASTContext &Context,
9099                        QualType IntendedTy,
9100                        const Expr *E) {
9101   // Use a 'while' to peel off layers of typedefs.
9102   QualType TyTy = IntendedTy;
9103   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9104     StringRef Name = UserTy->getDecl()->getName();
9105     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9106       .Case("CFIndex", Context.getNSIntegerType())
9107       .Case("NSInteger", Context.getNSIntegerType())
9108       .Case("NSUInteger", Context.getNSUIntegerType())
9109       .Case("SInt32", Context.IntTy)
9110       .Case("UInt32", Context.UnsignedIntTy)
9111       .Default(QualType());
9112 
9113     if (!CastTy.isNull())
9114       return std::make_pair(CastTy, Name);
9115 
9116     TyTy = UserTy->desugar();
9117   }
9118 
9119   // Strip parens if necessary.
9120   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9121     return shouldNotPrintDirectly(Context,
9122                                   PE->getSubExpr()->getType(),
9123                                   PE->getSubExpr());
9124 
9125   // If this is a conditional expression, then its result type is constructed
9126   // via usual arithmetic conversions and thus there might be no necessary
9127   // typedef sugar there.  Recurse to operands to check for NSInteger &
9128   // Co. usage condition.
9129   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9130     QualType TrueTy, FalseTy;
9131     StringRef TrueName, FalseName;
9132 
9133     std::tie(TrueTy, TrueName) =
9134       shouldNotPrintDirectly(Context,
9135                              CO->getTrueExpr()->getType(),
9136                              CO->getTrueExpr());
9137     std::tie(FalseTy, FalseName) =
9138       shouldNotPrintDirectly(Context,
9139                              CO->getFalseExpr()->getType(),
9140                              CO->getFalseExpr());
9141 
9142     if (TrueTy == FalseTy)
9143       return std::make_pair(TrueTy, TrueName);
9144     else if (TrueTy.isNull())
9145       return std::make_pair(FalseTy, FalseName);
9146     else if (FalseTy.isNull())
9147       return std::make_pair(TrueTy, TrueName);
9148   }
9149 
9150   return std::make_pair(QualType(), StringRef());
9151 }
9152 
9153 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9154 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9155 /// type do not count.
9156 static bool
9157 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9158   QualType From = ICE->getSubExpr()->getType();
9159   QualType To = ICE->getType();
9160   // It's an integer promotion if the destination type is the promoted
9161   // source type.
9162   if (ICE->getCastKind() == CK_IntegralCast &&
9163       From->isPromotableIntegerType() &&
9164       S.Context.getPromotedIntegerType(From) == To)
9165     return true;
9166   // Look through vector types, since we do default argument promotion for
9167   // those in OpenCL.
9168   if (const auto *VecTy = From->getAs<ExtVectorType>())
9169     From = VecTy->getElementType();
9170   if (const auto *VecTy = To->getAs<ExtVectorType>())
9171     To = VecTy->getElementType();
9172   // It's a floating promotion if the source type is a lower rank.
9173   return ICE->getCastKind() == CK_FloatingCast &&
9174          S.Context.getFloatingTypeOrder(From, To) < 0;
9175 }
9176 
9177 bool
9178 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9179                                     const char *StartSpecifier,
9180                                     unsigned SpecifierLen,
9181                                     const Expr *E) {
9182   using namespace analyze_format_string;
9183   using namespace analyze_printf;
9184 
9185   // Now type check the data expression that matches the
9186   // format specifier.
9187   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9188   if (!AT.isValid())
9189     return true;
9190 
9191   QualType ExprTy = E->getType();
9192   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9193     ExprTy = TET->getUnderlyingExpr()->getType();
9194   }
9195 
9196   // Diagnose attempts to print a boolean value as a character. Unlike other
9197   // -Wformat diagnostics, this is fine from a type perspective, but it still
9198   // doesn't make sense.
9199   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9200       E->isKnownToHaveBooleanValue()) {
9201     const CharSourceRange &CSR =
9202         getSpecifierRange(StartSpecifier, SpecifierLen);
9203     SmallString<4> FSString;
9204     llvm::raw_svector_ostream os(FSString);
9205     FS.toString(os);
9206     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9207                              << FSString,
9208                          E->getExprLoc(), false, CSR);
9209     return true;
9210   }
9211 
9212   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9213   if (Match == analyze_printf::ArgType::Match)
9214     return true;
9215 
9216   // Look through argument promotions for our error message's reported type.
9217   // This includes the integral and floating promotions, but excludes array
9218   // and function pointer decay (seeing that an argument intended to be a
9219   // string has type 'char [6]' is probably more confusing than 'char *') and
9220   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9221   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9222     if (isArithmeticArgumentPromotion(S, ICE)) {
9223       E = ICE->getSubExpr();
9224       ExprTy = E->getType();
9225 
9226       // Check if we didn't match because of an implicit cast from a 'char'
9227       // or 'short' to an 'int'.  This is done because printf is a varargs
9228       // function.
9229       if (ICE->getType() == S.Context.IntTy ||
9230           ICE->getType() == S.Context.UnsignedIntTy) {
9231         // All further checking is done on the subexpression
9232         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9233             AT.matchesType(S.Context, ExprTy);
9234         if (ImplicitMatch == analyze_printf::ArgType::Match)
9235           return true;
9236         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9237             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9238           Match = ImplicitMatch;
9239       }
9240     }
9241   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9242     // Special case for 'a', which has type 'int' in C.
9243     // Note, however, that we do /not/ want to treat multibyte constants like
9244     // 'MooV' as characters! This form is deprecated but still exists. In
9245     // addition, don't treat expressions as of type 'char' if one byte length
9246     // modifier is provided.
9247     if (ExprTy == S.Context.IntTy &&
9248         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9249       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9250         ExprTy = S.Context.CharTy;
9251   }
9252 
9253   // Look through enums to their underlying type.
9254   bool IsEnum = false;
9255   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9256     ExprTy = EnumTy->getDecl()->getIntegerType();
9257     IsEnum = true;
9258   }
9259 
9260   // %C in an Objective-C context prints a unichar, not a wchar_t.
9261   // If the argument is an integer of some kind, believe the %C and suggest
9262   // a cast instead of changing the conversion specifier.
9263   QualType IntendedTy = ExprTy;
9264   if (isObjCContext() &&
9265       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9266     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9267         !ExprTy->isCharType()) {
9268       // 'unichar' is defined as a typedef of unsigned short, but we should
9269       // prefer using the typedef if it is visible.
9270       IntendedTy = S.Context.UnsignedShortTy;
9271 
9272       // While we are here, check if the value is an IntegerLiteral that happens
9273       // to be within the valid range.
9274       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9275         const llvm::APInt &V = IL->getValue();
9276         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9277           return true;
9278       }
9279 
9280       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9281                           Sema::LookupOrdinaryName);
9282       if (S.LookupName(Result, S.getCurScope())) {
9283         NamedDecl *ND = Result.getFoundDecl();
9284         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9285           if (TD->getUnderlyingType() == IntendedTy)
9286             IntendedTy = S.Context.getTypedefType(TD);
9287       }
9288     }
9289   }
9290 
9291   // Special-case some of Darwin's platform-independence types by suggesting
9292   // casts to primitive types that are known to be large enough.
9293   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9294   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9295     QualType CastTy;
9296     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9297     if (!CastTy.isNull()) {
9298       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9299       // (long in ASTContext). Only complain to pedants.
9300       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9301           (AT.isSizeT() || AT.isPtrdiffT()) &&
9302           AT.matchesType(S.Context, CastTy))
9303         Match = ArgType::NoMatchPedantic;
9304       IntendedTy = CastTy;
9305       ShouldNotPrintDirectly = true;
9306     }
9307   }
9308 
9309   // We may be able to offer a FixItHint if it is a supported type.
9310   PrintfSpecifier fixedFS = FS;
9311   bool Success =
9312       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9313 
9314   if (Success) {
9315     // Get the fix string from the fixed format specifier
9316     SmallString<16> buf;
9317     llvm::raw_svector_ostream os(buf);
9318     fixedFS.toString(os);
9319 
9320     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9321 
9322     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9323       unsigned Diag;
9324       switch (Match) {
9325       case ArgType::Match: llvm_unreachable("expected non-matching");
9326       case ArgType::NoMatchPedantic:
9327         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9328         break;
9329       case ArgType::NoMatchTypeConfusion:
9330         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9331         break;
9332       case ArgType::NoMatch:
9333         Diag = diag::warn_format_conversion_argument_type_mismatch;
9334         break;
9335       }
9336 
9337       // In this case, the specifier is wrong and should be changed to match
9338       // the argument.
9339       EmitFormatDiagnostic(S.PDiag(Diag)
9340                                << AT.getRepresentativeTypeName(S.Context)
9341                                << IntendedTy << IsEnum << E->getSourceRange(),
9342                            E->getBeginLoc(),
9343                            /*IsStringLocation*/ false, SpecRange,
9344                            FixItHint::CreateReplacement(SpecRange, os.str()));
9345     } else {
9346       // The canonical type for formatting this value is different from the
9347       // actual type of the expression. (This occurs, for example, with Darwin's
9348       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9349       // should be printed as 'long' for 64-bit compatibility.)
9350       // Rather than emitting a normal format/argument mismatch, we want to
9351       // add a cast to the recommended type (and correct the format string
9352       // if necessary).
9353       SmallString<16> CastBuf;
9354       llvm::raw_svector_ostream CastFix(CastBuf);
9355       CastFix << "(";
9356       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9357       CastFix << ")";
9358 
9359       SmallVector<FixItHint,4> Hints;
9360       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9361         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9362 
9363       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9364         // If there's already a cast present, just replace it.
9365         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9366         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9367 
9368       } else if (!requiresParensToAddCast(E)) {
9369         // If the expression has high enough precedence,
9370         // just write the C-style cast.
9371         Hints.push_back(
9372             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9373       } else {
9374         // Otherwise, add parens around the expression as well as the cast.
9375         CastFix << "(";
9376         Hints.push_back(
9377             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9378 
9379         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9380         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9381       }
9382 
9383       if (ShouldNotPrintDirectly) {
9384         // The expression has a type that should not be printed directly.
9385         // We extract the name from the typedef because we don't want to show
9386         // the underlying type in the diagnostic.
9387         StringRef Name;
9388         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9389           Name = TypedefTy->getDecl()->getName();
9390         else
9391           Name = CastTyName;
9392         unsigned Diag = Match == ArgType::NoMatchPedantic
9393                             ? diag::warn_format_argument_needs_cast_pedantic
9394                             : diag::warn_format_argument_needs_cast;
9395         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9396                                            << E->getSourceRange(),
9397                              E->getBeginLoc(), /*IsStringLocation=*/false,
9398                              SpecRange, Hints);
9399       } else {
9400         // In this case, the expression could be printed using a different
9401         // specifier, but we've decided that the specifier is probably correct
9402         // and we should cast instead. Just use the normal warning message.
9403         EmitFormatDiagnostic(
9404             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9405                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9406                 << E->getSourceRange(),
9407             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9408       }
9409     }
9410   } else {
9411     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9412                                                    SpecifierLen);
9413     // Since the warning for passing non-POD types to variadic functions
9414     // was deferred until now, we emit a warning for non-POD
9415     // arguments here.
9416     switch (S.isValidVarArgType(ExprTy)) {
9417     case Sema::VAK_Valid:
9418     case Sema::VAK_ValidInCXX11: {
9419       unsigned Diag;
9420       switch (Match) {
9421       case ArgType::Match: llvm_unreachable("expected non-matching");
9422       case ArgType::NoMatchPedantic:
9423         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9424         break;
9425       case ArgType::NoMatchTypeConfusion:
9426         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9427         break;
9428       case ArgType::NoMatch:
9429         Diag = diag::warn_format_conversion_argument_type_mismatch;
9430         break;
9431       }
9432 
9433       EmitFormatDiagnostic(
9434           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9435                         << IsEnum << CSR << E->getSourceRange(),
9436           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9437       break;
9438     }
9439     case Sema::VAK_Undefined:
9440     case Sema::VAK_MSVCUndefined:
9441       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9442                                << S.getLangOpts().CPlusPlus11 << ExprTy
9443                                << CallType
9444                                << AT.getRepresentativeTypeName(S.Context) << CSR
9445                                << E->getSourceRange(),
9446                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9447       checkForCStrMembers(AT, E);
9448       break;
9449 
9450     case Sema::VAK_Invalid:
9451       if (ExprTy->isObjCObjectType())
9452         EmitFormatDiagnostic(
9453             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9454                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9455                 << AT.getRepresentativeTypeName(S.Context) << CSR
9456                 << E->getSourceRange(),
9457             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9458       else
9459         // FIXME: If this is an initializer list, suggest removing the braces
9460         // or inserting a cast to the target type.
9461         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9462             << isa<InitListExpr>(E) << ExprTy << CallType
9463             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9464       break;
9465     }
9466 
9467     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9468            "format string specifier index out of range");
9469     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9470   }
9471 
9472   return true;
9473 }
9474 
9475 //===--- CHECK: Scanf format string checking ------------------------------===//
9476 
9477 namespace {
9478 
9479 class CheckScanfHandler : public CheckFormatHandler {
9480 public:
9481   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9482                     const Expr *origFormatExpr, Sema::FormatStringType type,
9483                     unsigned firstDataArg, unsigned numDataArgs,
9484                     const char *beg, bool hasVAListArg,
9485                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9486                     bool inFunctionCall, Sema::VariadicCallType CallType,
9487                     llvm::SmallBitVector &CheckedVarArgs,
9488                     UncoveredArgHandler &UncoveredArg)
9489       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9490                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9491                            inFunctionCall, CallType, CheckedVarArgs,
9492                            UncoveredArg) {}
9493 
9494   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9495                             const char *startSpecifier,
9496                             unsigned specifierLen) override;
9497 
9498   bool HandleInvalidScanfConversionSpecifier(
9499           const analyze_scanf::ScanfSpecifier &FS,
9500           const char *startSpecifier,
9501           unsigned specifierLen) override;
9502 
9503   void HandleIncompleteScanList(const char *start, const char *end) override;
9504 };
9505 
9506 } // namespace
9507 
9508 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9509                                                  const char *end) {
9510   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9511                        getLocationOfByte(end), /*IsStringLocation*/true,
9512                        getSpecifierRange(start, end - start));
9513 }
9514 
9515 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9516                                         const analyze_scanf::ScanfSpecifier &FS,
9517                                         const char *startSpecifier,
9518                                         unsigned specifierLen) {
9519   const analyze_scanf::ScanfConversionSpecifier &CS =
9520     FS.getConversionSpecifier();
9521 
9522   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9523                                           getLocationOfByte(CS.getStart()),
9524                                           startSpecifier, specifierLen,
9525                                           CS.getStart(), CS.getLength());
9526 }
9527 
9528 bool CheckScanfHandler::HandleScanfSpecifier(
9529                                        const analyze_scanf::ScanfSpecifier &FS,
9530                                        const char *startSpecifier,
9531                                        unsigned specifierLen) {
9532   using namespace analyze_scanf;
9533   using namespace analyze_format_string;
9534 
9535   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9536 
9537   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9538   // be used to decide if we are using positional arguments consistently.
9539   if (FS.consumesDataArgument()) {
9540     if (atFirstArg) {
9541       atFirstArg = false;
9542       usesPositionalArgs = FS.usesPositionalArg();
9543     }
9544     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9545       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9546                                         startSpecifier, specifierLen);
9547       return false;
9548     }
9549   }
9550 
9551   // Check if the field with is non-zero.
9552   const OptionalAmount &Amt = FS.getFieldWidth();
9553   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9554     if (Amt.getConstantAmount() == 0) {
9555       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9556                                                    Amt.getConstantLength());
9557       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9558                            getLocationOfByte(Amt.getStart()),
9559                            /*IsStringLocation*/true, R,
9560                            FixItHint::CreateRemoval(R));
9561     }
9562   }
9563 
9564   if (!FS.consumesDataArgument()) {
9565     // FIXME: Technically specifying a precision or field width here
9566     // makes no sense.  Worth issuing a warning at some point.
9567     return true;
9568   }
9569 
9570   // Consume the argument.
9571   unsigned argIndex = FS.getArgIndex();
9572   if (argIndex < NumDataArgs) {
9573       // The check to see if the argIndex is valid will come later.
9574       // We set the bit here because we may exit early from this
9575       // function if we encounter some other error.
9576     CoveredArgs.set(argIndex);
9577   }
9578 
9579   // Check the length modifier is valid with the given conversion specifier.
9580   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9581                                  S.getLangOpts()))
9582     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9583                                 diag::warn_format_nonsensical_length);
9584   else if (!FS.hasStandardLengthModifier())
9585     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9586   else if (!FS.hasStandardLengthConversionCombination())
9587     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9588                                 diag::warn_format_non_standard_conversion_spec);
9589 
9590   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9591     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9592 
9593   // The remaining checks depend on the data arguments.
9594   if (HasVAListArg)
9595     return true;
9596 
9597   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9598     return false;
9599 
9600   // Check that the argument type matches the format specifier.
9601   const Expr *Ex = getDataArg(argIndex);
9602   if (!Ex)
9603     return true;
9604 
9605   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9606 
9607   if (!AT.isValid()) {
9608     return true;
9609   }
9610 
9611   analyze_format_string::ArgType::MatchKind Match =
9612       AT.matchesType(S.Context, Ex->getType());
9613   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9614   if (Match == analyze_format_string::ArgType::Match)
9615     return true;
9616 
9617   ScanfSpecifier fixedFS = FS;
9618   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9619                                  S.getLangOpts(), S.Context);
9620 
9621   unsigned Diag =
9622       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9623                : diag::warn_format_conversion_argument_type_mismatch;
9624 
9625   if (Success) {
9626     // Get the fix string from the fixed format specifier.
9627     SmallString<128> buf;
9628     llvm::raw_svector_ostream os(buf);
9629     fixedFS.toString(os);
9630 
9631     EmitFormatDiagnostic(
9632         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9633                       << Ex->getType() << false << Ex->getSourceRange(),
9634         Ex->getBeginLoc(),
9635         /*IsStringLocation*/ false,
9636         getSpecifierRange(startSpecifier, specifierLen),
9637         FixItHint::CreateReplacement(
9638             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9639   } else {
9640     EmitFormatDiagnostic(S.PDiag(Diag)
9641                              << AT.getRepresentativeTypeName(S.Context)
9642                              << Ex->getType() << false << Ex->getSourceRange(),
9643                          Ex->getBeginLoc(),
9644                          /*IsStringLocation*/ false,
9645                          getSpecifierRange(startSpecifier, specifierLen));
9646   }
9647 
9648   return true;
9649 }
9650 
9651 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9652                               const Expr *OrigFormatExpr,
9653                               ArrayRef<const Expr *> Args,
9654                               bool HasVAListArg, unsigned format_idx,
9655                               unsigned firstDataArg,
9656                               Sema::FormatStringType Type,
9657                               bool inFunctionCall,
9658                               Sema::VariadicCallType CallType,
9659                               llvm::SmallBitVector &CheckedVarArgs,
9660                               UncoveredArgHandler &UncoveredArg,
9661                               bool IgnoreStringsWithoutSpecifiers) {
9662   // CHECK: is the format string a wide literal?
9663   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9664     CheckFormatHandler::EmitFormatDiagnostic(
9665         S, inFunctionCall, Args[format_idx],
9666         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9667         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9668     return;
9669   }
9670 
9671   // Str - The format string.  NOTE: this is NOT null-terminated!
9672   StringRef StrRef = FExpr->getString();
9673   const char *Str = StrRef.data();
9674   // Account for cases where the string literal is truncated in a declaration.
9675   const ConstantArrayType *T =
9676     S.Context.getAsConstantArrayType(FExpr->getType());
9677   assert(T && "String literal not of constant array type!");
9678   size_t TypeSize = T->getSize().getZExtValue();
9679   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9680   const unsigned numDataArgs = Args.size() - firstDataArg;
9681 
9682   if (IgnoreStringsWithoutSpecifiers &&
9683       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9684           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9685     return;
9686 
9687   // Emit a warning if the string literal is truncated and does not contain an
9688   // embedded null character.
9689   if (TypeSize <= StrRef.size() &&
9690       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9691     CheckFormatHandler::EmitFormatDiagnostic(
9692         S, inFunctionCall, Args[format_idx],
9693         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9694         FExpr->getBeginLoc(),
9695         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9696     return;
9697   }
9698 
9699   // CHECK: empty format string?
9700   if (StrLen == 0 && numDataArgs > 0) {
9701     CheckFormatHandler::EmitFormatDiagnostic(
9702         S, inFunctionCall, Args[format_idx],
9703         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9704         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9705     return;
9706   }
9707 
9708   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9709       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9710       Type == Sema::FST_OSTrace) {
9711     CheckPrintfHandler H(
9712         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9713         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9714         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9715         CheckedVarArgs, UncoveredArg);
9716 
9717     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9718                                                   S.getLangOpts(),
9719                                                   S.Context.getTargetInfo(),
9720                                             Type == Sema::FST_FreeBSDKPrintf))
9721       H.DoneProcessing();
9722   } else if (Type == Sema::FST_Scanf) {
9723     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9724                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9725                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9726 
9727     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9728                                                  S.getLangOpts(),
9729                                                  S.Context.getTargetInfo()))
9730       H.DoneProcessing();
9731   } // TODO: handle other formats
9732 }
9733 
9734 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9735   // Str - The format string.  NOTE: this is NOT null-terminated!
9736   StringRef StrRef = FExpr->getString();
9737   const char *Str = StrRef.data();
9738   // Account for cases where the string literal is truncated in a declaration.
9739   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9740   assert(T && "String literal not of constant array type!");
9741   size_t TypeSize = T->getSize().getZExtValue();
9742   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9743   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9744                                                          getLangOpts(),
9745                                                          Context.getTargetInfo());
9746 }
9747 
9748 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9749 
9750 // Returns the related absolute value function that is larger, of 0 if one
9751 // does not exist.
9752 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9753   switch (AbsFunction) {
9754   default:
9755     return 0;
9756 
9757   case Builtin::BI__builtin_abs:
9758     return Builtin::BI__builtin_labs;
9759   case Builtin::BI__builtin_labs:
9760     return Builtin::BI__builtin_llabs;
9761   case Builtin::BI__builtin_llabs:
9762     return 0;
9763 
9764   case Builtin::BI__builtin_fabsf:
9765     return Builtin::BI__builtin_fabs;
9766   case Builtin::BI__builtin_fabs:
9767     return Builtin::BI__builtin_fabsl;
9768   case Builtin::BI__builtin_fabsl:
9769     return 0;
9770 
9771   case Builtin::BI__builtin_cabsf:
9772     return Builtin::BI__builtin_cabs;
9773   case Builtin::BI__builtin_cabs:
9774     return Builtin::BI__builtin_cabsl;
9775   case Builtin::BI__builtin_cabsl:
9776     return 0;
9777 
9778   case Builtin::BIabs:
9779     return Builtin::BIlabs;
9780   case Builtin::BIlabs:
9781     return Builtin::BIllabs;
9782   case Builtin::BIllabs:
9783     return 0;
9784 
9785   case Builtin::BIfabsf:
9786     return Builtin::BIfabs;
9787   case Builtin::BIfabs:
9788     return Builtin::BIfabsl;
9789   case Builtin::BIfabsl:
9790     return 0;
9791 
9792   case Builtin::BIcabsf:
9793    return Builtin::BIcabs;
9794   case Builtin::BIcabs:
9795     return Builtin::BIcabsl;
9796   case Builtin::BIcabsl:
9797     return 0;
9798   }
9799 }
9800 
9801 // Returns the argument type of the absolute value function.
9802 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9803                                              unsigned AbsType) {
9804   if (AbsType == 0)
9805     return QualType();
9806 
9807   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9808   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9809   if (Error != ASTContext::GE_None)
9810     return QualType();
9811 
9812   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9813   if (!FT)
9814     return QualType();
9815 
9816   if (FT->getNumParams() != 1)
9817     return QualType();
9818 
9819   return FT->getParamType(0);
9820 }
9821 
9822 // Returns the best absolute value function, or zero, based on type and
9823 // current absolute value function.
9824 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9825                                    unsigned AbsFunctionKind) {
9826   unsigned BestKind = 0;
9827   uint64_t ArgSize = Context.getTypeSize(ArgType);
9828   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9829        Kind = getLargerAbsoluteValueFunction(Kind)) {
9830     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9831     if (Context.getTypeSize(ParamType) >= ArgSize) {
9832       if (BestKind == 0)
9833         BestKind = Kind;
9834       else if (Context.hasSameType(ParamType, ArgType)) {
9835         BestKind = Kind;
9836         break;
9837       }
9838     }
9839   }
9840   return BestKind;
9841 }
9842 
9843 enum AbsoluteValueKind {
9844   AVK_Integer,
9845   AVK_Floating,
9846   AVK_Complex
9847 };
9848 
9849 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9850   if (T->isIntegralOrEnumerationType())
9851     return AVK_Integer;
9852   if (T->isRealFloatingType())
9853     return AVK_Floating;
9854   if (T->isAnyComplexType())
9855     return AVK_Complex;
9856 
9857   llvm_unreachable("Type not integer, floating, or complex");
9858 }
9859 
9860 // Changes the absolute value function to a different type.  Preserves whether
9861 // the function is a builtin.
9862 static unsigned changeAbsFunction(unsigned AbsKind,
9863                                   AbsoluteValueKind ValueKind) {
9864   switch (ValueKind) {
9865   case AVK_Integer:
9866     switch (AbsKind) {
9867     default:
9868       return 0;
9869     case Builtin::BI__builtin_fabsf:
9870     case Builtin::BI__builtin_fabs:
9871     case Builtin::BI__builtin_fabsl:
9872     case Builtin::BI__builtin_cabsf:
9873     case Builtin::BI__builtin_cabs:
9874     case Builtin::BI__builtin_cabsl:
9875       return Builtin::BI__builtin_abs;
9876     case Builtin::BIfabsf:
9877     case Builtin::BIfabs:
9878     case Builtin::BIfabsl:
9879     case Builtin::BIcabsf:
9880     case Builtin::BIcabs:
9881     case Builtin::BIcabsl:
9882       return Builtin::BIabs;
9883     }
9884   case AVK_Floating:
9885     switch (AbsKind) {
9886     default:
9887       return 0;
9888     case Builtin::BI__builtin_abs:
9889     case Builtin::BI__builtin_labs:
9890     case Builtin::BI__builtin_llabs:
9891     case Builtin::BI__builtin_cabsf:
9892     case Builtin::BI__builtin_cabs:
9893     case Builtin::BI__builtin_cabsl:
9894       return Builtin::BI__builtin_fabsf;
9895     case Builtin::BIabs:
9896     case Builtin::BIlabs:
9897     case Builtin::BIllabs:
9898     case Builtin::BIcabsf:
9899     case Builtin::BIcabs:
9900     case Builtin::BIcabsl:
9901       return Builtin::BIfabsf;
9902     }
9903   case AVK_Complex:
9904     switch (AbsKind) {
9905     default:
9906       return 0;
9907     case Builtin::BI__builtin_abs:
9908     case Builtin::BI__builtin_labs:
9909     case Builtin::BI__builtin_llabs:
9910     case Builtin::BI__builtin_fabsf:
9911     case Builtin::BI__builtin_fabs:
9912     case Builtin::BI__builtin_fabsl:
9913       return Builtin::BI__builtin_cabsf;
9914     case Builtin::BIabs:
9915     case Builtin::BIlabs:
9916     case Builtin::BIllabs:
9917     case Builtin::BIfabsf:
9918     case Builtin::BIfabs:
9919     case Builtin::BIfabsl:
9920       return Builtin::BIcabsf;
9921     }
9922   }
9923   llvm_unreachable("Unable to convert function");
9924 }
9925 
9926 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9927   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9928   if (!FnInfo)
9929     return 0;
9930 
9931   switch (FDecl->getBuiltinID()) {
9932   default:
9933     return 0;
9934   case Builtin::BI__builtin_abs:
9935   case Builtin::BI__builtin_fabs:
9936   case Builtin::BI__builtin_fabsf:
9937   case Builtin::BI__builtin_fabsl:
9938   case Builtin::BI__builtin_labs:
9939   case Builtin::BI__builtin_llabs:
9940   case Builtin::BI__builtin_cabs:
9941   case Builtin::BI__builtin_cabsf:
9942   case Builtin::BI__builtin_cabsl:
9943   case Builtin::BIabs:
9944   case Builtin::BIlabs:
9945   case Builtin::BIllabs:
9946   case Builtin::BIfabs:
9947   case Builtin::BIfabsf:
9948   case Builtin::BIfabsl:
9949   case Builtin::BIcabs:
9950   case Builtin::BIcabsf:
9951   case Builtin::BIcabsl:
9952     return FDecl->getBuiltinID();
9953   }
9954   llvm_unreachable("Unknown Builtin type");
9955 }
9956 
9957 // If the replacement is valid, emit a note with replacement function.
9958 // Additionally, suggest including the proper header if not already included.
9959 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9960                             unsigned AbsKind, QualType ArgType) {
9961   bool EmitHeaderHint = true;
9962   const char *HeaderName = nullptr;
9963   const char *FunctionName = nullptr;
9964   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9965     FunctionName = "std::abs";
9966     if (ArgType->isIntegralOrEnumerationType()) {
9967       HeaderName = "cstdlib";
9968     } else if (ArgType->isRealFloatingType()) {
9969       HeaderName = "cmath";
9970     } else {
9971       llvm_unreachable("Invalid Type");
9972     }
9973 
9974     // Lookup all std::abs
9975     if (NamespaceDecl *Std = S.getStdNamespace()) {
9976       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9977       R.suppressDiagnostics();
9978       S.LookupQualifiedName(R, Std);
9979 
9980       for (const auto *I : R) {
9981         const FunctionDecl *FDecl = nullptr;
9982         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9983           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9984         } else {
9985           FDecl = dyn_cast<FunctionDecl>(I);
9986         }
9987         if (!FDecl)
9988           continue;
9989 
9990         // Found std::abs(), check that they are the right ones.
9991         if (FDecl->getNumParams() != 1)
9992           continue;
9993 
9994         // Check that the parameter type can handle the argument.
9995         QualType ParamType = FDecl->getParamDecl(0)->getType();
9996         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9997             S.Context.getTypeSize(ArgType) <=
9998                 S.Context.getTypeSize(ParamType)) {
9999           // Found a function, don't need the header hint.
10000           EmitHeaderHint = false;
10001           break;
10002         }
10003       }
10004     }
10005   } else {
10006     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10007     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10008 
10009     if (HeaderName) {
10010       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10011       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10012       R.suppressDiagnostics();
10013       S.LookupName(R, S.getCurScope());
10014 
10015       if (R.isSingleResult()) {
10016         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10017         if (FD && FD->getBuiltinID() == AbsKind) {
10018           EmitHeaderHint = false;
10019         } else {
10020           return;
10021         }
10022       } else if (!R.empty()) {
10023         return;
10024       }
10025     }
10026   }
10027 
10028   S.Diag(Loc, diag::note_replace_abs_function)
10029       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10030 
10031   if (!HeaderName)
10032     return;
10033 
10034   if (!EmitHeaderHint)
10035     return;
10036 
10037   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10038                                                     << FunctionName;
10039 }
10040 
10041 template <std::size_t StrLen>
10042 static bool IsStdFunction(const FunctionDecl *FDecl,
10043                           const char (&Str)[StrLen]) {
10044   if (!FDecl)
10045     return false;
10046   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10047     return false;
10048   if (!FDecl->isInStdNamespace())
10049     return false;
10050 
10051   return true;
10052 }
10053 
10054 // Warn when using the wrong abs() function.
10055 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10056                                       const FunctionDecl *FDecl) {
10057   if (Call->getNumArgs() != 1)
10058     return;
10059 
10060   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10061   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10062   if (AbsKind == 0 && !IsStdAbs)
10063     return;
10064 
10065   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10066   QualType ParamType = Call->getArg(0)->getType();
10067 
10068   // Unsigned types cannot be negative.  Suggest removing the absolute value
10069   // function call.
10070   if (ArgType->isUnsignedIntegerType()) {
10071     const char *FunctionName =
10072         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10073     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10074     Diag(Call->getExprLoc(), diag::note_remove_abs)
10075         << FunctionName
10076         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10077     return;
10078   }
10079 
10080   // Taking the absolute value of a pointer is very suspicious, they probably
10081   // wanted to index into an array, dereference a pointer, call a function, etc.
10082   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10083     unsigned DiagType = 0;
10084     if (ArgType->isFunctionType())
10085       DiagType = 1;
10086     else if (ArgType->isArrayType())
10087       DiagType = 2;
10088 
10089     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10090     return;
10091   }
10092 
10093   // std::abs has overloads which prevent most of the absolute value problems
10094   // from occurring.
10095   if (IsStdAbs)
10096     return;
10097 
10098   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10099   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10100 
10101   // The argument and parameter are the same kind.  Check if they are the right
10102   // size.
10103   if (ArgValueKind == ParamValueKind) {
10104     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10105       return;
10106 
10107     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10108     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10109         << FDecl << ArgType << ParamType;
10110 
10111     if (NewAbsKind == 0)
10112       return;
10113 
10114     emitReplacement(*this, Call->getExprLoc(),
10115                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10116     return;
10117   }
10118 
10119   // ArgValueKind != ParamValueKind
10120   // The wrong type of absolute value function was used.  Attempt to find the
10121   // proper one.
10122   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10123   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10124   if (NewAbsKind == 0)
10125     return;
10126 
10127   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10128       << FDecl << ParamValueKind << ArgValueKind;
10129 
10130   emitReplacement(*this, Call->getExprLoc(),
10131                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10132 }
10133 
10134 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10135 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10136                                 const FunctionDecl *FDecl) {
10137   if (!Call || !FDecl) return;
10138 
10139   // Ignore template specializations and macros.
10140   if (inTemplateInstantiation()) return;
10141   if (Call->getExprLoc().isMacroID()) return;
10142 
10143   // Only care about the one template argument, two function parameter std::max
10144   if (Call->getNumArgs() != 2) return;
10145   if (!IsStdFunction(FDecl, "max")) return;
10146   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10147   if (!ArgList) return;
10148   if (ArgList->size() != 1) return;
10149 
10150   // Check that template type argument is unsigned integer.
10151   const auto& TA = ArgList->get(0);
10152   if (TA.getKind() != TemplateArgument::Type) return;
10153   QualType ArgType = TA.getAsType();
10154   if (!ArgType->isUnsignedIntegerType()) return;
10155 
10156   // See if either argument is a literal zero.
10157   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10158     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10159     if (!MTE) return false;
10160     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10161     if (!Num) return false;
10162     if (Num->getValue() != 0) return false;
10163     return true;
10164   };
10165 
10166   const Expr *FirstArg = Call->getArg(0);
10167   const Expr *SecondArg = Call->getArg(1);
10168   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10169   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10170 
10171   // Only warn when exactly one argument is zero.
10172   if (IsFirstArgZero == IsSecondArgZero) return;
10173 
10174   SourceRange FirstRange = FirstArg->getSourceRange();
10175   SourceRange SecondRange = SecondArg->getSourceRange();
10176 
10177   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10178 
10179   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10180       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10181 
10182   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10183   SourceRange RemovalRange;
10184   if (IsFirstArgZero) {
10185     RemovalRange = SourceRange(FirstRange.getBegin(),
10186                                SecondRange.getBegin().getLocWithOffset(-1));
10187   } else {
10188     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10189                                SecondRange.getEnd());
10190   }
10191 
10192   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10193         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10194         << FixItHint::CreateRemoval(RemovalRange);
10195 }
10196 
10197 //===--- CHECK: Standard memory functions ---------------------------------===//
10198 
10199 /// Takes the expression passed to the size_t parameter of functions
10200 /// such as memcmp, strncat, etc and warns if it's a comparison.
10201 ///
10202 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10203 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10204                                            IdentifierInfo *FnName,
10205                                            SourceLocation FnLoc,
10206                                            SourceLocation RParenLoc) {
10207   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10208   if (!Size)
10209     return false;
10210 
10211   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10212   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10213     return false;
10214 
10215   SourceRange SizeRange = Size->getSourceRange();
10216   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10217       << SizeRange << FnName;
10218   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10219       << FnName
10220       << FixItHint::CreateInsertion(
10221              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10222       << FixItHint::CreateRemoval(RParenLoc);
10223   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10224       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10225       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10226                                     ")");
10227 
10228   return true;
10229 }
10230 
10231 /// Determine whether the given type is or contains a dynamic class type
10232 /// (e.g., whether it has a vtable).
10233 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10234                                                      bool &IsContained) {
10235   // Look through array types while ignoring qualifiers.
10236   const Type *Ty = T->getBaseElementTypeUnsafe();
10237   IsContained = false;
10238 
10239   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10240   RD = RD ? RD->getDefinition() : nullptr;
10241   if (!RD || RD->isInvalidDecl())
10242     return nullptr;
10243 
10244   if (RD->isDynamicClass())
10245     return RD;
10246 
10247   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10248   // It's impossible for a class to transitively contain itself by value, so
10249   // infinite recursion is impossible.
10250   for (auto *FD : RD->fields()) {
10251     bool SubContained;
10252     if (const CXXRecordDecl *ContainedRD =
10253             getContainedDynamicClass(FD->getType(), SubContained)) {
10254       IsContained = true;
10255       return ContainedRD;
10256     }
10257   }
10258 
10259   return nullptr;
10260 }
10261 
10262 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10263   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10264     if (Unary->getKind() == UETT_SizeOf)
10265       return Unary;
10266   return nullptr;
10267 }
10268 
10269 /// If E is a sizeof expression, returns its argument expression,
10270 /// otherwise returns NULL.
10271 static const Expr *getSizeOfExprArg(const Expr *E) {
10272   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10273     if (!SizeOf->isArgumentType())
10274       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10275   return nullptr;
10276 }
10277 
10278 /// If E is a sizeof expression, returns its argument type.
10279 static QualType getSizeOfArgType(const Expr *E) {
10280   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10281     return SizeOf->getTypeOfArgument();
10282   return QualType();
10283 }
10284 
10285 namespace {
10286 
10287 struct SearchNonTrivialToInitializeField
10288     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10289   using Super =
10290       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10291 
10292   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10293 
10294   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10295                      SourceLocation SL) {
10296     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10297       asDerived().visitArray(PDIK, AT, SL);
10298       return;
10299     }
10300 
10301     Super::visitWithKind(PDIK, FT, SL);
10302   }
10303 
10304   void visitARCStrong(QualType FT, SourceLocation SL) {
10305     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10306   }
10307   void visitARCWeak(QualType FT, SourceLocation SL) {
10308     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10309   }
10310   void visitStruct(QualType FT, SourceLocation SL) {
10311     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10312       visit(FD->getType(), FD->getLocation());
10313   }
10314   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10315                   const ArrayType *AT, SourceLocation SL) {
10316     visit(getContext().getBaseElementType(AT), SL);
10317   }
10318   void visitTrivial(QualType FT, SourceLocation SL) {}
10319 
10320   static void diag(QualType RT, const Expr *E, Sema &S) {
10321     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10322   }
10323 
10324   ASTContext &getContext() { return S.getASTContext(); }
10325 
10326   const Expr *E;
10327   Sema &S;
10328 };
10329 
10330 struct SearchNonTrivialToCopyField
10331     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10332   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10333 
10334   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10335 
10336   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10337                      SourceLocation SL) {
10338     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10339       asDerived().visitArray(PCK, AT, SL);
10340       return;
10341     }
10342 
10343     Super::visitWithKind(PCK, FT, SL);
10344   }
10345 
10346   void visitARCStrong(QualType FT, SourceLocation SL) {
10347     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10348   }
10349   void visitARCWeak(QualType FT, SourceLocation SL) {
10350     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10351   }
10352   void visitStruct(QualType FT, SourceLocation SL) {
10353     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10354       visit(FD->getType(), FD->getLocation());
10355   }
10356   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10357                   SourceLocation SL) {
10358     visit(getContext().getBaseElementType(AT), SL);
10359   }
10360   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10361                 SourceLocation SL) {}
10362   void visitTrivial(QualType FT, SourceLocation SL) {}
10363   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10364 
10365   static void diag(QualType RT, const Expr *E, Sema &S) {
10366     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10367   }
10368 
10369   ASTContext &getContext() { return S.getASTContext(); }
10370 
10371   const Expr *E;
10372   Sema &S;
10373 };
10374 
10375 }
10376 
10377 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10378 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10379   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10380 
10381   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10382     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10383       return false;
10384 
10385     return doesExprLikelyComputeSize(BO->getLHS()) ||
10386            doesExprLikelyComputeSize(BO->getRHS());
10387   }
10388 
10389   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10390 }
10391 
10392 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10393 ///
10394 /// \code
10395 ///   #define MACRO 0
10396 ///   foo(MACRO);
10397 ///   foo(0);
10398 /// \endcode
10399 ///
10400 /// This should return true for the first call to foo, but not for the second
10401 /// (regardless of whether foo is a macro or function).
10402 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10403                                         SourceLocation CallLoc,
10404                                         SourceLocation ArgLoc) {
10405   if (!CallLoc.isMacroID())
10406     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10407 
10408   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10409          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10410 }
10411 
10412 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10413 /// last two arguments transposed.
10414 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10415   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10416     return;
10417 
10418   const Expr *SizeArg =
10419     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10420 
10421   auto isLiteralZero = [](const Expr *E) {
10422     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10423   };
10424 
10425   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10426   SourceLocation CallLoc = Call->getRParenLoc();
10427   SourceManager &SM = S.getSourceManager();
10428   if (isLiteralZero(SizeArg) &&
10429       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10430 
10431     SourceLocation DiagLoc = SizeArg->getExprLoc();
10432 
10433     // Some platforms #define bzero to __builtin_memset. See if this is the
10434     // case, and if so, emit a better diagnostic.
10435     if (BId == Builtin::BIbzero ||
10436         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10437                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10438       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10439       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10440     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10441       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10442       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10443     }
10444     return;
10445   }
10446 
10447   // If the second argument to a memset is a sizeof expression and the third
10448   // isn't, this is also likely an error. This should catch
10449   // 'memset(buf, sizeof(buf), 0xff)'.
10450   if (BId == Builtin::BImemset &&
10451       doesExprLikelyComputeSize(Call->getArg(1)) &&
10452       !doesExprLikelyComputeSize(Call->getArg(2))) {
10453     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10454     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10455     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10456     return;
10457   }
10458 }
10459 
10460 /// Check for dangerous or invalid arguments to memset().
10461 ///
10462 /// This issues warnings on known problematic, dangerous or unspecified
10463 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10464 /// function calls.
10465 ///
10466 /// \param Call The call expression to diagnose.
10467 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10468                                    unsigned BId,
10469                                    IdentifierInfo *FnName) {
10470   assert(BId != 0);
10471 
10472   // It is possible to have a non-standard definition of memset.  Validate
10473   // we have enough arguments, and if not, abort further checking.
10474   unsigned ExpectedNumArgs =
10475       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10476   if (Call->getNumArgs() < ExpectedNumArgs)
10477     return;
10478 
10479   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10480                       BId == Builtin::BIstrndup ? 1 : 2);
10481   unsigned LenArg =
10482       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10483   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10484 
10485   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10486                                      Call->getBeginLoc(), Call->getRParenLoc()))
10487     return;
10488 
10489   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10490   CheckMemaccessSize(*this, BId, Call);
10491 
10492   // We have special checking when the length is a sizeof expression.
10493   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10494   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10495   llvm::FoldingSetNodeID SizeOfArgID;
10496 
10497   // Although widely used, 'bzero' is not a standard function. Be more strict
10498   // with the argument types before allowing diagnostics and only allow the
10499   // form bzero(ptr, sizeof(...)).
10500   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10501   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10502     return;
10503 
10504   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10505     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10506     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10507 
10508     QualType DestTy = Dest->getType();
10509     QualType PointeeTy;
10510     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10511       PointeeTy = DestPtrTy->getPointeeType();
10512 
10513       // Never warn about void type pointers. This can be used to suppress
10514       // false positives.
10515       if (PointeeTy->isVoidType())
10516         continue;
10517 
10518       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10519       // actually comparing the expressions for equality. Because computing the
10520       // expression IDs can be expensive, we only do this if the diagnostic is
10521       // enabled.
10522       if (SizeOfArg &&
10523           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10524                            SizeOfArg->getExprLoc())) {
10525         // We only compute IDs for expressions if the warning is enabled, and
10526         // cache the sizeof arg's ID.
10527         if (SizeOfArgID == llvm::FoldingSetNodeID())
10528           SizeOfArg->Profile(SizeOfArgID, Context, true);
10529         llvm::FoldingSetNodeID DestID;
10530         Dest->Profile(DestID, Context, true);
10531         if (DestID == SizeOfArgID) {
10532           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10533           //       over sizeof(src) as well.
10534           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10535           StringRef ReadableName = FnName->getName();
10536 
10537           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10538             if (UnaryOp->getOpcode() == UO_AddrOf)
10539               ActionIdx = 1; // If its an address-of operator, just remove it.
10540           if (!PointeeTy->isIncompleteType() &&
10541               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10542             ActionIdx = 2; // If the pointee's size is sizeof(char),
10543                            // suggest an explicit length.
10544 
10545           // If the function is defined as a builtin macro, do not show macro
10546           // expansion.
10547           SourceLocation SL = SizeOfArg->getExprLoc();
10548           SourceRange DSR = Dest->getSourceRange();
10549           SourceRange SSR = SizeOfArg->getSourceRange();
10550           SourceManager &SM = getSourceManager();
10551 
10552           if (SM.isMacroArgExpansion(SL)) {
10553             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10554             SL = SM.getSpellingLoc(SL);
10555             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10556                              SM.getSpellingLoc(DSR.getEnd()));
10557             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10558                              SM.getSpellingLoc(SSR.getEnd()));
10559           }
10560 
10561           DiagRuntimeBehavior(SL, SizeOfArg,
10562                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10563                                 << ReadableName
10564                                 << PointeeTy
10565                                 << DestTy
10566                                 << DSR
10567                                 << SSR);
10568           DiagRuntimeBehavior(SL, SizeOfArg,
10569                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10570                                 << ActionIdx
10571                                 << SSR);
10572 
10573           break;
10574         }
10575       }
10576 
10577       // Also check for cases where the sizeof argument is the exact same
10578       // type as the memory argument, and where it points to a user-defined
10579       // record type.
10580       if (SizeOfArgTy != QualType()) {
10581         if (PointeeTy->isRecordType() &&
10582             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10583           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10584                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10585                                 << FnName << SizeOfArgTy << ArgIdx
10586                                 << PointeeTy << Dest->getSourceRange()
10587                                 << LenExpr->getSourceRange());
10588           break;
10589         }
10590       }
10591     } else if (DestTy->isArrayType()) {
10592       PointeeTy = DestTy;
10593     }
10594 
10595     if (PointeeTy == QualType())
10596       continue;
10597 
10598     // Always complain about dynamic classes.
10599     bool IsContained;
10600     if (const CXXRecordDecl *ContainedRD =
10601             getContainedDynamicClass(PointeeTy, IsContained)) {
10602 
10603       unsigned OperationType = 0;
10604       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10605       // "overwritten" if we're warning about the destination for any call
10606       // but memcmp; otherwise a verb appropriate to the call.
10607       if (ArgIdx != 0 || IsCmp) {
10608         if (BId == Builtin::BImemcpy)
10609           OperationType = 1;
10610         else if(BId == Builtin::BImemmove)
10611           OperationType = 2;
10612         else if (IsCmp)
10613           OperationType = 3;
10614       }
10615 
10616       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10617                           PDiag(diag::warn_dyn_class_memaccess)
10618                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10619                               << IsContained << ContainedRD << OperationType
10620                               << Call->getCallee()->getSourceRange());
10621     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10622              BId != Builtin::BImemset)
10623       DiagRuntimeBehavior(
10624         Dest->getExprLoc(), Dest,
10625         PDiag(diag::warn_arc_object_memaccess)
10626           << ArgIdx << FnName << PointeeTy
10627           << Call->getCallee()->getSourceRange());
10628     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10629       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10630           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10631         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10632                             PDiag(diag::warn_cstruct_memaccess)
10633                                 << ArgIdx << FnName << PointeeTy << 0);
10634         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10635       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10636                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10637         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10638                             PDiag(diag::warn_cstruct_memaccess)
10639                                 << ArgIdx << FnName << PointeeTy << 1);
10640         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10641       } else {
10642         continue;
10643       }
10644     } else
10645       continue;
10646 
10647     DiagRuntimeBehavior(
10648       Dest->getExprLoc(), Dest,
10649       PDiag(diag::note_bad_memaccess_silence)
10650         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10651     break;
10652   }
10653 }
10654 
10655 // A little helper routine: ignore addition and subtraction of integer literals.
10656 // This intentionally does not ignore all integer constant expressions because
10657 // we don't want to remove sizeof().
10658 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10659   Ex = Ex->IgnoreParenCasts();
10660 
10661   while (true) {
10662     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10663     if (!BO || !BO->isAdditiveOp())
10664       break;
10665 
10666     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10667     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10668 
10669     if (isa<IntegerLiteral>(RHS))
10670       Ex = LHS;
10671     else if (isa<IntegerLiteral>(LHS))
10672       Ex = RHS;
10673     else
10674       break;
10675   }
10676 
10677   return Ex;
10678 }
10679 
10680 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10681                                                       ASTContext &Context) {
10682   // Only handle constant-sized or VLAs, but not flexible members.
10683   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10684     // Only issue the FIXIT for arrays of size > 1.
10685     if (CAT->getSize().getSExtValue() <= 1)
10686       return false;
10687   } else if (!Ty->isVariableArrayType()) {
10688     return false;
10689   }
10690   return true;
10691 }
10692 
10693 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10694 // be the size of the source, instead of the destination.
10695 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10696                                     IdentifierInfo *FnName) {
10697 
10698   // Don't crash if the user has the wrong number of arguments
10699   unsigned NumArgs = Call->getNumArgs();
10700   if ((NumArgs != 3) && (NumArgs != 4))
10701     return;
10702 
10703   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10704   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10705   const Expr *CompareWithSrc = nullptr;
10706 
10707   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10708                                      Call->getBeginLoc(), Call->getRParenLoc()))
10709     return;
10710 
10711   // Look for 'strlcpy(dst, x, sizeof(x))'
10712   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10713     CompareWithSrc = Ex;
10714   else {
10715     // Look for 'strlcpy(dst, x, strlen(x))'
10716     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10717       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10718           SizeCall->getNumArgs() == 1)
10719         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10720     }
10721   }
10722 
10723   if (!CompareWithSrc)
10724     return;
10725 
10726   // Determine if the argument to sizeof/strlen is equal to the source
10727   // argument.  In principle there's all kinds of things you could do
10728   // here, for instance creating an == expression and evaluating it with
10729   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10730   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10731   if (!SrcArgDRE)
10732     return;
10733 
10734   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10735   if (!CompareWithSrcDRE ||
10736       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10737     return;
10738 
10739   const Expr *OriginalSizeArg = Call->getArg(2);
10740   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10741       << OriginalSizeArg->getSourceRange() << FnName;
10742 
10743   // Output a FIXIT hint if the destination is an array (rather than a
10744   // pointer to an array).  This could be enhanced to handle some
10745   // pointers if we know the actual size, like if DstArg is 'array+2'
10746   // we could say 'sizeof(array)-2'.
10747   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10748   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10749     return;
10750 
10751   SmallString<128> sizeString;
10752   llvm::raw_svector_ostream OS(sizeString);
10753   OS << "sizeof(";
10754   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10755   OS << ")";
10756 
10757   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10758       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10759                                       OS.str());
10760 }
10761 
10762 /// Check if two expressions refer to the same declaration.
10763 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10764   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10765     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10766       return D1->getDecl() == D2->getDecl();
10767   return false;
10768 }
10769 
10770 static const Expr *getStrlenExprArg(const Expr *E) {
10771   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10772     const FunctionDecl *FD = CE->getDirectCallee();
10773     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10774       return nullptr;
10775     return CE->getArg(0)->IgnoreParenCasts();
10776   }
10777   return nullptr;
10778 }
10779 
10780 // Warn on anti-patterns as the 'size' argument to strncat.
10781 // The correct size argument should look like following:
10782 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10783 void Sema::CheckStrncatArguments(const CallExpr *CE,
10784                                  IdentifierInfo *FnName) {
10785   // Don't crash if the user has the wrong number of arguments.
10786   if (CE->getNumArgs() < 3)
10787     return;
10788   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10789   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10790   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10791 
10792   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10793                                      CE->getRParenLoc()))
10794     return;
10795 
10796   // Identify common expressions, which are wrongly used as the size argument
10797   // to strncat and may lead to buffer overflows.
10798   unsigned PatternType = 0;
10799   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10800     // - sizeof(dst)
10801     if (referToTheSameDecl(SizeOfArg, DstArg))
10802       PatternType = 1;
10803     // - sizeof(src)
10804     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10805       PatternType = 2;
10806   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10807     if (BE->getOpcode() == BO_Sub) {
10808       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10809       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10810       // - sizeof(dst) - strlen(dst)
10811       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10812           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10813         PatternType = 1;
10814       // - sizeof(src) - (anything)
10815       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10816         PatternType = 2;
10817     }
10818   }
10819 
10820   if (PatternType == 0)
10821     return;
10822 
10823   // Generate the diagnostic.
10824   SourceLocation SL = LenArg->getBeginLoc();
10825   SourceRange SR = LenArg->getSourceRange();
10826   SourceManager &SM = getSourceManager();
10827 
10828   // If the function is defined as a builtin macro, do not show macro expansion.
10829   if (SM.isMacroArgExpansion(SL)) {
10830     SL = SM.getSpellingLoc(SL);
10831     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10832                      SM.getSpellingLoc(SR.getEnd()));
10833   }
10834 
10835   // Check if the destination is an array (rather than a pointer to an array).
10836   QualType DstTy = DstArg->getType();
10837   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10838                                                                     Context);
10839   if (!isKnownSizeArray) {
10840     if (PatternType == 1)
10841       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10842     else
10843       Diag(SL, diag::warn_strncat_src_size) << SR;
10844     return;
10845   }
10846 
10847   if (PatternType == 1)
10848     Diag(SL, diag::warn_strncat_large_size) << SR;
10849   else
10850     Diag(SL, diag::warn_strncat_src_size) << SR;
10851 
10852   SmallString<128> sizeString;
10853   llvm::raw_svector_ostream OS(sizeString);
10854   OS << "sizeof(";
10855   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10856   OS << ") - ";
10857   OS << "strlen(";
10858   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10859   OS << ") - 1";
10860 
10861   Diag(SL, diag::note_strncat_wrong_size)
10862     << FixItHint::CreateReplacement(SR, OS.str());
10863 }
10864 
10865 namespace {
10866 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10867                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10868   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10869     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10870         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10871     return;
10872   }
10873 }
10874 
10875 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10876                                  const UnaryOperator *UnaryExpr) {
10877   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10878     const Decl *D = Lvalue->getDecl();
10879     if (isa<DeclaratorDecl>(D))
10880       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10881         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10882   }
10883 
10884   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10885     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10886                                       Lvalue->getMemberDecl());
10887 }
10888 
10889 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10890                             const UnaryOperator *UnaryExpr) {
10891   const auto *Lambda = dyn_cast<LambdaExpr>(
10892       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10893   if (!Lambda)
10894     return;
10895 
10896   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10897       << CalleeName << 2 /*object: lambda expression*/;
10898 }
10899 
10900 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10901                                   const DeclRefExpr *Lvalue) {
10902   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10903   if (Var == nullptr)
10904     return;
10905 
10906   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10907       << CalleeName << 0 /*object: */ << Var;
10908 }
10909 
10910 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10911                             const CastExpr *Cast) {
10912   SmallString<128> SizeString;
10913   llvm::raw_svector_ostream OS(SizeString);
10914 
10915   clang::CastKind Kind = Cast->getCastKind();
10916   if (Kind == clang::CK_BitCast &&
10917       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10918     return;
10919   if (Kind == clang::CK_IntegralToPointer &&
10920       !isa<IntegerLiteral>(
10921           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10922     return;
10923 
10924   switch (Cast->getCastKind()) {
10925   case clang::CK_BitCast:
10926   case clang::CK_IntegralToPointer:
10927   case clang::CK_FunctionToPointerDecay:
10928     OS << '\'';
10929     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10930     OS << '\'';
10931     break;
10932   default:
10933     return;
10934   }
10935 
10936   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10937       << CalleeName << 0 /*object: */ << OS.str();
10938 }
10939 } // namespace
10940 
10941 /// Alerts the user that they are attempting to free a non-malloc'd object.
10942 void Sema::CheckFreeArguments(const CallExpr *E) {
10943   const std::string CalleeName =
10944       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10945 
10946   { // Prefer something that doesn't involve a cast to make things simpler.
10947     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10948     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10949       switch (UnaryExpr->getOpcode()) {
10950       case UnaryOperator::Opcode::UO_AddrOf:
10951         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10952       case UnaryOperator::Opcode::UO_Plus:
10953         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10954       default:
10955         break;
10956       }
10957 
10958     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10959       if (Lvalue->getType()->isArrayType())
10960         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10961 
10962     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10963       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10964           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10965       return;
10966     }
10967 
10968     if (isa<BlockExpr>(Arg)) {
10969       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10970           << CalleeName << 1 /*object: block*/;
10971       return;
10972     }
10973   }
10974   // Maybe the cast was important, check after the other cases.
10975   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10976     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10977 }
10978 
10979 void
10980 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10981                          SourceLocation ReturnLoc,
10982                          bool isObjCMethod,
10983                          const AttrVec *Attrs,
10984                          const FunctionDecl *FD) {
10985   // Check if the return value is null but should not be.
10986   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10987        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10988       CheckNonNullExpr(*this, RetValExp))
10989     Diag(ReturnLoc, diag::warn_null_ret)
10990       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10991 
10992   // C++11 [basic.stc.dynamic.allocation]p4:
10993   //   If an allocation function declared with a non-throwing
10994   //   exception-specification fails to allocate storage, it shall return
10995   //   a null pointer. Any other allocation function that fails to allocate
10996   //   storage shall indicate failure only by throwing an exception [...]
10997   if (FD) {
10998     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10999     if (Op == OO_New || Op == OO_Array_New) {
11000       const FunctionProtoType *Proto
11001         = FD->getType()->castAs<FunctionProtoType>();
11002       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11003           CheckNonNullExpr(*this, RetValExp))
11004         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11005           << FD << getLangOpts().CPlusPlus11;
11006     }
11007   }
11008 
11009   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11010   // here prevent the user from using a PPC MMA type as trailing return type.
11011   if (Context.getTargetInfo().getTriple().isPPC64())
11012     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11013 }
11014 
11015 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11016 
11017 /// Check for comparisons of floating point operands using != and ==.
11018 /// Issue a warning if these are no self-comparisons, as they are not likely
11019 /// to do what the programmer intended.
11020 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11021   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11022   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11023 
11024   // Special case: check for x == x (which is OK).
11025   // Do not emit warnings for such cases.
11026   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11027     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11028       if (DRL->getDecl() == DRR->getDecl())
11029         return;
11030 
11031   // Special case: check for comparisons against literals that can be exactly
11032   //  represented by APFloat.  In such cases, do not emit a warning.  This
11033   //  is a heuristic: often comparison against such literals are used to
11034   //  detect if a value in a variable has not changed.  This clearly can
11035   //  lead to false negatives.
11036   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11037     if (FLL->isExact())
11038       return;
11039   } else
11040     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11041       if (FLR->isExact())
11042         return;
11043 
11044   // Check for comparisons with builtin types.
11045   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11046     if (CL->getBuiltinCallee())
11047       return;
11048 
11049   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11050     if (CR->getBuiltinCallee())
11051       return;
11052 
11053   // Emit the diagnostic.
11054   Diag(Loc, diag::warn_floatingpoint_eq)
11055     << LHS->getSourceRange() << RHS->getSourceRange();
11056 }
11057 
11058 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11059 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11060 
11061 namespace {
11062 
11063 /// Structure recording the 'active' range of an integer-valued
11064 /// expression.
11065 struct IntRange {
11066   /// The number of bits active in the int. Note that this includes exactly one
11067   /// sign bit if !NonNegative.
11068   unsigned Width;
11069 
11070   /// True if the int is known not to have negative values. If so, all leading
11071   /// bits before Width are known zero, otherwise they are known to be the
11072   /// same as the MSB within Width.
11073   bool NonNegative;
11074 
11075   IntRange(unsigned Width, bool NonNegative)
11076       : Width(Width), NonNegative(NonNegative) {}
11077 
11078   /// Number of bits excluding the sign bit.
11079   unsigned valueBits() const {
11080     return NonNegative ? Width : Width - 1;
11081   }
11082 
11083   /// Returns the range of the bool type.
11084   static IntRange forBoolType() {
11085     return IntRange(1, true);
11086   }
11087 
11088   /// Returns the range of an opaque value of the given integral type.
11089   static IntRange forValueOfType(ASTContext &C, QualType T) {
11090     return forValueOfCanonicalType(C,
11091                           T->getCanonicalTypeInternal().getTypePtr());
11092   }
11093 
11094   /// Returns the range of an opaque value of a canonical integral type.
11095   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11096     assert(T->isCanonicalUnqualified());
11097 
11098     if (const VectorType *VT = dyn_cast<VectorType>(T))
11099       T = VT->getElementType().getTypePtr();
11100     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11101       T = CT->getElementType().getTypePtr();
11102     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11103       T = AT->getValueType().getTypePtr();
11104 
11105     if (!C.getLangOpts().CPlusPlus) {
11106       // For enum types in C code, use the underlying datatype.
11107       if (const EnumType *ET = dyn_cast<EnumType>(T))
11108         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11109     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11110       // For enum types in C++, use the known bit width of the enumerators.
11111       EnumDecl *Enum = ET->getDecl();
11112       // In C++11, enums can have a fixed underlying type. Use this type to
11113       // compute the range.
11114       if (Enum->isFixed()) {
11115         return IntRange(C.getIntWidth(QualType(T, 0)),
11116                         !ET->isSignedIntegerOrEnumerationType());
11117       }
11118 
11119       unsigned NumPositive = Enum->getNumPositiveBits();
11120       unsigned NumNegative = Enum->getNumNegativeBits();
11121 
11122       if (NumNegative == 0)
11123         return IntRange(NumPositive, true/*NonNegative*/);
11124       else
11125         return IntRange(std::max(NumPositive + 1, NumNegative),
11126                         false/*NonNegative*/);
11127     }
11128 
11129     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11130       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11131 
11132     const BuiltinType *BT = cast<BuiltinType>(T);
11133     assert(BT->isInteger());
11134 
11135     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11136   }
11137 
11138   /// Returns the "target" range of a canonical integral type, i.e.
11139   /// the range of values expressible in the type.
11140   ///
11141   /// This matches forValueOfCanonicalType except that enums have the
11142   /// full range of their type, not the range of their enumerators.
11143   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11144     assert(T->isCanonicalUnqualified());
11145 
11146     if (const VectorType *VT = dyn_cast<VectorType>(T))
11147       T = VT->getElementType().getTypePtr();
11148     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11149       T = CT->getElementType().getTypePtr();
11150     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11151       T = AT->getValueType().getTypePtr();
11152     if (const EnumType *ET = dyn_cast<EnumType>(T))
11153       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11154 
11155     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11156       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11157 
11158     const BuiltinType *BT = cast<BuiltinType>(T);
11159     assert(BT->isInteger());
11160 
11161     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11162   }
11163 
11164   /// Returns the supremum of two ranges: i.e. their conservative merge.
11165   static IntRange join(IntRange L, IntRange R) {
11166     bool Unsigned = L.NonNegative && R.NonNegative;
11167     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11168                     L.NonNegative && R.NonNegative);
11169   }
11170 
11171   /// Return the range of a bitwise-AND of the two ranges.
11172   static IntRange bit_and(IntRange L, IntRange R) {
11173     unsigned Bits = std::max(L.Width, R.Width);
11174     bool NonNegative = false;
11175     if (L.NonNegative) {
11176       Bits = std::min(Bits, L.Width);
11177       NonNegative = true;
11178     }
11179     if (R.NonNegative) {
11180       Bits = std::min(Bits, R.Width);
11181       NonNegative = true;
11182     }
11183     return IntRange(Bits, NonNegative);
11184   }
11185 
11186   /// Return the range of a sum of the two ranges.
11187   static IntRange sum(IntRange L, IntRange R) {
11188     bool Unsigned = L.NonNegative && R.NonNegative;
11189     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11190                     Unsigned);
11191   }
11192 
11193   /// Return the range of a difference of the two ranges.
11194   static IntRange difference(IntRange L, IntRange R) {
11195     // We need a 1-bit-wider range if:
11196     //   1) LHS can be negative: least value can be reduced.
11197     //   2) RHS can be negative: greatest value can be increased.
11198     bool CanWiden = !L.NonNegative || !R.NonNegative;
11199     bool Unsigned = L.NonNegative && R.Width == 0;
11200     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11201                         !Unsigned,
11202                     Unsigned);
11203   }
11204 
11205   /// Return the range of a product of the two ranges.
11206   static IntRange product(IntRange L, IntRange R) {
11207     // If both LHS and RHS can be negative, we can form
11208     //   -2^L * -2^R = 2^(L + R)
11209     // which requires L + R + 1 value bits to represent.
11210     bool CanWiden = !L.NonNegative && !R.NonNegative;
11211     bool Unsigned = L.NonNegative && R.NonNegative;
11212     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11213                     Unsigned);
11214   }
11215 
11216   /// Return the range of a remainder operation between the two ranges.
11217   static IntRange rem(IntRange L, IntRange R) {
11218     // The result of a remainder can't be larger than the result of
11219     // either side. The sign of the result is the sign of the LHS.
11220     bool Unsigned = L.NonNegative;
11221     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11222                     Unsigned);
11223   }
11224 };
11225 
11226 } // namespace
11227 
11228 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11229                               unsigned MaxWidth) {
11230   if (value.isSigned() && value.isNegative())
11231     return IntRange(value.getMinSignedBits(), false);
11232 
11233   if (value.getBitWidth() > MaxWidth)
11234     value = value.trunc(MaxWidth);
11235 
11236   // isNonNegative() just checks the sign bit without considering
11237   // signedness.
11238   return IntRange(value.getActiveBits(), true);
11239 }
11240 
11241 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11242                               unsigned MaxWidth) {
11243   if (result.isInt())
11244     return GetValueRange(C, result.getInt(), MaxWidth);
11245 
11246   if (result.isVector()) {
11247     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11248     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11249       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11250       R = IntRange::join(R, El);
11251     }
11252     return R;
11253   }
11254 
11255   if (result.isComplexInt()) {
11256     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11257     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11258     return IntRange::join(R, I);
11259   }
11260 
11261   // This can happen with lossless casts to intptr_t of "based" lvalues.
11262   // Assume it might use arbitrary bits.
11263   // FIXME: The only reason we need to pass the type in here is to get
11264   // the sign right on this one case.  It would be nice if APValue
11265   // preserved this.
11266   assert(result.isLValue() || result.isAddrLabelDiff());
11267   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11268 }
11269 
11270 static QualType GetExprType(const Expr *E) {
11271   QualType Ty = E->getType();
11272   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11273     Ty = AtomicRHS->getValueType();
11274   return Ty;
11275 }
11276 
11277 /// Pseudo-evaluate the given integer expression, estimating the
11278 /// range of values it might take.
11279 ///
11280 /// \param MaxWidth The width to which the value will be truncated.
11281 /// \param Approximate If \c true, return a likely range for the result: in
11282 ///        particular, assume that arithmetic on narrower types doesn't leave
11283 ///        those types. If \c false, return a range including all possible
11284 ///        result values.
11285 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11286                              bool InConstantContext, bool Approximate) {
11287   E = E->IgnoreParens();
11288 
11289   // Try a full evaluation first.
11290   Expr::EvalResult result;
11291   if (E->EvaluateAsRValue(result, C, InConstantContext))
11292     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11293 
11294   // I think we only want to look through implicit casts here; if the
11295   // user has an explicit widening cast, we should treat the value as
11296   // being of the new, wider type.
11297   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11298     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11299       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11300                           Approximate);
11301 
11302     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11303 
11304     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11305                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11306 
11307     // Assume that non-integer casts can span the full range of the type.
11308     if (!isIntegerCast)
11309       return OutputTypeRange;
11310 
11311     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11312                                      std::min(MaxWidth, OutputTypeRange.Width),
11313                                      InConstantContext, Approximate);
11314 
11315     // Bail out if the subexpr's range is as wide as the cast type.
11316     if (SubRange.Width >= OutputTypeRange.Width)
11317       return OutputTypeRange;
11318 
11319     // Otherwise, we take the smaller width, and we're non-negative if
11320     // either the output type or the subexpr is.
11321     return IntRange(SubRange.Width,
11322                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11323   }
11324 
11325   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11326     // If we can fold the condition, just take that operand.
11327     bool CondResult;
11328     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11329       return GetExprRange(C,
11330                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11331                           MaxWidth, InConstantContext, Approximate);
11332 
11333     // Otherwise, conservatively merge.
11334     // GetExprRange requires an integer expression, but a throw expression
11335     // results in a void type.
11336     Expr *E = CO->getTrueExpr();
11337     IntRange L = E->getType()->isVoidType()
11338                      ? IntRange{0, true}
11339                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11340     E = CO->getFalseExpr();
11341     IntRange R = E->getType()->isVoidType()
11342                      ? IntRange{0, true}
11343                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11344     return IntRange::join(L, R);
11345   }
11346 
11347   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11348     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11349 
11350     switch (BO->getOpcode()) {
11351     case BO_Cmp:
11352       llvm_unreachable("builtin <=> should have class type");
11353 
11354     // Boolean-valued operations are single-bit and positive.
11355     case BO_LAnd:
11356     case BO_LOr:
11357     case BO_LT:
11358     case BO_GT:
11359     case BO_LE:
11360     case BO_GE:
11361     case BO_EQ:
11362     case BO_NE:
11363       return IntRange::forBoolType();
11364 
11365     // The type of the assignments is the type of the LHS, so the RHS
11366     // is not necessarily the same type.
11367     case BO_MulAssign:
11368     case BO_DivAssign:
11369     case BO_RemAssign:
11370     case BO_AddAssign:
11371     case BO_SubAssign:
11372     case BO_XorAssign:
11373     case BO_OrAssign:
11374       // TODO: bitfields?
11375       return IntRange::forValueOfType(C, GetExprType(E));
11376 
11377     // Simple assignments just pass through the RHS, which will have
11378     // been coerced to the LHS type.
11379     case BO_Assign:
11380       // TODO: bitfields?
11381       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11382                           Approximate);
11383 
11384     // Operations with opaque sources are black-listed.
11385     case BO_PtrMemD:
11386     case BO_PtrMemI:
11387       return IntRange::forValueOfType(C, GetExprType(E));
11388 
11389     // Bitwise-and uses the *infinum* of the two source ranges.
11390     case BO_And:
11391     case BO_AndAssign:
11392       Combine = IntRange::bit_and;
11393       break;
11394 
11395     // Left shift gets black-listed based on a judgement call.
11396     case BO_Shl:
11397       // ...except that we want to treat '1 << (blah)' as logically
11398       // positive.  It's an important idiom.
11399       if (IntegerLiteral *I
11400             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11401         if (I->getValue() == 1) {
11402           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11403           return IntRange(R.Width, /*NonNegative*/ true);
11404         }
11405       }
11406       LLVM_FALLTHROUGH;
11407 
11408     case BO_ShlAssign:
11409       return IntRange::forValueOfType(C, GetExprType(E));
11410 
11411     // Right shift by a constant can narrow its left argument.
11412     case BO_Shr:
11413     case BO_ShrAssign: {
11414       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11415                                 Approximate);
11416 
11417       // If the shift amount is a positive constant, drop the width by
11418       // that much.
11419       if (Optional<llvm::APSInt> shift =
11420               BO->getRHS()->getIntegerConstantExpr(C)) {
11421         if (shift->isNonNegative()) {
11422           unsigned zext = shift->getZExtValue();
11423           if (zext >= L.Width)
11424             L.Width = (L.NonNegative ? 0 : 1);
11425           else
11426             L.Width -= zext;
11427         }
11428       }
11429 
11430       return L;
11431     }
11432 
11433     // Comma acts as its right operand.
11434     case BO_Comma:
11435       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11436                           Approximate);
11437 
11438     case BO_Add:
11439       if (!Approximate)
11440         Combine = IntRange::sum;
11441       break;
11442 
11443     case BO_Sub:
11444       if (BO->getLHS()->getType()->isPointerType())
11445         return IntRange::forValueOfType(C, GetExprType(E));
11446       if (!Approximate)
11447         Combine = IntRange::difference;
11448       break;
11449 
11450     case BO_Mul:
11451       if (!Approximate)
11452         Combine = IntRange::product;
11453       break;
11454 
11455     // The width of a division result is mostly determined by the size
11456     // of the LHS.
11457     case BO_Div: {
11458       // Don't 'pre-truncate' the operands.
11459       unsigned opWidth = C.getIntWidth(GetExprType(E));
11460       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11461                                 Approximate);
11462 
11463       // If the divisor is constant, use that.
11464       if (Optional<llvm::APSInt> divisor =
11465               BO->getRHS()->getIntegerConstantExpr(C)) {
11466         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11467         if (log2 >= L.Width)
11468           L.Width = (L.NonNegative ? 0 : 1);
11469         else
11470           L.Width = std::min(L.Width - log2, MaxWidth);
11471         return L;
11472       }
11473 
11474       // Otherwise, just use the LHS's width.
11475       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11476       // could be -1.
11477       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11478                                 Approximate);
11479       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11480     }
11481 
11482     case BO_Rem:
11483       Combine = IntRange::rem;
11484       break;
11485 
11486     // The default behavior is okay for these.
11487     case BO_Xor:
11488     case BO_Or:
11489       break;
11490     }
11491 
11492     // Combine the two ranges, but limit the result to the type in which we
11493     // performed the computation.
11494     QualType T = GetExprType(E);
11495     unsigned opWidth = C.getIntWidth(T);
11496     IntRange L =
11497         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11498     IntRange R =
11499         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11500     IntRange C = Combine(L, R);
11501     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11502     C.Width = std::min(C.Width, MaxWidth);
11503     return C;
11504   }
11505 
11506   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11507     switch (UO->getOpcode()) {
11508     // Boolean-valued operations are white-listed.
11509     case UO_LNot:
11510       return IntRange::forBoolType();
11511 
11512     // Operations with opaque sources are black-listed.
11513     case UO_Deref:
11514     case UO_AddrOf: // should be impossible
11515       return IntRange::forValueOfType(C, GetExprType(E));
11516 
11517     default:
11518       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11519                           Approximate);
11520     }
11521   }
11522 
11523   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11524     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11525                         Approximate);
11526 
11527   if (const auto *BitField = E->getSourceBitField())
11528     return IntRange(BitField->getBitWidthValue(C),
11529                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11530 
11531   return IntRange::forValueOfType(C, GetExprType(E));
11532 }
11533 
11534 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11535                              bool InConstantContext, bool Approximate) {
11536   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11537                       Approximate);
11538 }
11539 
11540 /// Checks whether the given value, which currently has the given
11541 /// source semantics, has the same value when coerced through the
11542 /// target semantics.
11543 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11544                                  const llvm::fltSemantics &Src,
11545                                  const llvm::fltSemantics &Tgt) {
11546   llvm::APFloat truncated = value;
11547 
11548   bool ignored;
11549   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11550   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11551 
11552   return truncated.bitwiseIsEqual(value);
11553 }
11554 
11555 /// Checks whether the given value, which currently has the given
11556 /// source semantics, has the same value when coerced through the
11557 /// target semantics.
11558 ///
11559 /// The value might be a vector of floats (or a complex number).
11560 static bool IsSameFloatAfterCast(const APValue &value,
11561                                  const llvm::fltSemantics &Src,
11562                                  const llvm::fltSemantics &Tgt) {
11563   if (value.isFloat())
11564     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11565 
11566   if (value.isVector()) {
11567     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11568       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11569         return false;
11570     return true;
11571   }
11572 
11573   assert(value.isComplexFloat());
11574   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11575           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11576 }
11577 
11578 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11579                                        bool IsListInit = false);
11580 
11581 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11582   // Suppress cases where we are comparing against an enum constant.
11583   if (const DeclRefExpr *DR =
11584       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11585     if (isa<EnumConstantDecl>(DR->getDecl()))
11586       return true;
11587 
11588   // Suppress cases where the value is expanded from a macro, unless that macro
11589   // is how a language represents a boolean literal. This is the case in both C
11590   // and Objective-C.
11591   SourceLocation BeginLoc = E->getBeginLoc();
11592   if (BeginLoc.isMacroID()) {
11593     StringRef MacroName = Lexer::getImmediateMacroName(
11594         BeginLoc, S.getSourceManager(), S.getLangOpts());
11595     return MacroName != "YES" && MacroName != "NO" &&
11596            MacroName != "true" && MacroName != "false";
11597   }
11598 
11599   return false;
11600 }
11601 
11602 static bool isKnownToHaveUnsignedValue(Expr *E) {
11603   return E->getType()->isIntegerType() &&
11604          (!E->getType()->isSignedIntegerType() ||
11605           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11606 }
11607 
11608 namespace {
11609 /// The promoted range of values of a type. In general this has the
11610 /// following structure:
11611 ///
11612 ///     |-----------| . . . |-----------|
11613 ///     ^           ^       ^           ^
11614 ///    Min       HoleMin  HoleMax      Max
11615 ///
11616 /// ... where there is only a hole if a signed type is promoted to unsigned
11617 /// (in which case Min and Max are the smallest and largest representable
11618 /// values).
11619 struct PromotedRange {
11620   // Min, or HoleMax if there is a hole.
11621   llvm::APSInt PromotedMin;
11622   // Max, or HoleMin if there is a hole.
11623   llvm::APSInt PromotedMax;
11624 
11625   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11626     if (R.Width == 0)
11627       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11628     else if (R.Width >= BitWidth && !Unsigned) {
11629       // Promotion made the type *narrower*. This happens when promoting
11630       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11631       // Treat all values of 'signed int' as being in range for now.
11632       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11633       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11634     } else {
11635       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11636                         .extOrTrunc(BitWidth);
11637       PromotedMin.setIsUnsigned(Unsigned);
11638 
11639       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11640                         .extOrTrunc(BitWidth);
11641       PromotedMax.setIsUnsigned(Unsigned);
11642     }
11643   }
11644 
11645   // Determine whether this range is contiguous (has no hole).
11646   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11647 
11648   // Where a constant value is within the range.
11649   enum ComparisonResult {
11650     LT = 0x1,
11651     LE = 0x2,
11652     GT = 0x4,
11653     GE = 0x8,
11654     EQ = 0x10,
11655     NE = 0x20,
11656     InRangeFlag = 0x40,
11657 
11658     Less = LE | LT | NE,
11659     Min = LE | InRangeFlag,
11660     InRange = InRangeFlag,
11661     Max = GE | InRangeFlag,
11662     Greater = GE | GT | NE,
11663 
11664     OnlyValue = LE | GE | EQ | InRangeFlag,
11665     InHole = NE
11666   };
11667 
11668   ComparisonResult compare(const llvm::APSInt &Value) const {
11669     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11670            Value.isUnsigned() == PromotedMin.isUnsigned());
11671     if (!isContiguous()) {
11672       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11673       if (Value.isMinValue()) return Min;
11674       if (Value.isMaxValue()) return Max;
11675       if (Value >= PromotedMin) return InRange;
11676       if (Value <= PromotedMax) return InRange;
11677       return InHole;
11678     }
11679 
11680     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11681     case -1: return Less;
11682     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11683     case 1:
11684       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11685       case -1: return InRange;
11686       case 0: return Max;
11687       case 1: return Greater;
11688       }
11689     }
11690 
11691     llvm_unreachable("impossible compare result");
11692   }
11693 
11694   static llvm::Optional<StringRef>
11695   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11696     if (Op == BO_Cmp) {
11697       ComparisonResult LTFlag = LT, GTFlag = GT;
11698       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11699 
11700       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11701       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11702       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11703       return llvm::None;
11704     }
11705 
11706     ComparisonResult TrueFlag, FalseFlag;
11707     if (Op == BO_EQ) {
11708       TrueFlag = EQ;
11709       FalseFlag = NE;
11710     } else if (Op == BO_NE) {
11711       TrueFlag = NE;
11712       FalseFlag = EQ;
11713     } else {
11714       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11715         TrueFlag = LT;
11716         FalseFlag = GE;
11717       } else {
11718         TrueFlag = GT;
11719         FalseFlag = LE;
11720       }
11721       if (Op == BO_GE || Op == BO_LE)
11722         std::swap(TrueFlag, FalseFlag);
11723     }
11724     if (R & TrueFlag)
11725       return StringRef("true");
11726     if (R & FalseFlag)
11727       return StringRef("false");
11728     return llvm::None;
11729   }
11730 };
11731 }
11732 
11733 static bool HasEnumType(Expr *E) {
11734   // Strip off implicit integral promotions.
11735   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11736     if (ICE->getCastKind() != CK_IntegralCast &&
11737         ICE->getCastKind() != CK_NoOp)
11738       break;
11739     E = ICE->getSubExpr();
11740   }
11741 
11742   return E->getType()->isEnumeralType();
11743 }
11744 
11745 static int classifyConstantValue(Expr *Constant) {
11746   // The values of this enumeration are used in the diagnostics
11747   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11748   enum ConstantValueKind {
11749     Miscellaneous = 0,
11750     LiteralTrue,
11751     LiteralFalse
11752   };
11753   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11754     return BL->getValue() ? ConstantValueKind::LiteralTrue
11755                           : ConstantValueKind::LiteralFalse;
11756   return ConstantValueKind::Miscellaneous;
11757 }
11758 
11759 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11760                                         Expr *Constant, Expr *Other,
11761                                         const llvm::APSInt &Value,
11762                                         bool RhsConstant) {
11763   if (S.inTemplateInstantiation())
11764     return false;
11765 
11766   Expr *OriginalOther = Other;
11767 
11768   Constant = Constant->IgnoreParenImpCasts();
11769   Other = Other->IgnoreParenImpCasts();
11770 
11771   // Suppress warnings on tautological comparisons between values of the same
11772   // enumeration type. There are only two ways we could warn on this:
11773   //  - If the constant is outside the range of representable values of
11774   //    the enumeration. In such a case, we should warn about the cast
11775   //    to enumeration type, not about the comparison.
11776   //  - If the constant is the maximum / minimum in-range value. For an
11777   //    enumeratin type, such comparisons can be meaningful and useful.
11778   if (Constant->getType()->isEnumeralType() &&
11779       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11780     return false;
11781 
11782   IntRange OtherValueRange = GetExprRange(
11783       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11784 
11785   QualType OtherT = Other->getType();
11786   if (const auto *AT = OtherT->getAs<AtomicType>())
11787     OtherT = AT->getValueType();
11788   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11789 
11790   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11791   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11792   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11793                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11794                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11795 
11796   // Whether we're treating Other as being a bool because of the form of
11797   // expression despite it having another type (typically 'int' in C).
11798   bool OtherIsBooleanDespiteType =
11799       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11800   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11801     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11802 
11803   // Check if all values in the range of possible values of this expression
11804   // lead to the same comparison outcome.
11805   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11806                                         Value.isUnsigned());
11807   auto Cmp = OtherPromotedValueRange.compare(Value);
11808   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11809   if (!Result)
11810     return false;
11811 
11812   // Also consider the range determined by the type alone. This allows us to
11813   // classify the warning under the proper diagnostic group.
11814   bool TautologicalTypeCompare = false;
11815   {
11816     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11817                                          Value.isUnsigned());
11818     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11819     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11820                                                        RhsConstant)) {
11821       TautologicalTypeCompare = true;
11822       Cmp = TypeCmp;
11823       Result = TypeResult;
11824     }
11825   }
11826 
11827   // Don't warn if the non-constant operand actually always evaluates to the
11828   // same value.
11829   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11830     return false;
11831 
11832   // Suppress the diagnostic for an in-range comparison if the constant comes
11833   // from a macro or enumerator. We don't want to diagnose
11834   //
11835   //   some_long_value <= INT_MAX
11836   //
11837   // when sizeof(int) == sizeof(long).
11838   bool InRange = Cmp & PromotedRange::InRangeFlag;
11839   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11840     return false;
11841 
11842   // A comparison of an unsigned bit-field against 0 is really a type problem,
11843   // even though at the type level the bit-field might promote to 'signed int'.
11844   if (Other->refersToBitField() && InRange && Value == 0 &&
11845       Other->getType()->isUnsignedIntegerOrEnumerationType())
11846     TautologicalTypeCompare = true;
11847 
11848   // If this is a comparison to an enum constant, include that
11849   // constant in the diagnostic.
11850   const EnumConstantDecl *ED = nullptr;
11851   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11852     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11853 
11854   // Should be enough for uint128 (39 decimal digits)
11855   SmallString<64> PrettySourceValue;
11856   llvm::raw_svector_ostream OS(PrettySourceValue);
11857   if (ED) {
11858     OS << '\'' << *ED << "' (" << Value << ")";
11859   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11860                Constant->IgnoreParenImpCasts())) {
11861     OS << (BL->getValue() ? "YES" : "NO");
11862   } else {
11863     OS << Value;
11864   }
11865 
11866   if (!TautologicalTypeCompare) {
11867     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11868         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11869         << E->getOpcodeStr() << OS.str() << *Result
11870         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11871     return true;
11872   }
11873 
11874   if (IsObjCSignedCharBool) {
11875     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11876                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11877                               << OS.str() << *Result);
11878     return true;
11879   }
11880 
11881   // FIXME: We use a somewhat different formatting for the in-range cases and
11882   // cases involving boolean values for historical reasons. We should pick a
11883   // consistent way of presenting these diagnostics.
11884   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11885 
11886     S.DiagRuntimeBehavior(
11887         E->getOperatorLoc(), E,
11888         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11889                          : diag::warn_tautological_bool_compare)
11890             << OS.str() << classifyConstantValue(Constant) << OtherT
11891             << OtherIsBooleanDespiteType << *Result
11892             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11893   } else {
11894     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11895     unsigned Diag =
11896         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11897             ? (HasEnumType(OriginalOther)
11898                    ? diag::warn_unsigned_enum_always_true_comparison
11899                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11900                               : diag::warn_unsigned_always_true_comparison)
11901             : diag::warn_tautological_constant_compare;
11902 
11903     S.Diag(E->getOperatorLoc(), Diag)
11904         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11905         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11906   }
11907 
11908   return true;
11909 }
11910 
11911 /// Analyze the operands of the given comparison.  Implements the
11912 /// fallback case from AnalyzeComparison.
11913 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11914   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11915   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11916 }
11917 
11918 /// Implements -Wsign-compare.
11919 ///
11920 /// \param E the binary operator to check for warnings
11921 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11922   // The type the comparison is being performed in.
11923   QualType T = E->getLHS()->getType();
11924 
11925   // Only analyze comparison operators where both sides have been converted to
11926   // the same type.
11927   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11928     return AnalyzeImpConvsInComparison(S, E);
11929 
11930   // Don't analyze value-dependent comparisons directly.
11931   if (E->isValueDependent())
11932     return AnalyzeImpConvsInComparison(S, E);
11933 
11934   Expr *LHS = E->getLHS();
11935   Expr *RHS = E->getRHS();
11936 
11937   if (T->isIntegralType(S.Context)) {
11938     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11939     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11940 
11941     // We don't care about expressions whose result is a constant.
11942     if (RHSValue && LHSValue)
11943       return AnalyzeImpConvsInComparison(S, E);
11944 
11945     // We only care about expressions where just one side is literal
11946     if ((bool)RHSValue ^ (bool)LHSValue) {
11947       // Is the constant on the RHS or LHS?
11948       const bool RhsConstant = (bool)RHSValue;
11949       Expr *Const = RhsConstant ? RHS : LHS;
11950       Expr *Other = RhsConstant ? LHS : RHS;
11951       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11952 
11953       // Check whether an integer constant comparison results in a value
11954       // of 'true' or 'false'.
11955       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11956         return AnalyzeImpConvsInComparison(S, E);
11957     }
11958   }
11959 
11960   if (!T->hasUnsignedIntegerRepresentation()) {
11961     // We don't do anything special if this isn't an unsigned integral
11962     // comparison:  we're only interested in integral comparisons, and
11963     // signed comparisons only happen in cases we don't care to warn about.
11964     return AnalyzeImpConvsInComparison(S, E);
11965   }
11966 
11967   LHS = LHS->IgnoreParenImpCasts();
11968   RHS = RHS->IgnoreParenImpCasts();
11969 
11970   if (!S.getLangOpts().CPlusPlus) {
11971     // Avoid warning about comparison of integers with different signs when
11972     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11973     // the type of `E`.
11974     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11975       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11976     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11977       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11978   }
11979 
11980   // Check to see if one of the (unmodified) operands is of different
11981   // signedness.
11982   Expr *signedOperand, *unsignedOperand;
11983   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11984     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11985            "unsigned comparison between two signed integer expressions?");
11986     signedOperand = LHS;
11987     unsignedOperand = RHS;
11988   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11989     signedOperand = RHS;
11990     unsignedOperand = LHS;
11991   } else {
11992     return AnalyzeImpConvsInComparison(S, E);
11993   }
11994 
11995   // Otherwise, calculate the effective range of the signed operand.
11996   IntRange signedRange = GetExprRange(
11997       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11998 
11999   // Go ahead and analyze implicit conversions in the operands.  Note
12000   // that we skip the implicit conversions on both sides.
12001   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12002   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12003 
12004   // If the signed range is non-negative, -Wsign-compare won't fire.
12005   if (signedRange.NonNegative)
12006     return;
12007 
12008   // For (in)equality comparisons, if the unsigned operand is a
12009   // constant which cannot collide with a overflowed signed operand,
12010   // then reinterpreting the signed operand as unsigned will not
12011   // change the result of the comparison.
12012   if (E->isEqualityOp()) {
12013     unsigned comparisonWidth = S.Context.getIntWidth(T);
12014     IntRange unsignedRange =
12015         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12016                      /*Approximate*/ true);
12017 
12018     // We should never be unable to prove that the unsigned operand is
12019     // non-negative.
12020     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12021 
12022     if (unsignedRange.Width < comparisonWidth)
12023       return;
12024   }
12025 
12026   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12027                         S.PDiag(diag::warn_mixed_sign_comparison)
12028                             << LHS->getType() << RHS->getType()
12029                             << LHS->getSourceRange() << RHS->getSourceRange());
12030 }
12031 
12032 /// Analyzes an attempt to assign the given value to a bitfield.
12033 ///
12034 /// Returns true if there was something fishy about the attempt.
12035 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12036                                       SourceLocation InitLoc) {
12037   assert(Bitfield->isBitField());
12038   if (Bitfield->isInvalidDecl())
12039     return false;
12040 
12041   // White-list bool bitfields.
12042   QualType BitfieldType = Bitfield->getType();
12043   if (BitfieldType->isBooleanType())
12044      return false;
12045 
12046   if (BitfieldType->isEnumeralType()) {
12047     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12048     // If the underlying enum type was not explicitly specified as an unsigned
12049     // type and the enum contain only positive values, MSVC++ will cause an
12050     // inconsistency by storing this as a signed type.
12051     if (S.getLangOpts().CPlusPlus11 &&
12052         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12053         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12054         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12055       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12056           << BitfieldEnumDecl;
12057     }
12058   }
12059 
12060   if (Bitfield->getType()->isBooleanType())
12061     return false;
12062 
12063   // Ignore value- or type-dependent expressions.
12064   if (Bitfield->getBitWidth()->isValueDependent() ||
12065       Bitfield->getBitWidth()->isTypeDependent() ||
12066       Init->isValueDependent() ||
12067       Init->isTypeDependent())
12068     return false;
12069 
12070   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12071   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12072 
12073   Expr::EvalResult Result;
12074   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12075                                    Expr::SE_AllowSideEffects)) {
12076     // The RHS is not constant.  If the RHS has an enum type, make sure the
12077     // bitfield is wide enough to hold all the values of the enum without
12078     // truncation.
12079     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12080       EnumDecl *ED = EnumTy->getDecl();
12081       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12082 
12083       // Enum types are implicitly signed on Windows, so check if there are any
12084       // negative enumerators to see if the enum was intended to be signed or
12085       // not.
12086       bool SignedEnum = ED->getNumNegativeBits() > 0;
12087 
12088       // Check for surprising sign changes when assigning enum values to a
12089       // bitfield of different signedness.  If the bitfield is signed and we
12090       // have exactly the right number of bits to store this unsigned enum,
12091       // suggest changing the enum to an unsigned type. This typically happens
12092       // on Windows where unfixed enums always use an underlying type of 'int'.
12093       unsigned DiagID = 0;
12094       if (SignedEnum && !SignedBitfield) {
12095         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12096       } else if (SignedBitfield && !SignedEnum &&
12097                  ED->getNumPositiveBits() == FieldWidth) {
12098         DiagID = diag::warn_signed_bitfield_enum_conversion;
12099       }
12100 
12101       if (DiagID) {
12102         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12103         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12104         SourceRange TypeRange =
12105             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12106         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12107             << SignedEnum << TypeRange;
12108       }
12109 
12110       // Compute the required bitwidth. If the enum has negative values, we need
12111       // one more bit than the normal number of positive bits to represent the
12112       // sign bit.
12113       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12114                                                   ED->getNumNegativeBits())
12115                                        : ED->getNumPositiveBits();
12116 
12117       // Check the bitwidth.
12118       if (BitsNeeded > FieldWidth) {
12119         Expr *WidthExpr = Bitfield->getBitWidth();
12120         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12121             << Bitfield << ED;
12122         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12123             << BitsNeeded << ED << WidthExpr->getSourceRange();
12124       }
12125     }
12126 
12127     return false;
12128   }
12129 
12130   llvm::APSInt Value = Result.Val.getInt();
12131 
12132   unsigned OriginalWidth = Value.getBitWidth();
12133 
12134   if (!Value.isSigned() || Value.isNegative())
12135     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12136       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12137         OriginalWidth = Value.getMinSignedBits();
12138 
12139   if (OriginalWidth <= FieldWidth)
12140     return false;
12141 
12142   // Compute the value which the bitfield will contain.
12143   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12144   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12145 
12146   // Check whether the stored value is equal to the original value.
12147   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12148   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12149     return false;
12150 
12151   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12152   // therefore don't strictly fit into a signed bitfield of width 1.
12153   if (FieldWidth == 1 && Value == 1)
12154     return false;
12155 
12156   std::string PrettyValue = toString(Value, 10);
12157   std::string PrettyTrunc = toString(TruncatedValue, 10);
12158 
12159   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12160     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12161     << Init->getSourceRange();
12162 
12163   return true;
12164 }
12165 
12166 /// Analyze the given simple or compound assignment for warning-worthy
12167 /// operations.
12168 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12169   // Just recurse on the LHS.
12170   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12171 
12172   // We want to recurse on the RHS as normal unless we're assigning to
12173   // a bitfield.
12174   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12175     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12176                                   E->getOperatorLoc())) {
12177       // Recurse, ignoring any implicit conversions on the RHS.
12178       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12179                                         E->getOperatorLoc());
12180     }
12181   }
12182 
12183   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12184 
12185   // Diagnose implicitly sequentially-consistent atomic assignment.
12186   if (E->getLHS()->getType()->isAtomicType())
12187     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12188 }
12189 
12190 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12191 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12192                             SourceLocation CContext, unsigned diag,
12193                             bool pruneControlFlow = false) {
12194   if (pruneControlFlow) {
12195     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12196                           S.PDiag(diag)
12197                               << SourceType << T << E->getSourceRange()
12198                               << SourceRange(CContext));
12199     return;
12200   }
12201   S.Diag(E->getExprLoc(), diag)
12202     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12203 }
12204 
12205 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12206 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12207                             SourceLocation CContext,
12208                             unsigned diag, bool pruneControlFlow = false) {
12209   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12210 }
12211 
12212 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12213   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12214       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12215 }
12216 
12217 static void adornObjCBoolConversionDiagWithTernaryFixit(
12218     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12219   Expr *Ignored = SourceExpr->IgnoreImplicit();
12220   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12221     Ignored = OVE->getSourceExpr();
12222   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12223                      isa<BinaryOperator>(Ignored) ||
12224                      isa<CXXOperatorCallExpr>(Ignored);
12225   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12226   if (NeedsParens)
12227     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12228             << FixItHint::CreateInsertion(EndLoc, ")");
12229   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12230 }
12231 
12232 /// Diagnose an implicit cast from a floating point value to an integer value.
12233 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12234                                     SourceLocation CContext) {
12235   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12236   const bool PruneWarnings = S.inTemplateInstantiation();
12237 
12238   Expr *InnerE = E->IgnoreParenImpCasts();
12239   // We also want to warn on, e.g., "int i = -1.234"
12240   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12241     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12242       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12243 
12244   const bool IsLiteral =
12245       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12246 
12247   llvm::APFloat Value(0.0);
12248   bool IsConstant =
12249     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12250   if (!IsConstant) {
12251     if (isObjCSignedCharBool(S, T)) {
12252       return adornObjCBoolConversionDiagWithTernaryFixit(
12253           S, E,
12254           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12255               << E->getType());
12256     }
12257 
12258     return DiagnoseImpCast(S, E, T, CContext,
12259                            diag::warn_impcast_float_integer, PruneWarnings);
12260   }
12261 
12262   bool isExact = false;
12263 
12264   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12265                             T->hasUnsignedIntegerRepresentation());
12266   llvm::APFloat::opStatus Result = Value.convertToInteger(
12267       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12268 
12269   // FIXME: Force the precision of the source value down so we don't print
12270   // digits which are usually useless (we don't really care here if we
12271   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12272   // would automatically print the shortest representation, but it's a bit
12273   // tricky to implement.
12274   SmallString<16> PrettySourceValue;
12275   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12276   precision = (precision * 59 + 195) / 196;
12277   Value.toString(PrettySourceValue, precision);
12278 
12279   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12280     return adornObjCBoolConversionDiagWithTernaryFixit(
12281         S, E,
12282         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12283             << PrettySourceValue);
12284   }
12285 
12286   if (Result == llvm::APFloat::opOK && isExact) {
12287     if (IsLiteral) return;
12288     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12289                            PruneWarnings);
12290   }
12291 
12292   // Conversion of a floating-point value to a non-bool integer where the
12293   // integral part cannot be represented by the integer type is undefined.
12294   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12295     return DiagnoseImpCast(
12296         S, E, T, CContext,
12297         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12298                   : diag::warn_impcast_float_to_integer_out_of_range,
12299         PruneWarnings);
12300 
12301   unsigned DiagID = 0;
12302   if (IsLiteral) {
12303     // Warn on floating point literal to integer.
12304     DiagID = diag::warn_impcast_literal_float_to_integer;
12305   } else if (IntegerValue == 0) {
12306     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12307       return DiagnoseImpCast(S, E, T, CContext,
12308                              diag::warn_impcast_float_integer, PruneWarnings);
12309     }
12310     // Warn on non-zero to zero conversion.
12311     DiagID = diag::warn_impcast_float_to_integer_zero;
12312   } else {
12313     if (IntegerValue.isUnsigned()) {
12314       if (!IntegerValue.isMaxValue()) {
12315         return DiagnoseImpCast(S, E, T, CContext,
12316                                diag::warn_impcast_float_integer, PruneWarnings);
12317       }
12318     } else {  // IntegerValue.isSigned()
12319       if (!IntegerValue.isMaxSignedValue() &&
12320           !IntegerValue.isMinSignedValue()) {
12321         return DiagnoseImpCast(S, E, T, CContext,
12322                                diag::warn_impcast_float_integer, PruneWarnings);
12323       }
12324     }
12325     // Warn on evaluatable floating point expression to integer conversion.
12326     DiagID = diag::warn_impcast_float_to_integer;
12327   }
12328 
12329   SmallString<16> PrettyTargetValue;
12330   if (IsBool)
12331     PrettyTargetValue = Value.isZero() ? "false" : "true";
12332   else
12333     IntegerValue.toString(PrettyTargetValue);
12334 
12335   if (PruneWarnings) {
12336     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12337                           S.PDiag(DiagID)
12338                               << E->getType() << T.getUnqualifiedType()
12339                               << PrettySourceValue << PrettyTargetValue
12340                               << E->getSourceRange() << SourceRange(CContext));
12341   } else {
12342     S.Diag(E->getExprLoc(), DiagID)
12343         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12344         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12345   }
12346 }
12347 
12348 /// Analyze the given compound assignment for the possible losing of
12349 /// floating-point precision.
12350 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12351   assert(isa<CompoundAssignOperator>(E) &&
12352          "Must be compound assignment operation");
12353   // Recurse on the LHS and RHS in here
12354   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12355   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12356 
12357   if (E->getLHS()->getType()->isAtomicType())
12358     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12359 
12360   // Now check the outermost expression
12361   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12362   const auto *RBT = cast<CompoundAssignOperator>(E)
12363                         ->getComputationResultType()
12364                         ->getAs<BuiltinType>();
12365 
12366   // The below checks assume source is floating point.
12367   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12368 
12369   // If source is floating point but target is an integer.
12370   if (ResultBT->isInteger())
12371     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12372                            E->getExprLoc(), diag::warn_impcast_float_integer);
12373 
12374   if (!ResultBT->isFloatingPoint())
12375     return;
12376 
12377   // If both source and target are floating points, warn about losing precision.
12378   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12379       QualType(ResultBT, 0), QualType(RBT, 0));
12380   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12381     // warn about dropping FP rank.
12382     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12383                     diag::warn_impcast_float_result_precision);
12384 }
12385 
12386 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12387                                       IntRange Range) {
12388   if (!Range.Width) return "0";
12389 
12390   llvm::APSInt ValueInRange = Value;
12391   ValueInRange.setIsSigned(!Range.NonNegative);
12392   ValueInRange = ValueInRange.trunc(Range.Width);
12393   return toString(ValueInRange, 10);
12394 }
12395 
12396 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12397   if (!isa<ImplicitCastExpr>(Ex))
12398     return false;
12399 
12400   Expr *InnerE = Ex->IgnoreParenImpCasts();
12401   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12402   const Type *Source =
12403     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12404   if (Target->isDependentType())
12405     return false;
12406 
12407   const BuiltinType *FloatCandidateBT =
12408     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12409   const Type *BoolCandidateType = ToBool ? Target : Source;
12410 
12411   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12412           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12413 }
12414 
12415 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12416                                              SourceLocation CC) {
12417   unsigned NumArgs = TheCall->getNumArgs();
12418   for (unsigned i = 0; i < NumArgs; ++i) {
12419     Expr *CurrA = TheCall->getArg(i);
12420     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12421       continue;
12422 
12423     bool IsSwapped = ((i > 0) &&
12424         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12425     IsSwapped |= ((i < (NumArgs - 1)) &&
12426         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12427     if (IsSwapped) {
12428       // Warn on this floating-point to bool conversion.
12429       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12430                       CurrA->getType(), CC,
12431                       diag::warn_impcast_floating_point_to_bool);
12432     }
12433   }
12434 }
12435 
12436 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12437                                    SourceLocation CC) {
12438   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12439                         E->getExprLoc()))
12440     return;
12441 
12442   // Don't warn on functions which have return type nullptr_t.
12443   if (isa<CallExpr>(E))
12444     return;
12445 
12446   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12447   const Expr::NullPointerConstantKind NullKind =
12448       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12449   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12450     return;
12451 
12452   // Return if target type is a safe conversion.
12453   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12454       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12455     return;
12456 
12457   SourceLocation Loc = E->getSourceRange().getBegin();
12458 
12459   // Venture through the macro stacks to get to the source of macro arguments.
12460   // The new location is a better location than the complete location that was
12461   // passed in.
12462   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12463   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12464 
12465   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12466   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12467     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12468         Loc, S.SourceMgr, S.getLangOpts());
12469     if (MacroName == "NULL")
12470       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12471   }
12472 
12473   // Only warn if the null and context location are in the same macro expansion.
12474   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12475     return;
12476 
12477   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12478       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12479       << FixItHint::CreateReplacement(Loc,
12480                                       S.getFixItZeroLiteralForType(T, Loc));
12481 }
12482 
12483 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12484                                   ObjCArrayLiteral *ArrayLiteral);
12485 
12486 static void
12487 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12488                            ObjCDictionaryLiteral *DictionaryLiteral);
12489 
12490 /// Check a single element within a collection literal against the
12491 /// target element type.
12492 static void checkObjCCollectionLiteralElement(Sema &S,
12493                                               QualType TargetElementType,
12494                                               Expr *Element,
12495                                               unsigned ElementKind) {
12496   // Skip a bitcast to 'id' or qualified 'id'.
12497   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12498     if (ICE->getCastKind() == CK_BitCast &&
12499         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12500       Element = ICE->getSubExpr();
12501   }
12502 
12503   QualType ElementType = Element->getType();
12504   ExprResult ElementResult(Element);
12505   if (ElementType->getAs<ObjCObjectPointerType>() &&
12506       S.CheckSingleAssignmentConstraints(TargetElementType,
12507                                          ElementResult,
12508                                          false, false)
12509         != Sema::Compatible) {
12510     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12511         << ElementType << ElementKind << TargetElementType
12512         << Element->getSourceRange();
12513   }
12514 
12515   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12516     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12517   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12518     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12519 }
12520 
12521 /// Check an Objective-C array literal being converted to the given
12522 /// target type.
12523 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12524                                   ObjCArrayLiteral *ArrayLiteral) {
12525   if (!S.NSArrayDecl)
12526     return;
12527 
12528   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12529   if (!TargetObjCPtr)
12530     return;
12531 
12532   if (TargetObjCPtr->isUnspecialized() ||
12533       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12534         != S.NSArrayDecl->getCanonicalDecl())
12535     return;
12536 
12537   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12538   if (TypeArgs.size() != 1)
12539     return;
12540 
12541   QualType TargetElementType = TypeArgs[0];
12542   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12543     checkObjCCollectionLiteralElement(S, TargetElementType,
12544                                       ArrayLiteral->getElement(I),
12545                                       0);
12546   }
12547 }
12548 
12549 /// Check an Objective-C dictionary literal being converted to the given
12550 /// target type.
12551 static void
12552 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12553                            ObjCDictionaryLiteral *DictionaryLiteral) {
12554   if (!S.NSDictionaryDecl)
12555     return;
12556 
12557   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12558   if (!TargetObjCPtr)
12559     return;
12560 
12561   if (TargetObjCPtr->isUnspecialized() ||
12562       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12563         != S.NSDictionaryDecl->getCanonicalDecl())
12564     return;
12565 
12566   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12567   if (TypeArgs.size() != 2)
12568     return;
12569 
12570   QualType TargetKeyType = TypeArgs[0];
12571   QualType TargetObjectType = TypeArgs[1];
12572   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12573     auto Element = DictionaryLiteral->getKeyValueElement(I);
12574     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12575     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12576   }
12577 }
12578 
12579 // Helper function to filter out cases for constant width constant conversion.
12580 // Don't warn on char array initialization or for non-decimal values.
12581 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12582                                           SourceLocation CC) {
12583   // If initializing from a constant, and the constant starts with '0',
12584   // then it is a binary, octal, or hexadecimal.  Allow these constants
12585   // to fill all the bits, even if there is a sign change.
12586   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12587     const char FirstLiteralCharacter =
12588         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12589     if (FirstLiteralCharacter == '0')
12590       return false;
12591   }
12592 
12593   // If the CC location points to a '{', and the type is char, then assume
12594   // assume it is an array initialization.
12595   if (CC.isValid() && T->isCharType()) {
12596     const char FirstContextCharacter =
12597         S.getSourceManager().getCharacterData(CC)[0];
12598     if (FirstContextCharacter == '{')
12599       return false;
12600   }
12601 
12602   return true;
12603 }
12604 
12605 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12606   const auto *IL = dyn_cast<IntegerLiteral>(E);
12607   if (!IL) {
12608     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12609       if (UO->getOpcode() == UO_Minus)
12610         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12611     }
12612   }
12613 
12614   return IL;
12615 }
12616 
12617 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12618   E = E->IgnoreParenImpCasts();
12619   SourceLocation ExprLoc = E->getExprLoc();
12620 
12621   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12622     BinaryOperator::Opcode Opc = BO->getOpcode();
12623     Expr::EvalResult Result;
12624     // Do not diagnose unsigned shifts.
12625     if (Opc == BO_Shl) {
12626       const auto *LHS = getIntegerLiteral(BO->getLHS());
12627       const auto *RHS = getIntegerLiteral(BO->getRHS());
12628       if (LHS && LHS->getValue() == 0)
12629         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12630       else if (!E->isValueDependent() && LHS && RHS &&
12631                RHS->getValue().isNonNegative() &&
12632                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12633         S.Diag(ExprLoc, diag::warn_left_shift_always)
12634             << (Result.Val.getInt() != 0);
12635       else if (E->getType()->isSignedIntegerType())
12636         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12637     }
12638   }
12639 
12640   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12641     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12642     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12643     if (!LHS || !RHS)
12644       return;
12645     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12646         (RHS->getValue() == 0 || RHS->getValue() == 1))
12647       // Do not diagnose common idioms.
12648       return;
12649     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12650       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12651   }
12652 }
12653 
12654 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12655                                     SourceLocation CC,
12656                                     bool *ICContext = nullptr,
12657                                     bool IsListInit = false) {
12658   if (E->isTypeDependent() || E->isValueDependent()) return;
12659 
12660   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12661   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12662   if (Source == Target) return;
12663   if (Target->isDependentType()) return;
12664 
12665   // If the conversion context location is invalid don't complain. We also
12666   // don't want to emit a warning if the issue occurs from the expansion of
12667   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12668   // delay this check as long as possible. Once we detect we are in that
12669   // scenario, we just return.
12670   if (CC.isInvalid())
12671     return;
12672 
12673   if (Source->isAtomicType())
12674     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12675 
12676   // Diagnose implicit casts to bool.
12677   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12678     if (isa<StringLiteral>(E))
12679       // Warn on string literal to bool.  Checks for string literals in logical
12680       // and expressions, for instance, assert(0 && "error here"), are
12681       // prevented by a check in AnalyzeImplicitConversions().
12682       return DiagnoseImpCast(S, E, T, CC,
12683                              diag::warn_impcast_string_literal_to_bool);
12684     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12685         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12686       // This covers the literal expressions that evaluate to Objective-C
12687       // objects.
12688       return DiagnoseImpCast(S, E, T, CC,
12689                              diag::warn_impcast_objective_c_literal_to_bool);
12690     }
12691     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12692       // Warn on pointer to bool conversion that is always true.
12693       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12694                                      SourceRange(CC));
12695     }
12696   }
12697 
12698   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12699   // is a typedef for signed char (macOS), then that constant value has to be 1
12700   // or 0.
12701   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12702     Expr::EvalResult Result;
12703     if (E->EvaluateAsInt(Result, S.getASTContext(),
12704                          Expr::SE_AllowSideEffects)) {
12705       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12706         adornObjCBoolConversionDiagWithTernaryFixit(
12707             S, E,
12708             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12709                 << toString(Result.Val.getInt(), 10));
12710       }
12711       return;
12712     }
12713   }
12714 
12715   // Check implicit casts from Objective-C collection literals to specialized
12716   // collection types, e.g., NSArray<NSString *> *.
12717   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12718     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12719   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12720     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12721 
12722   // Strip vector types.
12723   if (isa<VectorType>(Source)) {
12724     if (Target->isVLSTBuiltinType() &&
12725         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12726                                          QualType(Source, 0)) ||
12727          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12728                                             QualType(Source, 0))))
12729       return;
12730 
12731     if (!isa<VectorType>(Target)) {
12732       if (S.SourceMgr.isInSystemMacro(CC))
12733         return;
12734       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12735     }
12736 
12737     // If the vector cast is cast between two vectors of the same size, it is
12738     // a bitcast, not a conversion.
12739     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12740       return;
12741 
12742     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12743     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12744   }
12745   if (auto VecTy = dyn_cast<VectorType>(Target))
12746     Target = VecTy->getElementType().getTypePtr();
12747 
12748   // Strip complex types.
12749   if (isa<ComplexType>(Source)) {
12750     if (!isa<ComplexType>(Target)) {
12751       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12752         return;
12753 
12754       return DiagnoseImpCast(S, E, T, CC,
12755                              S.getLangOpts().CPlusPlus
12756                                  ? diag::err_impcast_complex_scalar
12757                                  : diag::warn_impcast_complex_scalar);
12758     }
12759 
12760     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12761     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12762   }
12763 
12764   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12765   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12766 
12767   // If the source is floating point...
12768   if (SourceBT && SourceBT->isFloatingPoint()) {
12769     // ...and the target is floating point...
12770     if (TargetBT && TargetBT->isFloatingPoint()) {
12771       // ...then warn if we're dropping FP rank.
12772 
12773       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12774           QualType(SourceBT, 0), QualType(TargetBT, 0));
12775       if (Order > 0) {
12776         // Don't warn about float constants that are precisely
12777         // representable in the target type.
12778         Expr::EvalResult result;
12779         if (E->EvaluateAsRValue(result, S.Context)) {
12780           // Value might be a float, a float vector, or a float complex.
12781           if (IsSameFloatAfterCast(result.Val,
12782                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12783                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12784             return;
12785         }
12786 
12787         if (S.SourceMgr.isInSystemMacro(CC))
12788           return;
12789 
12790         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12791       }
12792       // ... or possibly if we're increasing rank, too
12793       else if (Order < 0) {
12794         if (S.SourceMgr.isInSystemMacro(CC))
12795           return;
12796 
12797         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12798       }
12799       return;
12800     }
12801 
12802     // If the target is integral, always warn.
12803     if (TargetBT && TargetBT->isInteger()) {
12804       if (S.SourceMgr.isInSystemMacro(CC))
12805         return;
12806 
12807       DiagnoseFloatingImpCast(S, E, T, CC);
12808     }
12809 
12810     // Detect the case where a call result is converted from floating-point to
12811     // to bool, and the final argument to the call is converted from bool, to
12812     // discover this typo:
12813     //
12814     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12815     //
12816     // FIXME: This is an incredibly special case; is there some more general
12817     // way to detect this class of misplaced-parentheses bug?
12818     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12819       // Check last argument of function call to see if it is an
12820       // implicit cast from a type matching the type the result
12821       // is being cast to.
12822       CallExpr *CEx = cast<CallExpr>(E);
12823       if (unsigned NumArgs = CEx->getNumArgs()) {
12824         Expr *LastA = CEx->getArg(NumArgs - 1);
12825         Expr *InnerE = LastA->IgnoreParenImpCasts();
12826         if (isa<ImplicitCastExpr>(LastA) &&
12827             InnerE->getType()->isBooleanType()) {
12828           // Warn on this floating-point to bool conversion
12829           DiagnoseImpCast(S, E, T, CC,
12830                           diag::warn_impcast_floating_point_to_bool);
12831         }
12832       }
12833     }
12834     return;
12835   }
12836 
12837   // Valid casts involving fixed point types should be accounted for here.
12838   if (Source->isFixedPointType()) {
12839     if (Target->isUnsaturatedFixedPointType()) {
12840       Expr::EvalResult Result;
12841       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12842                                   S.isConstantEvaluated())) {
12843         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12844         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12845         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12846         if (Value > MaxVal || Value < MinVal) {
12847           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12848                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12849                                     << Value.toString() << T
12850                                     << E->getSourceRange()
12851                                     << clang::SourceRange(CC));
12852           return;
12853         }
12854       }
12855     } else if (Target->isIntegerType()) {
12856       Expr::EvalResult Result;
12857       if (!S.isConstantEvaluated() &&
12858           E->EvaluateAsFixedPoint(Result, S.Context,
12859                                   Expr::SE_AllowSideEffects)) {
12860         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12861 
12862         bool Overflowed;
12863         llvm::APSInt IntResult = FXResult.convertToInt(
12864             S.Context.getIntWidth(T),
12865             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12866 
12867         if (Overflowed) {
12868           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12869                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12870                                     << FXResult.toString() << T
12871                                     << E->getSourceRange()
12872                                     << clang::SourceRange(CC));
12873           return;
12874         }
12875       }
12876     }
12877   } else if (Target->isUnsaturatedFixedPointType()) {
12878     if (Source->isIntegerType()) {
12879       Expr::EvalResult Result;
12880       if (!S.isConstantEvaluated() &&
12881           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12882         llvm::APSInt Value = Result.Val.getInt();
12883 
12884         bool Overflowed;
12885         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12886             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12887 
12888         if (Overflowed) {
12889           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12890                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12891                                     << toString(Value, /*Radix=*/10) << T
12892                                     << E->getSourceRange()
12893                                     << clang::SourceRange(CC));
12894           return;
12895         }
12896       }
12897     }
12898   }
12899 
12900   // If we are casting an integer type to a floating point type without
12901   // initialization-list syntax, we might lose accuracy if the floating
12902   // point type has a narrower significand than the integer type.
12903   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12904       TargetBT->isFloatingType() && !IsListInit) {
12905     // Determine the number of precision bits in the source integer type.
12906     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12907                                         /*Approximate*/ true);
12908     unsigned int SourcePrecision = SourceRange.Width;
12909 
12910     // Determine the number of precision bits in the
12911     // target floating point type.
12912     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12913         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12914 
12915     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12916         SourcePrecision > TargetPrecision) {
12917 
12918       if (Optional<llvm::APSInt> SourceInt =
12919               E->getIntegerConstantExpr(S.Context)) {
12920         // If the source integer is a constant, convert it to the target
12921         // floating point type. Issue a warning if the value changes
12922         // during the whole conversion.
12923         llvm::APFloat TargetFloatValue(
12924             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12925         llvm::APFloat::opStatus ConversionStatus =
12926             TargetFloatValue.convertFromAPInt(
12927                 *SourceInt, SourceBT->isSignedInteger(),
12928                 llvm::APFloat::rmNearestTiesToEven);
12929 
12930         if (ConversionStatus != llvm::APFloat::opOK) {
12931           SmallString<32> PrettySourceValue;
12932           SourceInt->toString(PrettySourceValue, 10);
12933           SmallString<32> PrettyTargetValue;
12934           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12935 
12936           S.DiagRuntimeBehavior(
12937               E->getExprLoc(), E,
12938               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12939                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12940                   << E->getSourceRange() << clang::SourceRange(CC));
12941         }
12942       } else {
12943         // Otherwise, the implicit conversion may lose precision.
12944         DiagnoseImpCast(S, E, T, CC,
12945                         diag::warn_impcast_integer_float_precision);
12946       }
12947     }
12948   }
12949 
12950   DiagnoseNullConversion(S, E, T, CC);
12951 
12952   S.DiscardMisalignedMemberAddress(Target, E);
12953 
12954   if (Target->isBooleanType())
12955     DiagnoseIntInBoolContext(S, E);
12956 
12957   if (!Source->isIntegerType() || !Target->isIntegerType())
12958     return;
12959 
12960   // TODO: remove this early return once the false positives for constant->bool
12961   // in templates, macros, etc, are reduced or removed.
12962   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12963     return;
12964 
12965   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12966       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12967     return adornObjCBoolConversionDiagWithTernaryFixit(
12968         S, E,
12969         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12970             << E->getType());
12971   }
12972 
12973   IntRange SourceTypeRange =
12974       IntRange::forTargetOfCanonicalType(S.Context, Source);
12975   IntRange LikelySourceRange =
12976       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12977   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12978 
12979   if (LikelySourceRange.Width > TargetRange.Width) {
12980     // If the source is a constant, use a default-on diagnostic.
12981     // TODO: this should happen for bitfield stores, too.
12982     Expr::EvalResult Result;
12983     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12984                          S.isConstantEvaluated())) {
12985       llvm::APSInt Value(32);
12986       Value = Result.Val.getInt();
12987 
12988       if (S.SourceMgr.isInSystemMacro(CC))
12989         return;
12990 
12991       std::string PrettySourceValue = toString(Value, 10);
12992       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12993 
12994       S.DiagRuntimeBehavior(
12995           E->getExprLoc(), E,
12996           S.PDiag(diag::warn_impcast_integer_precision_constant)
12997               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12998               << E->getSourceRange() << SourceRange(CC));
12999       return;
13000     }
13001 
13002     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13003     if (S.SourceMgr.isInSystemMacro(CC))
13004       return;
13005 
13006     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13007       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13008                              /* pruneControlFlow */ true);
13009     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13010   }
13011 
13012   if (TargetRange.Width > SourceTypeRange.Width) {
13013     if (auto *UO = dyn_cast<UnaryOperator>(E))
13014       if (UO->getOpcode() == UO_Minus)
13015         if (Source->isUnsignedIntegerType()) {
13016           if (Target->isUnsignedIntegerType())
13017             return DiagnoseImpCast(S, E, T, CC,
13018                                    diag::warn_impcast_high_order_zero_bits);
13019           if (Target->isSignedIntegerType())
13020             return DiagnoseImpCast(S, E, T, CC,
13021                                    diag::warn_impcast_nonnegative_result);
13022         }
13023   }
13024 
13025   if (TargetRange.Width == LikelySourceRange.Width &&
13026       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13027       Source->isSignedIntegerType()) {
13028     // Warn when doing a signed to signed conversion, warn if the positive
13029     // source value is exactly the width of the target type, which will
13030     // cause a negative value to be stored.
13031 
13032     Expr::EvalResult Result;
13033     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13034         !S.SourceMgr.isInSystemMacro(CC)) {
13035       llvm::APSInt Value = Result.Val.getInt();
13036       if (isSameWidthConstantConversion(S, E, T, CC)) {
13037         std::string PrettySourceValue = toString(Value, 10);
13038         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13039 
13040         S.DiagRuntimeBehavior(
13041             E->getExprLoc(), E,
13042             S.PDiag(diag::warn_impcast_integer_precision_constant)
13043                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13044                 << E->getSourceRange() << SourceRange(CC));
13045         return;
13046       }
13047     }
13048 
13049     // Fall through for non-constants to give a sign conversion warning.
13050   }
13051 
13052   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13053       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13054        LikelySourceRange.Width == TargetRange.Width)) {
13055     if (S.SourceMgr.isInSystemMacro(CC))
13056       return;
13057 
13058     unsigned DiagID = diag::warn_impcast_integer_sign;
13059 
13060     // Traditionally, gcc has warned about this under -Wsign-compare.
13061     // We also want to warn about it in -Wconversion.
13062     // So if -Wconversion is off, use a completely identical diagnostic
13063     // in the sign-compare group.
13064     // The conditional-checking code will
13065     if (ICContext) {
13066       DiagID = diag::warn_impcast_integer_sign_conditional;
13067       *ICContext = true;
13068     }
13069 
13070     return DiagnoseImpCast(S, E, T, CC, DiagID);
13071   }
13072 
13073   // Diagnose conversions between different enumeration types.
13074   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13075   // type, to give us better diagnostics.
13076   QualType SourceType = E->getType();
13077   if (!S.getLangOpts().CPlusPlus) {
13078     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13079       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13080         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13081         SourceType = S.Context.getTypeDeclType(Enum);
13082         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13083       }
13084   }
13085 
13086   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13087     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13088       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13089           TargetEnum->getDecl()->hasNameForLinkage() &&
13090           SourceEnum != TargetEnum) {
13091         if (S.SourceMgr.isInSystemMacro(CC))
13092           return;
13093 
13094         return DiagnoseImpCast(S, E, SourceType, T, CC,
13095                                diag::warn_impcast_different_enum_types);
13096       }
13097 }
13098 
13099 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13100                                      SourceLocation CC, QualType T);
13101 
13102 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13103                                     SourceLocation CC, bool &ICContext) {
13104   E = E->IgnoreParenImpCasts();
13105 
13106   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13107     return CheckConditionalOperator(S, CO, CC, T);
13108 
13109   AnalyzeImplicitConversions(S, E, CC);
13110   if (E->getType() != T)
13111     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13112 }
13113 
13114 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13115                                      SourceLocation CC, QualType T) {
13116   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13117 
13118   Expr *TrueExpr = E->getTrueExpr();
13119   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13120     TrueExpr = BCO->getCommon();
13121 
13122   bool Suspicious = false;
13123   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13124   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13125 
13126   if (T->isBooleanType())
13127     DiagnoseIntInBoolContext(S, E);
13128 
13129   // If -Wconversion would have warned about either of the candidates
13130   // for a signedness conversion to the context type...
13131   if (!Suspicious) return;
13132 
13133   // ...but it's currently ignored...
13134   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13135     return;
13136 
13137   // ...then check whether it would have warned about either of the
13138   // candidates for a signedness conversion to the condition type.
13139   if (E->getType() == T) return;
13140 
13141   Suspicious = false;
13142   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13143                           E->getType(), CC, &Suspicious);
13144   if (!Suspicious)
13145     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13146                             E->getType(), CC, &Suspicious);
13147 }
13148 
13149 /// Check conversion of given expression to boolean.
13150 /// Input argument E is a logical expression.
13151 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13152   if (S.getLangOpts().Bool)
13153     return;
13154   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13155     return;
13156   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13157 }
13158 
13159 namespace {
13160 struct AnalyzeImplicitConversionsWorkItem {
13161   Expr *E;
13162   SourceLocation CC;
13163   bool IsListInit;
13164 };
13165 }
13166 
13167 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13168 /// that should be visited are added to WorkList.
13169 static void AnalyzeImplicitConversions(
13170     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13171     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13172   Expr *OrigE = Item.E;
13173   SourceLocation CC = Item.CC;
13174 
13175   QualType T = OrigE->getType();
13176   Expr *E = OrigE->IgnoreParenImpCasts();
13177 
13178   // Propagate whether we are in a C++ list initialization expression.
13179   // If so, we do not issue warnings for implicit int-float conversion
13180   // precision loss, because C++11 narrowing already handles it.
13181   bool IsListInit = Item.IsListInit ||
13182                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13183 
13184   if (E->isTypeDependent() || E->isValueDependent())
13185     return;
13186 
13187   Expr *SourceExpr = E;
13188   // Examine, but don't traverse into the source expression of an
13189   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13190   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13191   // evaluate it in the context of checking the specific conversion to T though.
13192   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13193     if (auto *Src = OVE->getSourceExpr())
13194       SourceExpr = Src;
13195 
13196   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13197     if (UO->getOpcode() == UO_Not &&
13198         UO->getSubExpr()->isKnownToHaveBooleanValue())
13199       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13200           << OrigE->getSourceRange() << T->isBooleanType()
13201           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13202 
13203   // For conditional operators, we analyze the arguments as if they
13204   // were being fed directly into the output.
13205   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13206     CheckConditionalOperator(S, CO, CC, T);
13207     return;
13208   }
13209 
13210   // Check implicit argument conversions for function calls.
13211   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13212     CheckImplicitArgumentConversions(S, Call, CC);
13213 
13214   // Go ahead and check any implicit conversions we might have skipped.
13215   // The non-canonical typecheck is just an optimization;
13216   // CheckImplicitConversion will filter out dead implicit conversions.
13217   if (SourceExpr->getType() != T)
13218     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13219 
13220   // Now continue drilling into this expression.
13221 
13222   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13223     // The bound subexpressions in a PseudoObjectExpr are not reachable
13224     // as transitive children.
13225     // FIXME: Use a more uniform representation for this.
13226     for (auto *SE : POE->semantics())
13227       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13228         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13229   }
13230 
13231   // Skip past explicit casts.
13232   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13233     E = CE->getSubExpr()->IgnoreParenImpCasts();
13234     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13235       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13236     WorkList.push_back({E, CC, IsListInit});
13237     return;
13238   }
13239 
13240   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13241     // Do a somewhat different check with comparison operators.
13242     if (BO->isComparisonOp())
13243       return AnalyzeComparison(S, BO);
13244 
13245     // And with simple assignments.
13246     if (BO->getOpcode() == BO_Assign)
13247       return AnalyzeAssignment(S, BO);
13248     // And with compound assignments.
13249     if (BO->isAssignmentOp())
13250       return AnalyzeCompoundAssignment(S, BO);
13251   }
13252 
13253   // These break the otherwise-useful invariant below.  Fortunately,
13254   // we don't really need to recurse into them, because any internal
13255   // expressions should have been analyzed already when they were
13256   // built into statements.
13257   if (isa<StmtExpr>(E)) return;
13258 
13259   // Don't descend into unevaluated contexts.
13260   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13261 
13262   // Now just recurse over the expression's children.
13263   CC = E->getExprLoc();
13264   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13265   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13266   for (Stmt *SubStmt : E->children()) {
13267     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13268     if (!ChildExpr)
13269       continue;
13270 
13271     if (IsLogicalAndOperator &&
13272         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13273       // Ignore checking string literals that are in logical and operators.
13274       // This is a common pattern for asserts.
13275       continue;
13276     WorkList.push_back({ChildExpr, CC, IsListInit});
13277   }
13278 
13279   if (BO && BO->isLogicalOp()) {
13280     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13281     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13282       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13283 
13284     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13285     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13286       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13287   }
13288 
13289   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13290     if (U->getOpcode() == UO_LNot) {
13291       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13292     } else if (U->getOpcode() != UO_AddrOf) {
13293       if (U->getSubExpr()->getType()->isAtomicType())
13294         S.Diag(U->getSubExpr()->getBeginLoc(),
13295                diag::warn_atomic_implicit_seq_cst);
13296     }
13297   }
13298 }
13299 
13300 /// AnalyzeImplicitConversions - Find and report any interesting
13301 /// implicit conversions in the given expression.  There are a couple
13302 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13303 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13304                                        bool IsListInit/*= false*/) {
13305   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13306   WorkList.push_back({OrigE, CC, IsListInit});
13307   while (!WorkList.empty())
13308     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13309 }
13310 
13311 /// Diagnose integer type and any valid implicit conversion to it.
13312 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13313   // Taking into account implicit conversions,
13314   // allow any integer.
13315   if (!E->getType()->isIntegerType()) {
13316     S.Diag(E->getBeginLoc(),
13317            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13318     return true;
13319   }
13320   // Potentially emit standard warnings for implicit conversions if enabled
13321   // using -Wconversion.
13322   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13323   return false;
13324 }
13325 
13326 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13327 // Returns true when emitting a warning about taking the address of a reference.
13328 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13329                               const PartialDiagnostic &PD) {
13330   E = E->IgnoreParenImpCasts();
13331 
13332   const FunctionDecl *FD = nullptr;
13333 
13334   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13335     if (!DRE->getDecl()->getType()->isReferenceType())
13336       return false;
13337   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13338     if (!M->getMemberDecl()->getType()->isReferenceType())
13339       return false;
13340   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13341     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13342       return false;
13343     FD = Call->getDirectCallee();
13344   } else {
13345     return false;
13346   }
13347 
13348   SemaRef.Diag(E->getExprLoc(), PD);
13349 
13350   // If possible, point to location of function.
13351   if (FD) {
13352     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13353   }
13354 
13355   return true;
13356 }
13357 
13358 // Returns true if the SourceLocation is expanded from any macro body.
13359 // Returns false if the SourceLocation is invalid, is from not in a macro
13360 // expansion, or is from expanded from a top-level macro argument.
13361 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13362   if (Loc.isInvalid())
13363     return false;
13364 
13365   while (Loc.isMacroID()) {
13366     if (SM.isMacroBodyExpansion(Loc))
13367       return true;
13368     Loc = SM.getImmediateMacroCallerLoc(Loc);
13369   }
13370 
13371   return false;
13372 }
13373 
13374 /// Diagnose pointers that are always non-null.
13375 /// \param E the expression containing the pointer
13376 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13377 /// compared to a null pointer
13378 /// \param IsEqual True when the comparison is equal to a null pointer
13379 /// \param Range Extra SourceRange to highlight in the diagnostic
13380 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13381                                         Expr::NullPointerConstantKind NullKind,
13382                                         bool IsEqual, SourceRange Range) {
13383   if (!E)
13384     return;
13385 
13386   // Don't warn inside macros.
13387   if (E->getExprLoc().isMacroID()) {
13388     const SourceManager &SM = getSourceManager();
13389     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13390         IsInAnyMacroBody(SM, Range.getBegin()))
13391       return;
13392   }
13393   E = E->IgnoreImpCasts();
13394 
13395   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13396 
13397   if (isa<CXXThisExpr>(E)) {
13398     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13399                                 : diag::warn_this_bool_conversion;
13400     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13401     return;
13402   }
13403 
13404   bool IsAddressOf = false;
13405 
13406   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13407     if (UO->getOpcode() != UO_AddrOf)
13408       return;
13409     IsAddressOf = true;
13410     E = UO->getSubExpr();
13411   }
13412 
13413   if (IsAddressOf) {
13414     unsigned DiagID = IsCompare
13415                           ? diag::warn_address_of_reference_null_compare
13416                           : diag::warn_address_of_reference_bool_conversion;
13417     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13418                                          << IsEqual;
13419     if (CheckForReference(*this, E, PD)) {
13420       return;
13421     }
13422   }
13423 
13424   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13425     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13426     std::string Str;
13427     llvm::raw_string_ostream S(Str);
13428     E->printPretty(S, nullptr, getPrintingPolicy());
13429     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13430                                 : diag::warn_cast_nonnull_to_bool;
13431     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13432       << E->getSourceRange() << Range << IsEqual;
13433     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13434   };
13435 
13436   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13437   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13438     if (auto *Callee = Call->getDirectCallee()) {
13439       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13440         ComplainAboutNonnullParamOrCall(A);
13441         return;
13442       }
13443     }
13444   }
13445 
13446   // Expect to find a single Decl.  Skip anything more complicated.
13447   ValueDecl *D = nullptr;
13448   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13449     D = R->getDecl();
13450   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13451     D = M->getMemberDecl();
13452   }
13453 
13454   // Weak Decls can be null.
13455   if (!D || D->isWeak())
13456     return;
13457 
13458   // Check for parameter decl with nonnull attribute
13459   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13460     if (getCurFunction() &&
13461         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13462       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13463         ComplainAboutNonnullParamOrCall(A);
13464         return;
13465       }
13466 
13467       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13468         // Skip function template not specialized yet.
13469         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13470           return;
13471         auto ParamIter = llvm::find(FD->parameters(), PV);
13472         assert(ParamIter != FD->param_end());
13473         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13474 
13475         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13476           if (!NonNull->args_size()) {
13477               ComplainAboutNonnullParamOrCall(NonNull);
13478               return;
13479           }
13480 
13481           for (const ParamIdx &ArgNo : NonNull->args()) {
13482             if (ArgNo.getASTIndex() == ParamNo) {
13483               ComplainAboutNonnullParamOrCall(NonNull);
13484               return;
13485             }
13486           }
13487         }
13488       }
13489     }
13490   }
13491 
13492   QualType T = D->getType();
13493   const bool IsArray = T->isArrayType();
13494   const bool IsFunction = T->isFunctionType();
13495 
13496   // Address of function is used to silence the function warning.
13497   if (IsAddressOf && IsFunction) {
13498     return;
13499   }
13500 
13501   // Found nothing.
13502   if (!IsAddressOf && !IsFunction && !IsArray)
13503     return;
13504 
13505   // Pretty print the expression for the diagnostic.
13506   std::string Str;
13507   llvm::raw_string_ostream S(Str);
13508   E->printPretty(S, nullptr, getPrintingPolicy());
13509 
13510   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13511                               : diag::warn_impcast_pointer_to_bool;
13512   enum {
13513     AddressOf,
13514     FunctionPointer,
13515     ArrayPointer
13516   } DiagType;
13517   if (IsAddressOf)
13518     DiagType = AddressOf;
13519   else if (IsFunction)
13520     DiagType = FunctionPointer;
13521   else if (IsArray)
13522     DiagType = ArrayPointer;
13523   else
13524     llvm_unreachable("Could not determine diagnostic.");
13525   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13526                                 << Range << IsEqual;
13527 
13528   if (!IsFunction)
13529     return;
13530 
13531   // Suggest '&' to silence the function warning.
13532   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13533       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13534 
13535   // Check to see if '()' fixit should be emitted.
13536   QualType ReturnType;
13537   UnresolvedSet<4> NonTemplateOverloads;
13538   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13539   if (ReturnType.isNull())
13540     return;
13541 
13542   if (IsCompare) {
13543     // There are two cases here.  If there is null constant, the only suggest
13544     // for a pointer return type.  If the null is 0, then suggest if the return
13545     // type is a pointer or an integer type.
13546     if (!ReturnType->isPointerType()) {
13547       if (NullKind == Expr::NPCK_ZeroExpression ||
13548           NullKind == Expr::NPCK_ZeroLiteral) {
13549         if (!ReturnType->isIntegerType())
13550           return;
13551       } else {
13552         return;
13553       }
13554     }
13555   } else { // !IsCompare
13556     // For function to bool, only suggest if the function pointer has bool
13557     // return type.
13558     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13559       return;
13560   }
13561   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13562       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13563 }
13564 
13565 /// Diagnoses "dangerous" implicit conversions within the given
13566 /// expression (which is a full expression).  Implements -Wconversion
13567 /// and -Wsign-compare.
13568 ///
13569 /// \param CC the "context" location of the implicit conversion, i.e.
13570 ///   the most location of the syntactic entity requiring the implicit
13571 ///   conversion
13572 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13573   // Don't diagnose in unevaluated contexts.
13574   if (isUnevaluatedContext())
13575     return;
13576 
13577   // Don't diagnose for value- or type-dependent expressions.
13578   if (E->isTypeDependent() || E->isValueDependent())
13579     return;
13580 
13581   // Check for array bounds violations in cases where the check isn't triggered
13582   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13583   // ArraySubscriptExpr is on the RHS of a variable initialization.
13584   CheckArrayAccess(E);
13585 
13586   // This is not the right CC for (e.g.) a variable initialization.
13587   AnalyzeImplicitConversions(*this, E, CC);
13588 }
13589 
13590 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13591 /// Input argument E is a logical expression.
13592 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13593   ::CheckBoolLikeConversion(*this, E, CC);
13594 }
13595 
13596 /// Diagnose when expression is an integer constant expression and its evaluation
13597 /// results in integer overflow
13598 void Sema::CheckForIntOverflow (Expr *E) {
13599   // Use a work list to deal with nested struct initializers.
13600   SmallVector<Expr *, 2> Exprs(1, E);
13601 
13602   do {
13603     Expr *OriginalE = Exprs.pop_back_val();
13604     Expr *E = OriginalE->IgnoreParenCasts();
13605 
13606     if (isa<BinaryOperator>(E)) {
13607       E->EvaluateForOverflow(Context);
13608       continue;
13609     }
13610 
13611     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13612       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13613     else if (isa<ObjCBoxedExpr>(OriginalE))
13614       E->EvaluateForOverflow(Context);
13615     else if (auto Call = dyn_cast<CallExpr>(E))
13616       Exprs.append(Call->arg_begin(), Call->arg_end());
13617     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13618       Exprs.append(Message->arg_begin(), Message->arg_end());
13619   } while (!Exprs.empty());
13620 }
13621 
13622 namespace {
13623 
13624 /// Visitor for expressions which looks for unsequenced operations on the
13625 /// same object.
13626 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13627   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13628 
13629   /// A tree of sequenced regions within an expression. Two regions are
13630   /// unsequenced if one is an ancestor or a descendent of the other. When we
13631   /// finish processing an expression with sequencing, such as a comma
13632   /// expression, we fold its tree nodes into its parent, since they are
13633   /// unsequenced with respect to nodes we will visit later.
13634   class SequenceTree {
13635     struct Value {
13636       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13637       unsigned Parent : 31;
13638       unsigned Merged : 1;
13639     };
13640     SmallVector<Value, 8> Values;
13641 
13642   public:
13643     /// A region within an expression which may be sequenced with respect
13644     /// to some other region.
13645     class Seq {
13646       friend class SequenceTree;
13647 
13648       unsigned Index;
13649 
13650       explicit Seq(unsigned N) : Index(N) {}
13651 
13652     public:
13653       Seq() : Index(0) {}
13654     };
13655 
13656     SequenceTree() { Values.push_back(Value(0)); }
13657     Seq root() const { return Seq(0); }
13658 
13659     /// Create a new sequence of operations, which is an unsequenced
13660     /// subset of \p Parent. This sequence of operations is sequenced with
13661     /// respect to other children of \p Parent.
13662     Seq allocate(Seq Parent) {
13663       Values.push_back(Value(Parent.Index));
13664       return Seq(Values.size() - 1);
13665     }
13666 
13667     /// Merge a sequence of operations into its parent.
13668     void merge(Seq S) {
13669       Values[S.Index].Merged = true;
13670     }
13671 
13672     /// Determine whether two operations are unsequenced. This operation
13673     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13674     /// should have been merged into its parent as appropriate.
13675     bool isUnsequenced(Seq Cur, Seq Old) {
13676       unsigned C = representative(Cur.Index);
13677       unsigned Target = representative(Old.Index);
13678       while (C >= Target) {
13679         if (C == Target)
13680           return true;
13681         C = Values[C].Parent;
13682       }
13683       return false;
13684     }
13685 
13686   private:
13687     /// Pick a representative for a sequence.
13688     unsigned representative(unsigned K) {
13689       if (Values[K].Merged)
13690         // Perform path compression as we go.
13691         return Values[K].Parent = representative(Values[K].Parent);
13692       return K;
13693     }
13694   };
13695 
13696   /// An object for which we can track unsequenced uses.
13697   using Object = const NamedDecl *;
13698 
13699   /// Different flavors of object usage which we track. We only track the
13700   /// least-sequenced usage of each kind.
13701   enum UsageKind {
13702     /// A read of an object. Multiple unsequenced reads are OK.
13703     UK_Use,
13704 
13705     /// A modification of an object which is sequenced before the value
13706     /// computation of the expression, such as ++n in C++.
13707     UK_ModAsValue,
13708 
13709     /// A modification of an object which is not sequenced before the value
13710     /// computation of the expression, such as n++.
13711     UK_ModAsSideEffect,
13712 
13713     UK_Count = UK_ModAsSideEffect + 1
13714   };
13715 
13716   /// Bundle together a sequencing region and the expression corresponding
13717   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13718   struct Usage {
13719     const Expr *UsageExpr;
13720     SequenceTree::Seq Seq;
13721 
13722     Usage() : UsageExpr(nullptr), Seq() {}
13723   };
13724 
13725   struct UsageInfo {
13726     Usage Uses[UK_Count];
13727 
13728     /// Have we issued a diagnostic for this object already?
13729     bool Diagnosed;
13730 
13731     UsageInfo() : Uses(), Diagnosed(false) {}
13732   };
13733   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13734 
13735   Sema &SemaRef;
13736 
13737   /// Sequenced regions within the expression.
13738   SequenceTree Tree;
13739 
13740   /// Declaration modifications and references which we have seen.
13741   UsageInfoMap UsageMap;
13742 
13743   /// The region we are currently within.
13744   SequenceTree::Seq Region;
13745 
13746   /// Filled in with declarations which were modified as a side-effect
13747   /// (that is, post-increment operations).
13748   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13749 
13750   /// Expressions to check later. We defer checking these to reduce
13751   /// stack usage.
13752   SmallVectorImpl<const Expr *> &WorkList;
13753 
13754   /// RAII object wrapping the visitation of a sequenced subexpression of an
13755   /// expression. At the end of this process, the side-effects of the evaluation
13756   /// become sequenced with respect to the value computation of the result, so
13757   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13758   /// UK_ModAsValue.
13759   struct SequencedSubexpression {
13760     SequencedSubexpression(SequenceChecker &Self)
13761       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13762       Self.ModAsSideEffect = &ModAsSideEffect;
13763     }
13764 
13765     ~SequencedSubexpression() {
13766       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13767         // Add a new usage with usage kind UK_ModAsValue, and then restore
13768         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13769         // the previous one was empty).
13770         UsageInfo &UI = Self.UsageMap[M.first];
13771         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13772         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13773         SideEffectUsage = M.second;
13774       }
13775       Self.ModAsSideEffect = OldModAsSideEffect;
13776     }
13777 
13778     SequenceChecker &Self;
13779     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13780     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13781   };
13782 
13783   /// RAII object wrapping the visitation of a subexpression which we might
13784   /// choose to evaluate as a constant. If any subexpression is evaluated and
13785   /// found to be non-constant, this allows us to suppress the evaluation of
13786   /// the outer expression.
13787   class EvaluationTracker {
13788   public:
13789     EvaluationTracker(SequenceChecker &Self)
13790         : Self(Self), Prev(Self.EvalTracker) {
13791       Self.EvalTracker = this;
13792     }
13793 
13794     ~EvaluationTracker() {
13795       Self.EvalTracker = Prev;
13796       if (Prev)
13797         Prev->EvalOK &= EvalOK;
13798     }
13799 
13800     bool evaluate(const Expr *E, bool &Result) {
13801       if (!EvalOK || E->isValueDependent())
13802         return false;
13803       EvalOK = E->EvaluateAsBooleanCondition(
13804           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13805       return EvalOK;
13806     }
13807 
13808   private:
13809     SequenceChecker &Self;
13810     EvaluationTracker *Prev;
13811     bool EvalOK = true;
13812   } *EvalTracker = nullptr;
13813 
13814   /// Find the object which is produced by the specified expression,
13815   /// if any.
13816   Object getObject(const Expr *E, bool Mod) const {
13817     E = E->IgnoreParenCasts();
13818     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13819       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13820         return getObject(UO->getSubExpr(), Mod);
13821     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13822       if (BO->getOpcode() == BO_Comma)
13823         return getObject(BO->getRHS(), Mod);
13824       if (Mod && BO->isAssignmentOp())
13825         return getObject(BO->getLHS(), Mod);
13826     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13827       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13828       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13829         return ME->getMemberDecl();
13830     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13831       // FIXME: If this is a reference, map through to its value.
13832       return DRE->getDecl();
13833     return nullptr;
13834   }
13835 
13836   /// Note that an object \p O was modified or used by an expression
13837   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13838   /// the object \p O as obtained via the \p UsageMap.
13839   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13840     // Get the old usage for the given object and usage kind.
13841     Usage &U = UI.Uses[UK];
13842     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13843       // If we have a modification as side effect and are in a sequenced
13844       // subexpression, save the old Usage so that we can restore it later
13845       // in SequencedSubexpression::~SequencedSubexpression.
13846       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13847         ModAsSideEffect->push_back(std::make_pair(O, U));
13848       // Then record the new usage with the current sequencing region.
13849       U.UsageExpr = UsageExpr;
13850       U.Seq = Region;
13851     }
13852   }
13853 
13854   /// Check whether a modification or use of an object \p O in an expression
13855   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13856   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13857   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13858   /// usage and false we are checking for a mod-use unsequenced usage.
13859   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13860                   UsageKind OtherKind, bool IsModMod) {
13861     if (UI.Diagnosed)
13862       return;
13863 
13864     const Usage &U = UI.Uses[OtherKind];
13865     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13866       return;
13867 
13868     const Expr *Mod = U.UsageExpr;
13869     const Expr *ModOrUse = UsageExpr;
13870     if (OtherKind == UK_Use)
13871       std::swap(Mod, ModOrUse);
13872 
13873     SemaRef.DiagRuntimeBehavior(
13874         Mod->getExprLoc(), {Mod, ModOrUse},
13875         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13876                                : diag::warn_unsequenced_mod_use)
13877             << O << SourceRange(ModOrUse->getExprLoc()));
13878     UI.Diagnosed = true;
13879   }
13880 
13881   // A note on note{Pre, Post}{Use, Mod}:
13882   //
13883   // (It helps to follow the algorithm with an expression such as
13884   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13885   //  operations before C++17 and both are well-defined in C++17).
13886   //
13887   // When visiting a node which uses/modify an object we first call notePreUse
13888   // or notePreMod before visiting its sub-expression(s). At this point the
13889   // children of the current node have not yet been visited and so the eventual
13890   // uses/modifications resulting from the children of the current node have not
13891   // been recorded yet.
13892   //
13893   // We then visit the children of the current node. After that notePostUse or
13894   // notePostMod is called. These will 1) detect an unsequenced modification
13895   // as side effect (as in "k++ + k") and 2) add a new usage with the
13896   // appropriate usage kind.
13897   //
13898   // We also have to be careful that some operation sequences modification as
13899   // side effect as well (for example: || or ,). To account for this we wrap
13900   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13901   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13902   // which record usages which are modifications as side effect, and then
13903   // downgrade them (or more accurately restore the previous usage which was a
13904   // modification as side effect) when exiting the scope of the sequenced
13905   // subexpression.
13906 
13907   void notePreUse(Object O, const Expr *UseExpr) {
13908     UsageInfo &UI = UsageMap[O];
13909     // Uses conflict with other modifications.
13910     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13911   }
13912 
13913   void notePostUse(Object O, const Expr *UseExpr) {
13914     UsageInfo &UI = UsageMap[O];
13915     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13916                /*IsModMod=*/false);
13917     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13918   }
13919 
13920   void notePreMod(Object O, const Expr *ModExpr) {
13921     UsageInfo &UI = UsageMap[O];
13922     // Modifications conflict with other modifications and with uses.
13923     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13924     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13925   }
13926 
13927   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13928     UsageInfo &UI = UsageMap[O];
13929     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13930                /*IsModMod=*/true);
13931     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13932   }
13933 
13934 public:
13935   SequenceChecker(Sema &S, const Expr *E,
13936                   SmallVectorImpl<const Expr *> &WorkList)
13937       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13938     Visit(E);
13939     // Silence a -Wunused-private-field since WorkList is now unused.
13940     // TODO: Evaluate if it can be used, and if not remove it.
13941     (void)this->WorkList;
13942   }
13943 
13944   void VisitStmt(const Stmt *S) {
13945     // Skip all statements which aren't expressions for now.
13946   }
13947 
13948   void VisitExpr(const Expr *E) {
13949     // By default, just recurse to evaluated subexpressions.
13950     Base::VisitStmt(E);
13951   }
13952 
13953   void VisitCastExpr(const CastExpr *E) {
13954     Object O = Object();
13955     if (E->getCastKind() == CK_LValueToRValue)
13956       O = getObject(E->getSubExpr(), false);
13957 
13958     if (O)
13959       notePreUse(O, E);
13960     VisitExpr(E);
13961     if (O)
13962       notePostUse(O, E);
13963   }
13964 
13965   void VisitSequencedExpressions(const Expr *SequencedBefore,
13966                                  const Expr *SequencedAfter) {
13967     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13968     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13969     SequenceTree::Seq OldRegion = Region;
13970 
13971     {
13972       SequencedSubexpression SeqBefore(*this);
13973       Region = BeforeRegion;
13974       Visit(SequencedBefore);
13975     }
13976 
13977     Region = AfterRegion;
13978     Visit(SequencedAfter);
13979 
13980     Region = OldRegion;
13981 
13982     Tree.merge(BeforeRegion);
13983     Tree.merge(AfterRegion);
13984   }
13985 
13986   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13987     // C++17 [expr.sub]p1:
13988     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13989     //   expression E1 is sequenced before the expression E2.
13990     if (SemaRef.getLangOpts().CPlusPlus17)
13991       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13992     else {
13993       Visit(ASE->getLHS());
13994       Visit(ASE->getRHS());
13995     }
13996   }
13997 
13998   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13999   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14000   void VisitBinPtrMem(const BinaryOperator *BO) {
14001     // C++17 [expr.mptr.oper]p4:
14002     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14003     //  the expression E1 is sequenced before the expression E2.
14004     if (SemaRef.getLangOpts().CPlusPlus17)
14005       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14006     else {
14007       Visit(BO->getLHS());
14008       Visit(BO->getRHS());
14009     }
14010   }
14011 
14012   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14013   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14014   void VisitBinShlShr(const BinaryOperator *BO) {
14015     // C++17 [expr.shift]p4:
14016     //  The expression E1 is sequenced before the expression E2.
14017     if (SemaRef.getLangOpts().CPlusPlus17)
14018       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14019     else {
14020       Visit(BO->getLHS());
14021       Visit(BO->getRHS());
14022     }
14023   }
14024 
14025   void VisitBinComma(const BinaryOperator *BO) {
14026     // C++11 [expr.comma]p1:
14027     //   Every value computation and side effect associated with the left
14028     //   expression is sequenced before every value computation and side
14029     //   effect associated with the right expression.
14030     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14031   }
14032 
14033   void VisitBinAssign(const BinaryOperator *BO) {
14034     SequenceTree::Seq RHSRegion;
14035     SequenceTree::Seq LHSRegion;
14036     if (SemaRef.getLangOpts().CPlusPlus17) {
14037       RHSRegion = Tree.allocate(Region);
14038       LHSRegion = Tree.allocate(Region);
14039     } else {
14040       RHSRegion = Region;
14041       LHSRegion = Region;
14042     }
14043     SequenceTree::Seq OldRegion = Region;
14044 
14045     // C++11 [expr.ass]p1:
14046     //  [...] the assignment is sequenced after the value computation
14047     //  of the right and left operands, [...]
14048     //
14049     // so check it before inspecting the operands and update the
14050     // map afterwards.
14051     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14052     if (O)
14053       notePreMod(O, BO);
14054 
14055     if (SemaRef.getLangOpts().CPlusPlus17) {
14056       // C++17 [expr.ass]p1:
14057       //  [...] The right operand is sequenced before the left operand. [...]
14058       {
14059         SequencedSubexpression SeqBefore(*this);
14060         Region = RHSRegion;
14061         Visit(BO->getRHS());
14062       }
14063 
14064       Region = LHSRegion;
14065       Visit(BO->getLHS());
14066 
14067       if (O && isa<CompoundAssignOperator>(BO))
14068         notePostUse(O, BO);
14069 
14070     } else {
14071       // C++11 does not specify any sequencing between the LHS and RHS.
14072       Region = LHSRegion;
14073       Visit(BO->getLHS());
14074 
14075       if (O && isa<CompoundAssignOperator>(BO))
14076         notePostUse(O, BO);
14077 
14078       Region = RHSRegion;
14079       Visit(BO->getRHS());
14080     }
14081 
14082     // C++11 [expr.ass]p1:
14083     //  the assignment is sequenced [...] before the value computation of the
14084     //  assignment expression.
14085     // C11 6.5.16/3 has no such rule.
14086     Region = OldRegion;
14087     if (O)
14088       notePostMod(O, BO,
14089                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14090                                                   : UK_ModAsSideEffect);
14091     if (SemaRef.getLangOpts().CPlusPlus17) {
14092       Tree.merge(RHSRegion);
14093       Tree.merge(LHSRegion);
14094     }
14095   }
14096 
14097   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14098     VisitBinAssign(CAO);
14099   }
14100 
14101   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14102   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14103   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14104     Object O = getObject(UO->getSubExpr(), true);
14105     if (!O)
14106       return VisitExpr(UO);
14107 
14108     notePreMod(O, UO);
14109     Visit(UO->getSubExpr());
14110     // C++11 [expr.pre.incr]p1:
14111     //   the expression ++x is equivalent to x+=1
14112     notePostMod(O, UO,
14113                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14114                                                 : UK_ModAsSideEffect);
14115   }
14116 
14117   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14118   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14119   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14120     Object O = getObject(UO->getSubExpr(), true);
14121     if (!O)
14122       return VisitExpr(UO);
14123 
14124     notePreMod(O, UO);
14125     Visit(UO->getSubExpr());
14126     notePostMod(O, UO, UK_ModAsSideEffect);
14127   }
14128 
14129   void VisitBinLOr(const BinaryOperator *BO) {
14130     // C++11 [expr.log.or]p2:
14131     //  If the second expression is evaluated, every value computation and
14132     //  side effect associated with the first expression is sequenced before
14133     //  every value computation and side effect associated with the
14134     //  second expression.
14135     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14136     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14137     SequenceTree::Seq OldRegion = Region;
14138 
14139     EvaluationTracker Eval(*this);
14140     {
14141       SequencedSubexpression Sequenced(*this);
14142       Region = LHSRegion;
14143       Visit(BO->getLHS());
14144     }
14145 
14146     // C++11 [expr.log.or]p1:
14147     //  [...] the second operand is not evaluated if the first operand
14148     //  evaluates to true.
14149     bool EvalResult = false;
14150     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14151     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14152     if (ShouldVisitRHS) {
14153       Region = RHSRegion;
14154       Visit(BO->getRHS());
14155     }
14156 
14157     Region = OldRegion;
14158     Tree.merge(LHSRegion);
14159     Tree.merge(RHSRegion);
14160   }
14161 
14162   void VisitBinLAnd(const BinaryOperator *BO) {
14163     // C++11 [expr.log.and]p2:
14164     //  If the second expression is evaluated, every value computation and
14165     //  side effect associated with the first expression is sequenced before
14166     //  every value computation and side effect associated with the
14167     //  second expression.
14168     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14169     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14170     SequenceTree::Seq OldRegion = Region;
14171 
14172     EvaluationTracker Eval(*this);
14173     {
14174       SequencedSubexpression Sequenced(*this);
14175       Region = LHSRegion;
14176       Visit(BO->getLHS());
14177     }
14178 
14179     // C++11 [expr.log.and]p1:
14180     //  [...] the second operand is not evaluated if the first operand is false.
14181     bool EvalResult = false;
14182     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14183     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14184     if (ShouldVisitRHS) {
14185       Region = RHSRegion;
14186       Visit(BO->getRHS());
14187     }
14188 
14189     Region = OldRegion;
14190     Tree.merge(LHSRegion);
14191     Tree.merge(RHSRegion);
14192   }
14193 
14194   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14195     // C++11 [expr.cond]p1:
14196     //  [...] Every value computation and side effect associated with the first
14197     //  expression is sequenced before every value computation and side effect
14198     //  associated with the second or third expression.
14199     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14200 
14201     // No sequencing is specified between the true and false expression.
14202     // However since exactly one of both is going to be evaluated we can
14203     // consider them to be sequenced. This is needed to avoid warning on
14204     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14205     // both the true and false expressions because we can't evaluate x.
14206     // This will still allow us to detect an expression like (pre C++17)
14207     // "(x ? y += 1 : y += 2) = y".
14208     //
14209     // We don't wrap the visitation of the true and false expression with
14210     // SequencedSubexpression because we don't want to downgrade modifications
14211     // as side effect in the true and false expressions after the visition
14212     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14213     // not warn between the two "y++", but we should warn between the "y++"
14214     // and the "y".
14215     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14216     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14217     SequenceTree::Seq OldRegion = Region;
14218 
14219     EvaluationTracker Eval(*this);
14220     {
14221       SequencedSubexpression Sequenced(*this);
14222       Region = ConditionRegion;
14223       Visit(CO->getCond());
14224     }
14225 
14226     // C++11 [expr.cond]p1:
14227     // [...] The first expression is contextually converted to bool (Clause 4).
14228     // It is evaluated and if it is true, the result of the conditional
14229     // expression is the value of the second expression, otherwise that of the
14230     // third expression. Only one of the second and third expressions is
14231     // evaluated. [...]
14232     bool EvalResult = false;
14233     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14234     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14235     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14236     if (ShouldVisitTrueExpr) {
14237       Region = TrueRegion;
14238       Visit(CO->getTrueExpr());
14239     }
14240     if (ShouldVisitFalseExpr) {
14241       Region = FalseRegion;
14242       Visit(CO->getFalseExpr());
14243     }
14244 
14245     Region = OldRegion;
14246     Tree.merge(ConditionRegion);
14247     Tree.merge(TrueRegion);
14248     Tree.merge(FalseRegion);
14249   }
14250 
14251   void VisitCallExpr(const CallExpr *CE) {
14252     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14253 
14254     if (CE->isUnevaluatedBuiltinCall(Context))
14255       return;
14256 
14257     // C++11 [intro.execution]p15:
14258     //   When calling a function [...], every value computation and side effect
14259     //   associated with any argument expression, or with the postfix expression
14260     //   designating the called function, is sequenced before execution of every
14261     //   expression or statement in the body of the function [and thus before
14262     //   the value computation of its result].
14263     SequencedSubexpression Sequenced(*this);
14264     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14265       // C++17 [expr.call]p5
14266       //   The postfix-expression is sequenced before each expression in the
14267       //   expression-list and any default argument. [...]
14268       SequenceTree::Seq CalleeRegion;
14269       SequenceTree::Seq OtherRegion;
14270       if (SemaRef.getLangOpts().CPlusPlus17) {
14271         CalleeRegion = Tree.allocate(Region);
14272         OtherRegion = Tree.allocate(Region);
14273       } else {
14274         CalleeRegion = Region;
14275         OtherRegion = Region;
14276       }
14277       SequenceTree::Seq OldRegion = Region;
14278 
14279       // Visit the callee expression first.
14280       Region = CalleeRegion;
14281       if (SemaRef.getLangOpts().CPlusPlus17) {
14282         SequencedSubexpression Sequenced(*this);
14283         Visit(CE->getCallee());
14284       } else {
14285         Visit(CE->getCallee());
14286       }
14287 
14288       // Then visit the argument expressions.
14289       Region = OtherRegion;
14290       for (const Expr *Argument : CE->arguments())
14291         Visit(Argument);
14292 
14293       Region = OldRegion;
14294       if (SemaRef.getLangOpts().CPlusPlus17) {
14295         Tree.merge(CalleeRegion);
14296         Tree.merge(OtherRegion);
14297       }
14298     });
14299   }
14300 
14301   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14302     // C++17 [over.match.oper]p2:
14303     //   [...] the operator notation is first transformed to the equivalent
14304     //   function-call notation as summarized in Table 12 (where @ denotes one
14305     //   of the operators covered in the specified subclause). However, the
14306     //   operands are sequenced in the order prescribed for the built-in
14307     //   operator (Clause 8).
14308     //
14309     // From the above only overloaded binary operators and overloaded call
14310     // operators have sequencing rules in C++17 that we need to handle
14311     // separately.
14312     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14313         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14314       return VisitCallExpr(CXXOCE);
14315 
14316     enum {
14317       NoSequencing,
14318       LHSBeforeRHS,
14319       RHSBeforeLHS,
14320       LHSBeforeRest
14321     } SequencingKind;
14322     switch (CXXOCE->getOperator()) {
14323     case OO_Equal:
14324     case OO_PlusEqual:
14325     case OO_MinusEqual:
14326     case OO_StarEqual:
14327     case OO_SlashEqual:
14328     case OO_PercentEqual:
14329     case OO_CaretEqual:
14330     case OO_AmpEqual:
14331     case OO_PipeEqual:
14332     case OO_LessLessEqual:
14333     case OO_GreaterGreaterEqual:
14334       SequencingKind = RHSBeforeLHS;
14335       break;
14336 
14337     case OO_LessLess:
14338     case OO_GreaterGreater:
14339     case OO_AmpAmp:
14340     case OO_PipePipe:
14341     case OO_Comma:
14342     case OO_ArrowStar:
14343     case OO_Subscript:
14344       SequencingKind = LHSBeforeRHS;
14345       break;
14346 
14347     case OO_Call:
14348       SequencingKind = LHSBeforeRest;
14349       break;
14350 
14351     default:
14352       SequencingKind = NoSequencing;
14353       break;
14354     }
14355 
14356     if (SequencingKind == NoSequencing)
14357       return VisitCallExpr(CXXOCE);
14358 
14359     // This is a call, so all subexpressions are sequenced before the result.
14360     SequencedSubexpression Sequenced(*this);
14361 
14362     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14363       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14364              "Should only get there with C++17 and above!");
14365       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14366              "Should only get there with an overloaded binary operator"
14367              " or an overloaded call operator!");
14368 
14369       if (SequencingKind == LHSBeforeRest) {
14370         assert(CXXOCE->getOperator() == OO_Call &&
14371                "We should only have an overloaded call operator here!");
14372 
14373         // This is very similar to VisitCallExpr, except that we only have the
14374         // C++17 case. The postfix-expression is the first argument of the
14375         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14376         // are in the following arguments.
14377         //
14378         // Note that we intentionally do not visit the callee expression since
14379         // it is just a decayed reference to a function.
14380         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14381         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14382         SequenceTree::Seq OldRegion = Region;
14383 
14384         assert(CXXOCE->getNumArgs() >= 1 &&
14385                "An overloaded call operator must have at least one argument"
14386                " for the postfix-expression!");
14387         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14388         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14389                                           CXXOCE->getNumArgs() - 1);
14390 
14391         // Visit the postfix-expression first.
14392         {
14393           Region = PostfixExprRegion;
14394           SequencedSubexpression Sequenced(*this);
14395           Visit(PostfixExpr);
14396         }
14397 
14398         // Then visit the argument expressions.
14399         Region = ArgsRegion;
14400         for (const Expr *Arg : Args)
14401           Visit(Arg);
14402 
14403         Region = OldRegion;
14404         Tree.merge(PostfixExprRegion);
14405         Tree.merge(ArgsRegion);
14406       } else {
14407         assert(CXXOCE->getNumArgs() == 2 &&
14408                "Should only have two arguments here!");
14409         assert((SequencingKind == LHSBeforeRHS ||
14410                 SequencingKind == RHSBeforeLHS) &&
14411                "Unexpected sequencing kind!");
14412 
14413         // We do not visit the callee expression since it is just a decayed
14414         // reference to a function.
14415         const Expr *E1 = CXXOCE->getArg(0);
14416         const Expr *E2 = CXXOCE->getArg(1);
14417         if (SequencingKind == RHSBeforeLHS)
14418           std::swap(E1, E2);
14419 
14420         return VisitSequencedExpressions(E1, E2);
14421       }
14422     });
14423   }
14424 
14425   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14426     // This is a call, so all subexpressions are sequenced before the result.
14427     SequencedSubexpression Sequenced(*this);
14428 
14429     if (!CCE->isListInitialization())
14430       return VisitExpr(CCE);
14431 
14432     // In C++11, list initializations are sequenced.
14433     SmallVector<SequenceTree::Seq, 32> Elts;
14434     SequenceTree::Seq Parent = Region;
14435     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14436                                               E = CCE->arg_end();
14437          I != E; ++I) {
14438       Region = Tree.allocate(Parent);
14439       Elts.push_back(Region);
14440       Visit(*I);
14441     }
14442 
14443     // Forget that the initializers are sequenced.
14444     Region = Parent;
14445     for (unsigned I = 0; I < Elts.size(); ++I)
14446       Tree.merge(Elts[I]);
14447   }
14448 
14449   void VisitInitListExpr(const InitListExpr *ILE) {
14450     if (!SemaRef.getLangOpts().CPlusPlus11)
14451       return VisitExpr(ILE);
14452 
14453     // In C++11, list initializations are sequenced.
14454     SmallVector<SequenceTree::Seq, 32> Elts;
14455     SequenceTree::Seq Parent = Region;
14456     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14457       const Expr *E = ILE->getInit(I);
14458       if (!E)
14459         continue;
14460       Region = Tree.allocate(Parent);
14461       Elts.push_back(Region);
14462       Visit(E);
14463     }
14464 
14465     // Forget that the initializers are sequenced.
14466     Region = Parent;
14467     for (unsigned I = 0; I < Elts.size(); ++I)
14468       Tree.merge(Elts[I]);
14469   }
14470 };
14471 
14472 } // namespace
14473 
14474 void Sema::CheckUnsequencedOperations(const Expr *E) {
14475   SmallVector<const Expr *, 8> WorkList;
14476   WorkList.push_back(E);
14477   while (!WorkList.empty()) {
14478     const Expr *Item = WorkList.pop_back_val();
14479     SequenceChecker(*this, Item, WorkList);
14480   }
14481 }
14482 
14483 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14484                               bool IsConstexpr) {
14485   llvm::SaveAndRestore<bool> ConstantContext(
14486       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14487   CheckImplicitConversions(E, CheckLoc);
14488   if (!E->isInstantiationDependent())
14489     CheckUnsequencedOperations(E);
14490   if (!IsConstexpr && !E->isValueDependent())
14491     CheckForIntOverflow(E);
14492   DiagnoseMisalignedMembers();
14493 }
14494 
14495 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14496                                        FieldDecl *BitField,
14497                                        Expr *Init) {
14498   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14499 }
14500 
14501 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14502                                          SourceLocation Loc) {
14503   if (!PType->isVariablyModifiedType())
14504     return;
14505   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14506     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14507     return;
14508   }
14509   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14510     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14511     return;
14512   }
14513   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14514     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14515     return;
14516   }
14517 
14518   const ArrayType *AT = S.Context.getAsArrayType(PType);
14519   if (!AT)
14520     return;
14521 
14522   if (AT->getSizeModifier() != ArrayType::Star) {
14523     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14524     return;
14525   }
14526 
14527   S.Diag(Loc, diag::err_array_star_in_function_definition);
14528 }
14529 
14530 /// CheckParmsForFunctionDef - Check that the parameters of the given
14531 /// function are appropriate for the definition of a function. This
14532 /// takes care of any checks that cannot be performed on the
14533 /// declaration itself, e.g., that the types of each of the function
14534 /// parameters are complete.
14535 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14536                                     bool CheckParameterNames) {
14537   bool HasInvalidParm = false;
14538   for (ParmVarDecl *Param : Parameters) {
14539     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14540     // function declarator that is part of a function definition of
14541     // that function shall not have incomplete type.
14542     //
14543     // This is also C++ [dcl.fct]p6.
14544     if (!Param->isInvalidDecl() &&
14545         RequireCompleteType(Param->getLocation(), Param->getType(),
14546                             diag::err_typecheck_decl_incomplete_type)) {
14547       Param->setInvalidDecl();
14548       HasInvalidParm = true;
14549     }
14550 
14551     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14552     // declaration of each parameter shall include an identifier.
14553     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14554         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14555       // Diagnose this as an extension in C17 and earlier.
14556       if (!getLangOpts().C2x)
14557         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14558     }
14559 
14560     // C99 6.7.5.3p12:
14561     //   If the function declarator is not part of a definition of that
14562     //   function, parameters may have incomplete type and may use the [*]
14563     //   notation in their sequences of declarator specifiers to specify
14564     //   variable length array types.
14565     QualType PType = Param->getOriginalType();
14566     // FIXME: This diagnostic should point the '[*]' if source-location
14567     // information is added for it.
14568     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14569 
14570     // If the parameter is a c++ class type and it has to be destructed in the
14571     // callee function, declare the destructor so that it can be called by the
14572     // callee function. Do not perform any direct access check on the dtor here.
14573     if (!Param->isInvalidDecl()) {
14574       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14575         if (!ClassDecl->isInvalidDecl() &&
14576             !ClassDecl->hasIrrelevantDestructor() &&
14577             !ClassDecl->isDependentContext() &&
14578             ClassDecl->isParamDestroyedInCallee()) {
14579           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14580           MarkFunctionReferenced(Param->getLocation(), Destructor);
14581           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14582         }
14583       }
14584     }
14585 
14586     // Parameters with the pass_object_size attribute only need to be marked
14587     // constant at function definitions. Because we lack information about
14588     // whether we're on a declaration or definition when we're instantiating the
14589     // attribute, we need to check for constness here.
14590     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14591       if (!Param->getType().isConstQualified())
14592         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14593             << Attr->getSpelling() << 1;
14594 
14595     // Check for parameter names shadowing fields from the class.
14596     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14597       // The owning context for the parameter should be the function, but we
14598       // want to see if this function's declaration context is a record.
14599       DeclContext *DC = Param->getDeclContext();
14600       if (DC && DC->isFunctionOrMethod()) {
14601         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14602           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14603                                      RD, /*DeclIsField*/ false);
14604       }
14605     }
14606   }
14607 
14608   return HasInvalidParm;
14609 }
14610 
14611 Optional<std::pair<CharUnits, CharUnits>>
14612 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14613 
14614 /// Compute the alignment and offset of the base class object given the
14615 /// derived-to-base cast expression and the alignment and offset of the derived
14616 /// class object.
14617 static std::pair<CharUnits, CharUnits>
14618 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14619                                    CharUnits BaseAlignment, CharUnits Offset,
14620                                    ASTContext &Ctx) {
14621   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14622        ++PathI) {
14623     const CXXBaseSpecifier *Base = *PathI;
14624     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14625     if (Base->isVirtual()) {
14626       // The complete object may have a lower alignment than the non-virtual
14627       // alignment of the base, in which case the base may be misaligned. Choose
14628       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14629       // conservative lower bound of the complete object alignment.
14630       CharUnits NonVirtualAlignment =
14631           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14632       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14633       Offset = CharUnits::Zero();
14634     } else {
14635       const ASTRecordLayout &RL =
14636           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14637       Offset += RL.getBaseClassOffset(BaseDecl);
14638     }
14639     DerivedType = Base->getType();
14640   }
14641 
14642   return std::make_pair(BaseAlignment, Offset);
14643 }
14644 
14645 /// Compute the alignment and offset of a binary additive operator.
14646 static Optional<std::pair<CharUnits, CharUnits>>
14647 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14648                                      bool IsSub, ASTContext &Ctx) {
14649   QualType PointeeType = PtrE->getType()->getPointeeType();
14650 
14651   if (!PointeeType->isConstantSizeType())
14652     return llvm::None;
14653 
14654   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14655 
14656   if (!P)
14657     return llvm::None;
14658 
14659   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14660   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14661     CharUnits Offset = EltSize * IdxRes->getExtValue();
14662     if (IsSub)
14663       Offset = -Offset;
14664     return std::make_pair(P->first, P->second + Offset);
14665   }
14666 
14667   // If the integer expression isn't a constant expression, compute the lower
14668   // bound of the alignment using the alignment and offset of the pointer
14669   // expression and the element size.
14670   return std::make_pair(
14671       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14672       CharUnits::Zero());
14673 }
14674 
14675 /// This helper function takes an lvalue expression and returns the alignment of
14676 /// a VarDecl and a constant offset from the VarDecl.
14677 Optional<std::pair<CharUnits, CharUnits>>
14678 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14679   E = E->IgnoreParens();
14680   switch (E->getStmtClass()) {
14681   default:
14682     break;
14683   case Stmt::CStyleCastExprClass:
14684   case Stmt::CXXStaticCastExprClass:
14685   case Stmt::ImplicitCastExprClass: {
14686     auto *CE = cast<CastExpr>(E);
14687     const Expr *From = CE->getSubExpr();
14688     switch (CE->getCastKind()) {
14689     default:
14690       break;
14691     case CK_NoOp:
14692       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14693     case CK_UncheckedDerivedToBase:
14694     case CK_DerivedToBase: {
14695       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14696       if (!P)
14697         break;
14698       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14699                                                 P->second, Ctx);
14700     }
14701     }
14702     break;
14703   }
14704   case Stmt::ArraySubscriptExprClass: {
14705     auto *ASE = cast<ArraySubscriptExpr>(E);
14706     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14707                                                 false, Ctx);
14708   }
14709   case Stmt::DeclRefExprClass: {
14710     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14711       // FIXME: If VD is captured by copy or is an escaping __block variable,
14712       // use the alignment of VD's type.
14713       if (!VD->getType()->isReferenceType())
14714         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14715       if (VD->hasInit())
14716         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14717     }
14718     break;
14719   }
14720   case Stmt::MemberExprClass: {
14721     auto *ME = cast<MemberExpr>(E);
14722     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14723     if (!FD || FD->getType()->isReferenceType() ||
14724         FD->getParent()->isInvalidDecl())
14725       break;
14726     Optional<std::pair<CharUnits, CharUnits>> P;
14727     if (ME->isArrow())
14728       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14729     else
14730       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14731     if (!P)
14732       break;
14733     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14734     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14735     return std::make_pair(P->first,
14736                           P->second + CharUnits::fromQuantity(Offset));
14737   }
14738   case Stmt::UnaryOperatorClass: {
14739     auto *UO = cast<UnaryOperator>(E);
14740     switch (UO->getOpcode()) {
14741     default:
14742       break;
14743     case UO_Deref:
14744       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14745     }
14746     break;
14747   }
14748   case Stmt::BinaryOperatorClass: {
14749     auto *BO = cast<BinaryOperator>(E);
14750     auto Opcode = BO->getOpcode();
14751     switch (Opcode) {
14752     default:
14753       break;
14754     case BO_Comma:
14755       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14756     }
14757     break;
14758   }
14759   }
14760   return llvm::None;
14761 }
14762 
14763 /// This helper function takes a pointer expression and returns the alignment of
14764 /// a VarDecl and a constant offset from the VarDecl.
14765 Optional<std::pair<CharUnits, CharUnits>>
14766 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14767   E = E->IgnoreParens();
14768   switch (E->getStmtClass()) {
14769   default:
14770     break;
14771   case Stmt::CStyleCastExprClass:
14772   case Stmt::CXXStaticCastExprClass:
14773   case Stmt::ImplicitCastExprClass: {
14774     auto *CE = cast<CastExpr>(E);
14775     const Expr *From = CE->getSubExpr();
14776     switch (CE->getCastKind()) {
14777     default:
14778       break;
14779     case CK_NoOp:
14780       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14781     case CK_ArrayToPointerDecay:
14782       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14783     case CK_UncheckedDerivedToBase:
14784     case CK_DerivedToBase: {
14785       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14786       if (!P)
14787         break;
14788       return getDerivedToBaseAlignmentAndOffset(
14789           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14790     }
14791     }
14792     break;
14793   }
14794   case Stmt::CXXThisExprClass: {
14795     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14796     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14797     return std::make_pair(Alignment, CharUnits::Zero());
14798   }
14799   case Stmt::UnaryOperatorClass: {
14800     auto *UO = cast<UnaryOperator>(E);
14801     if (UO->getOpcode() == UO_AddrOf)
14802       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14803     break;
14804   }
14805   case Stmt::BinaryOperatorClass: {
14806     auto *BO = cast<BinaryOperator>(E);
14807     auto Opcode = BO->getOpcode();
14808     switch (Opcode) {
14809     default:
14810       break;
14811     case BO_Add:
14812     case BO_Sub: {
14813       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14814       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14815         std::swap(LHS, RHS);
14816       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14817                                                   Ctx);
14818     }
14819     case BO_Comma:
14820       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14821     }
14822     break;
14823   }
14824   }
14825   return llvm::None;
14826 }
14827 
14828 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14829   // See if we can compute the alignment of a VarDecl and an offset from it.
14830   Optional<std::pair<CharUnits, CharUnits>> P =
14831       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14832 
14833   if (P)
14834     return P->first.alignmentAtOffset(P->second);
14835 
14836   // If that failed, return the type's alignment.
14837   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14838 }
14839 
14840 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14841 /// pointer cast increases the alignment requirements.
14842 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14843   // This is actually a lot of work to potentially be doing on every
14844   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14845   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14846     return;
14847 
14848   // Ignore dependent types.
14849   if (T->isDependentType() || Op->getType()->isDependentType())
14850     return;
14851 
14852   // Require that the destination be a pointer type.
14853   const PointerType *DestPtr = T->getAs<PointerType>();
14854   if (!DestPtr) return;
14855 
14856   // If the destination has alignment 1, we're done.
14857   QualType DestPointee = DestPtr->getPointeeType();
14858   if (DestPointee->isIncompleteType()) return;
14859   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14860   if (DestAlign.isOne()) return;
14861 
14862   // Require that the source be a pointer type.
14863   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14864   if (!SrcPtr) return;
14865   QualType SrcPointee = SrcPtr->getPointeeType();
14866 
14867   // Explicitly allow casts from cv void*.  We already implicitly
14868   // allowed casts to cv void*, since they have alignment 1.
14869   // Also allow casts involving incomplete types, which implicitly
14870   // includes 'void'.
14871   if (SrcPointee->isIncompleteType()) return;
14872 
14873   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14874 
14875   if (SrcAlign >= DestAlign) return;
14876 
14877   Diag(TRange.getBegin(), diag::warn_cast_align)
14878     << Op->getType() << T
14879     << static_cast<unsigned>(SrcAlign.getQuantity())
14880     << static_cast<unsigned>(DestAlign.getQuantity())
14881     << TRange << Op->getSourceRange();
14882 }
14883 
14884 /// Check whether this array fits the idiom of a size-one tail padded
14885 /// array member of a struct.
14886 ///
14887 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14888 /// commonly used to emulate flexible arrays in C89 code.
14889 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14890                                     const NamedDecl *ND) {
14891   if (Size != 1 || !ND) return false;
14892 
14893   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14894   if (!FD) return false;
14895 
14896   // Don't consider sizes resulting from macro expansions or template argument
14897   // substitution to form C89 tail-padded arrays.
14898 
14899   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14900   while (TInfo) {
14901     TypeLoc TL = TInfo->getTypeLoc();
14902     // Look through typedefs.
14903     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14904       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14905       TInfo = TDL->getTypeSourceInfo();
14906       continue;
14907     }
14908     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14909       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14910       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14911         return false;
14912     }
14913     break;
14914   }
14915 
14916   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14917   if (!RD) return false;
14918   if (RD->isUnion()) return false;
14919   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14920     if (!CRD->isStandardLayout()) return false;
14921   }
14922 
14923   // See if this is the last field decl in the record.
14924   const Decl *D = FD;
14925   while ((D = D->getNextDeclInContext()))
14926     if (isa<FieldDecl>(D))
14927       return false;
14928   return true;
14929 }
14930 
14931 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14932                             const ArraySubscriptExpr *ASE,
14933                             bool AllowOnePastEnd, bool IndexNegated) {
14934   // Already diagnosed by the constant evaluator.
14935   if (isConstantEvaluated())
14936     return;
14937 
14938   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14939   if (IndexExpr->isValueDependent())
14940     return;
14941 
14942   const Type *EffectiveType =
14943       BaseExpr->getType()->getPointeeOrArrayElementType();
14944   BaseExpr = BaseExpr->IgnoreParenCasts();
14945   const ConstantArrayType *ArrayTy =
14946       Context.getAsConstantArrayType(BaseExpr->getType());
14947 
14948   const Type *BaseType =
14949       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14950   bool IsUnboundedArray = (BaseType == nullptr);
14951   if (EffectiveType->isDependentType() ||
14952       (!IsUnboundedArray && BaseType->isDependentType()))
14953     return;
14954 
14955   Expr::EvalResult Result;
14956   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14957     return;
14958 
14959   llvm::APSInt index = Result.Val.getInt();
14960   if (IndexNegated) {
14961     index.setIsUnsigned(false);
14962     index = -index;
14963   }
14964 
14965   const NamedDecl *ND = nullptr;
14966   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14967     ND = DRE->getDecl();
14968   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14969     ND = ME->getMemberDecl();
14970 
14971   if (IsUnboundedArray) {
14972     if (index.isUnsigned() || !index.isNegative()) {
14973       const auto &ASTC = getASTContext();
14974       unsigned AddrBits =
14975           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14976               EffectiveType->getCanonicalTypeInternal()));
14977       if (index.getBitWidth() < AddrBits)
14978         index = index.zext(AddrBits);
14979       Optional<CharUnits> ElemCharUnits =
14980           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14981       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14982       // pointer) bounds-checking isn't meaningful.
14983       if (!ElemCharUnits)
14984         return;
14985       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14986       // If index has more active bits than address space, we already know
14987       // we have a bounds violation to warn about.  Otherwise, compute
14988       // address of (index + 1)th element, and warn about bounds violation
14989       // only if that address exceeds address space.
14990       if (index.getActiveBits() <= AddrBits) {
14991         bool Overflow;
14992         llvm::APInt Product(index);
14993         Product += 1;
14994         Product = Product.umul_ov(ElemBytes, Overflow);
14995         if (!Overflow && Product.getActiveBits() <= AddrBits)
14996           return;
14997       }
14998 
14999       // Need to compute max possible elements in address space, since that
15000       // is included in diag message.
15001       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15002       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15003       MaxElems += 1;
15004       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15005       MaxElems = MaxElems.udiv(ElemBytes);
15006 
15007       unsigned DiagID =
15008           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15009               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15010 
15011       // Diag message shows element size in bits and in "bytes" (platform-
15012       // dependent CharUnits)
15013       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15014                           PDiag(DiagID)
15015                               << toString(index, 10, true) << AddrBits
15016                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15017                               << toString(ElemBytes, 10, false)
15018                               << toString(MaxElems, 10, false)
15019                               << (unsigned)MaxElems.getLimitedValue(~0U)
15020                               << IndexExpr->getSourceRange());
15021 
15022       if (!ND) {
15023         // Try harder to find a NamedDecl to point at in the note.
15024         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15025           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15026         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15027           ND = DRE->getDecl();
15028         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15029           ND = ME->getMemberDecl();
15030       }
15031 
15032       if (ND)
15033         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15034                             PDiag(diag::note_array_declared_here) << ND);
15035     }
15036     return;
15037   }
15038 
15039   if (index.isUnsigned() || !index.isNegative()) {
15040     // It is possible that the type of the base expression after
15041     // IgnoreParenCasts is incomplete, even though the type of the base
15042     // expression before IgnoreParenCasts is complete (see PR39746 for an
15043     // example). In this case we have no information about whether the array
15044     // access exceeds the array bounds. However we can still diagnose an array
15045     // access which precedes the array bounds.
15046     if (BaseType->isIncompleteType())
15047       return;
15048 
15049     llvm::APInt size = ArrayTy->getSize();
15050     if (!size.isStrictlyPositive())
15051       return;
15052 
15053     if (BaseType != EffectiveType) {
15054       // Make sure we're comparing apples to apples when comparing index to size
15055       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15056       uint64_t array_typesize = Context.getTypeSize(BaseType);
15057       // Handle ptrarith_typesize being zero, such as when casting to void*
15058       if (!ptrarith_typesize) ptrarith_typesize = 1;
15059       if (ptrarith_typesize != array_typesize) {
15060         // There's a cast to a different size type involved
15061         uint64_t ratio = array_typesize / ptrarith_typesize;
15062         // TODO: Be smarter about handling cases where array_typesize is not a
15063         // multiple of ptrarith_typesize
15064         if (ptrarith_typesize * ratio == array_typesize)
15065           size *= llvm::APInt(size.getBitWidth(), ratio);
15066       }
15067     }
15068 
15069     if (size.getBitWidth() > index.getBitWidth())
15070       index = index.zext(size.getBitWidth());
15071     else if (size.getBitWidth() < index.getBitWidth())
15072       size = size.zext(index.getBitWidth());
15073 
15074     // For array subscripting the index must be less than size, but for pointer
15075     // arithmetic also allow the index (offset) to be equal to size since
15076     // computing the next address after the end of the array is legal and
15077     // commonly done e.g. in C++ iterators and range-based for loops.
15078     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15079       return;
15080 
15081     // Also don't warn for arrays of size 1 which are members of some
15082     // structure. These are often used to approximate flexible arrays in C89
15083     // code.
15084     if (IsTailPaddedMemberArray(*this, size, ND))
15085       return;
15086 
15087     // Suppress the warning if the subscript expression (as identified by the
15088     // ']' location) and the index expression are both from macro expansions
15089     // within a system header.
15090     if (ASE) {
15091       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15092           ASE->getRBracketLoc());
15093       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15094         SourceLocation IndexLoc =
15095             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15096         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15097           return;
15098       }
15099     }
15100 
15101     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15102                           : diag::warn_ptr_arith_exceeds_bounds;
15103 
15104     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15105                         PDiag(DiagID) << toString(index, 10, true)
15106                                       << toString(size, 10, true)
15107                                       << (unsigned)size.getLimitedValue(~0U)
15108                                       << IndexExpr->getSourceRange());
15109   } else {
15110     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15111     if (!ASE) {
15112       DiagID = diag::warn_ptr_arith_precedes_bounds;
15113       if (index.isNegative()) index = -index;
15114     }
15115 
15116     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15117                         PDiag(DiagID) << toString(index, 10, true)
15118                                       << IndexExpr->getSourceRange());
15119   }
15120 
15121   if (!ND) {
15122     // Try harder to find a NamedDecl to point at in the note.
15123     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15124       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15125     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15126       ND = DRE->getDecl();
15127     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15128       ND = ME->getMemberDecl();
15129   }
15130 
15131   if (ND)
15132     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15133                         PDiag(diag::note_array_declared_here) << ND);
15134 }
15135 
15136 void Sema::CheckArrayAccess(const Expr *expr) {
15137   int AllowOnePastEnd = 0;
15138   while (expr) {
15139     expr = expr->IgnoreParenImpCasts();
15140     switch (expr->getStmtClass()) {
15141       case Stmt::ArraySubscriptExprClass: {
15142         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15143         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15144                          AllowOnePastEnd > 0);
15145         expr = ASE->getBase();
15146         break;
15147       }
15148       case Stmt::MemberExprClass: {
15149         expr = cast<MemberExpr>(expr)->getBase();
15150         break;
15151       }
15152       case Stmt::OMPArraySectionExprClass: {
15153         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15154         if (ASE->getLowerBound())
15155           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15156                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15157         return;
15158       }
15159       case Stmt::UnaryOperatorClass: {
15160         // Only unwrap the * and & unary operators
15161         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15162         expr = UO->getSubExpr();
15163         switch (UO->getOpcode()) {
15164           case UO_AddrOf:
15165             AllowOnePastEnd++;
15166             break;
15167           case UO_Deref:
15168             AllowOnePastEnd--;
15169             break;
15170           default:
15171             return;
15172         }
15173         break;
15174       }
15175       case Stmt::ConditionalOperatorClass: {
15176         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15177         if (const Expr *lhs = cond->getLHS())
15178           CheckArrayAccess(lhs);
15179         if (const Expr *rhs = cond->getRHS())
15180           CheckArrayAccess(rhs);
15181         return;
15182       }
15183       case Stmt::CXXOperatorCallExprClass: {
15184         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15185         for (const auto *Arg : OCE->arguments())
15186           CheckArrayAccess(Arg);
15187         return;
15188       }
15189       default:
15190         return;
15191     }
15192   }
15193 }
15194 
15195 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15196 
15197 namespace {
15198 
15199 struct RetainCycleOwner {
15200   VarDecl *Variable = nullptr;
15201   SourceRange Range;
15202   SourceLocation Loc;
15203   bool Indirect = false;
15204 
15205   RetainCycleOwner() = default;
15206 
15207   void setLocsFrom(Expr *e) {
15208     Loc = e->getExprLoc();
15209     Range = e->getSourceRange();
15210   }
15211 };
15212 
15213 } // namespace
15214 
15215 /// Consider whether capturing the given variable can possibly lead to
15216 /// a retain cycle.
15217 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15218   // In ARC, it's captured strongly iff the variable has __strong
15219   // lifetime.  In MRR, it's captured strongly if the variable is
15220   // __block and has an appropriate type.
15221   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15222     return false;
15223 
15224   owner.Variable = var;
15225   if (ref)
15226     owner.setLocsFrom(ref);
15227   return true;
15228 }
15229 
15230 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15231   while (true) {
15232     e = e->IgnoreParens();
15233     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15234       switch (cast->getCastKind()) {
15235       case CK_BitCast:
15236       case CK_LValueBitCast:
15237       case CK_LValueToRValue:
15238       case CK_ARCReclaimReturnedObject:
15239         e = cast->getSubExpr();
15240         continue;
15241 
15242       default:
15243         return false;
15244       }
15245     }
15246 
15247     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15248       ObjCIvarDecl *ivar = ref->getDecl();
15249       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15250         return false;
15251 
15252       // Try to find a retain cycle in the base.
15253       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15254         return false;
15255 
15256       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15257       owner.Indirect = true;
15258       return true;
15259     }
15260 
15261     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15262       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15263       if (!var) return false;
15264       return considerVariable(var, ref, owner);
15265     }
15266 
15267     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15268       if (member->isArrow()) return false;
15269 
15270       // Don't count this as an indirect ownership.
15271       e = member->getBase();
15272       continue;
15273     }
15274 
15275     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15276       // Only pay attention to pseudo-objects on property references.
15277       ObjCPropertyRefExpr *pre
15278         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15279                                               ->IgnoreParens());
15280       if (!pre) return false;
15281       if (pre->isImplicitProperty()) return false;
15282       ObjCPropertyDecl *property = pre->getExplicitProperty();
15283       if (!property->isRetaining() &&
15284           !(property->getPropertyIvarDecl() &&
15285             property->getPropertyIvarDecl()->getType()
15286               .getObjCLifetime() == Qualifiers::OCL_Strong))
15287           return false;
15288 
15289       owner.Indirect = true;
15290       if (pre->isSuperReceiver()) {
15291         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15292         if (!owner.Variable)
15293           return false;
15294         owner.Loc = pre->getLocation();
15295         owner.Range = pre->getSourceRange();
15296         return true;
15297       }
15298       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15299                               ->getSourceExpr());
15300       continue;
15301     }
15302 
15303     // Array ivars?
15304 
15305     return false;
15306   }
15307 }
15308 
15309 namespace {
15310 
15311   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15312     ASTContext &Context;
15313     VarDecl *Variable;
15314     Expr *Capturer = nullptr;
15315     bool VarWillBeReased = false;
15316 
15317     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15318         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15319           Context(Context), Variable(variable) {}
15320 
15321     void VisitDeclRefExpr(DeclRefExpr *ref) {
15322       if (ref->getDecl() == Variable && !Capturer)
15323         Capturer = ref;
15324     }
15325 
15326     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15327       if (Capturer) return;
15328       Visit(ref->getBase());
15329       if (Capturer && ref->isFreeIvar())
15330         Capturer = ref;
15331     }
15332 
15333     void VisitBlockExpr(BlockExpr *block) {
15334       // Look inside nested blocks
15335       if (block->getBlockDecl()->capturesVariable(Variable))
15336         Visit(block->getBlockDecl()->getBody());
15337     }
15338 
15339     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15340       if (Capturer) return;
15341       if (OVE->getSourceExpr())
15342         Visit(OVE->getSourceExpr());
15343     }
15344 
15345     void VisitBinaryOperator(BinaryOperator *BinOp) {
15346       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15347         return;
15348       Expr *LHS = BinOp->getLHS();
15349       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15350         if (DRE->getDecl() != Variable)
15351           return;
15352         if (Expr *RHS = BinOp->getRHS()) {
15353           RHS = RHS->IgnoreParenCasts();
15354           Optional<llvm::APSInt> Value;
15355           VarWillBeReased =
15356               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15357                *Value == 0);
15358         }
15359       }
15360     }
15361   };
15362 
15363 } // namespace
15364 
15365 /// Check whether the given argument is a block which captures a
15366 /// variable.
15367 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15368   assert(owner.Variable && owner.Loc.isValid());
15369 
15370   e = e->IgnoreParenCasts();
15371 
15372   // Look through [^{...} copy] and Block_copy(^{...}).
15373   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15374     Selector Cmd = ME->getSelector();
15375     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15376       e = ME->getInstanceReceiver();
15377       if (!e)
15378         return nullptr;
15379       e = e->IgnoreParenCasts();
15380     }
15381   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15382     if (CE->getNumArgs() == 1) {
15383       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15384       if (Fn) {
15385         const IdentifierInfo *FnI = Fn->getIdentifier();
15386         if (FnI && FnI->isStr("_Block_copy")) {
15387           e = CE->getArg(0)->IgnoreParenCasts();
15388         }
15389       }
15390     }
15391   }
15392 
15393   BlockExpr *block = dyn_cast<BlockExpr>(e);
15394   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15395     return nullptr;
15396 
15397   FindCaptureVisitor visitor(S.Context, owner.Variable);
15398   visitor.Visit(block->getBlockDecl()->getBody());
15399   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15400 }
15401 
15402 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15403                                 RetainCycleOwner &owner) {
15404   assert(capturer);
15405   assert(owner.Variable && owner.Loc.isValid());
15406 
15407   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15408     << owner.Variable << capturer->getSourceRange();
15409   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15410     << owner.Indirect << owner.Range;
15411 }
15412 
15413 /// Check for a keyword selector that starts with the word 'add' or
15414 /// 'set'.
15415 static bool isSetterLikeSelector(Selector sel) {
15416   if (sel.isUnarySelector()) return false;
15417 
15418   StringRef str = sel.getNameForSlot(0);
15419   while (!str.empty() && str.front() == '_') str = str.substr(1);
15420   if (str.startswith("set"))
15421     str = str.substr(3);
15422   else if (str.startswith("add")) {
15423     // Specially allow 'addOperationWithBlock:'.
15424     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15425       return false;
15426     str = str.substr(3);
15427   }
15428   else
15429     return false;
15430 
15431   if (str.empty()) return true;
15432   return !isLowercase(str.front());
15433 }
15434 
15435 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15436                                                     ObjCMessageExpr *Message) {
15437   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15438                                                 Message->getReceiverInterface(),
15439                                                 NSAPI::ClassId_NSMutableArray);
15440   if (!IsMutableArray) {
15441     return None;
15442   }
15443 
15444   Selector Sel = Message->getSelector();
15445 
15446   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15447     S.NSAPIObj->getNSArrayMethodKind(Sel);
15448   if (!MKOpt) {
15449     return None;
15450   }
15451 
15452   NSAPI::NSArrayMethodKind MK = *MKOpt;
15453 
15454   switch (MK) {
15455     case NSAPI::NSMutableArr_addObject:
15456     case NSAPI::NSMutableArr_insertObjectAtIndex:
15457     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15458       return 0;
15459     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15460       return 1;
15461 
15462     default:
15463       return None;
15464   }
15465 
15466   return None;
15467 }
15468 
15469 static
15470 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15471                                                   ObjCMessageExpr *Message) {
15472   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15473                                             Message->getReceiverInterface(),
15474                                             NSAPI::ClassId_NSMutableDictionary);
15475   if (!IsMutableDictionary) {
15476     return None;
15477   }
15478 
15479   Selector Sel = Message->getSelector();
15480 
15481   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15482     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15483   if (!MKOpt) {
15484     return None;
15485   }
15486 
15487   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15488 
15489   switch (MK) {
15490     case NSAPI::NSMutableDict_setObjectForKey:
15491     case NSAPI::NSMutableDict_setValueForKey:
15492     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15493       return 0;
15494 
15495     default:
15496       return None;
15497   }
15498 
15499   return None;
15500 }
15501 
15502 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15503   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15504                                                 Message->getReceiverInterface(),
15505                                                 NSAPI::ClassId_NSMutableSet);
15506 
15507   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15508                                             Message->getReceiverInterface(),
15509                                             NSAPI::ClassId_NSMutableOrderedSet);
15510   if (!IsMutableSet && !IsMutableOrderedSet) {
15511     return None;
15512   }
15513 
15514   Selector Sel = Message->getSelector();
15515 
15516   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15517   if (!MKOpt) {
15518     return None;
15519   }
15520 
15521   NSAPI::NSSetMethodKind MK = *MKOpt;
15522 
15523   switch (MK) {
15524     case NSAPI::NSMutableSet_addObject:
15525     case NSAPI::NSOrderedSet_setObjectAtIndex:
15526     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15527     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15528       return 0;
15529     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15530       return 1;
15531   }
15532 
15533   return None;
15534 }
15535 
15536 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15537   if (!Message->isInstanceMessage()) {
15538     return;
15539   }
15540 
15541   Optional<int> ArgOpt;
15542 
15543   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15544       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15545       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15546     return;
15547   }
15548 
15549   int ArgIndex = *ArgOpt;
15550 
15551   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15552   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15553     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15554   }
15555 
15556   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15557     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15558       if (ArgRE->isObjCSelfExpr()) {
15559         Diag(Message->getSourceRange().getBegin(),
15560              diag::warn_objc_circular_container)
15561           << ArgRE->getDecl() << StringRef("'super'");
15562       }
15563     }
15564   } else {
15565     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15566 
15567     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15568       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15569     }
15570 
15571     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15572       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15573         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15574           ValueDecl *Decl = ReceiverRE->getDecl();
15575           Diag(Message->getSourceRange().getBegin(),
15576                diag::warn_objc_circular_container)
15577             << Decl << Decl;
15578           if (!ArgRE->isObjCSelfExpr()) {
15579             Diag(Decl->getLocation(),
15580                  diag::note_objc_circular_container_declared_here)
15581               << Decl;
15582           }
15583         }
15584       }
15585     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15586       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15587         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15588           ObjCIvarDecl *Decl = IvarRE->getDecl();
15589           Diag(Message->getSourceRange().getBegin(),
15590                diag::warn_objc_circular_container)
15591             << Decl << Decl;
15592           Diag(Decl->getLocation(),
15593                diag::note_objc_circular_container_declared_here)
15594             << Decl;
15595         }
15596       }
15597     }
15598   }
15599 }
15600 
15601 /// Check a message send to see if it's likely to cause a retain cycle.
15602 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15603   // Only check instance methods whose selector looks like a setter.
15604   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15605     return;
15606 
15607   // Try to find a variable that the receiver is strongly owned by.
15608   RetainCycleOwner owner;
15609   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15610     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15611       return;
15612   } else {
15613     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15614     owner.Variable = getCurMethodDecl()->getSelfDecl();
15615     owner.Loc = msg->getSuperLoc();
15616     owner.Range = msg->getSuperLoc();
15617   }
15618 
15619   // Check whether the receiver is captured by any of the arguments.
15620   const ObjCMethodDecl *MD = msg->getMethodDecl();
15621   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15622     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15623       // noescape blocks should not be retained by the method.
15624       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15625         continue;
15626       return diagnoseRetainCycle(*this, capturer, owner);
15627     }
15628   }
15629 }
15630 
15631 /// Check a property assign to see if it's likely to cause a retain cycle.
15632 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15633   RetainCycleOwner owner;
15634   if (!findRetainCycleOwner(*this, receiver, owner))
15635     return;
15636 
15637   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15638     diagnoseRetainCycle(*this, capturer, owner);
15639 }
15640 
15641 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15642   RetainCycleOwner Owner;
15643   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15644     return;
15645 
15646   // Because we don't have an expression for the variable, we have to set the
15647   // location explicitly here.
15648   Owner.Loc = Var->getLocation();
15649   Owner.Range = Var->getSourceRange();
15650 
15651   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15652     diagnoseRetainCycle(*this, Capturer, Owner);
15653 }
15654 
15655 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15656                                      Expr *RHS, bool isProperty) {
15657   // Check if RHS is an Objective-C object literal, which also can get
15658   // immediately zapped in a weak reference.  Note that we explicitly
15659   // allow ObjCStringLiterals, since those are designed to never really die.
15660   RHS = RHS->IgnoreParenImpCasts();
15661 
15662   // This enum needs to match with the 'select' in
15663   // warn_objc_arc_literal_assign (off-by-1).
15664   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15665   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15666     return false;
15667 
15668   S.Diag(Loc, diag::warn_arc_literal_assign)
15669     << (unsigned) Kind
15670     << (isProperty ? 0 : 1)
15671     << RHS->getSourceRange();
15672 
15673   return true;
15674 }
15675 
15676 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15677                                     Qualifiers::ObjCLifetime LT,
15678                                     Expr *RHS, bool isProperty) {
15679   // Strip off any implicit cast added to get to the one ARC-specific.
15680   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15681     if (cast->getCastKind() == CK_ARCConsumeObject) {
15682       S.Diag(Loc, diag::warn_arc_retained_assign)
15683         << (LT == Qualifiers::OCL_ExplicitNone)
15684         << (isProperty ? 0 : 1)
15685         << RHS->getSourceRange();
15686       return true;
15687     }
15688     RHS = cast->getSubExpr();
15689   }
15690 
15691   if (LT == Qualifiers::OCL_Weak &&
15692       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15693     return true;
15694 
15695   return false;
15696 }
15697 
15698 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15699                               QualType LHS, Expr *RHS) {
15700   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15701 
15702   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15703     return false;
15704 
15705   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15706     return true;
15707 
15708   return false;
15709 }
15710 
15711 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15712                               Expr *LHS, Expr *RHS) {
15713   QualType LHSType;
15714   // PropertyRef on LHS type need be directly obtained from
15715   // its declaration as it has a PseudoType.
15716   ObjCPropertyRefExpr *PRE
15717     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15718   if (PRE && !PRE->isImplicitProperty()) {
15719     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15720     if (PD)
15721       LHSType = PD->getType();
15722   }
15723 
15724   if (LHSType.isNull())
15725     LHSType = LHS->getType();
15726 
15727   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15728 
15729   if (LT == Qualifiers::OCL_Weak) {
15730     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15731       getCurFunction()->markSafeWeakUse(LHS);
15732   }
15733 
15734   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15735     return;
15736 
15737   // FIXME. Check for other life times.
15738   if (LT != Qualifiers::OCL_None)
15739     return;
15740 
15741   if (PRE) {
15742     if (PRE->isImplicitProperty())
15743       return;
15744     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15745     if (!PD)
15746       return;
15747 
15748     unsigned Attributes = PD->getPropertyAttributes();
15749     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15750       // when 'assign' attribute was not explicitly specified
15751       // by user, ignore it and rely on property type itself
15752       // for lifetime info.
15753       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15754       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15755           LHSType->isObjCRetainableType())
15756         return;
15757 
15758       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15759         if (cast->getCastKind() == CK_ARCConsumeObject) {
15760           Diag(Loc, diag::warn_arc_retained_property_assign)
15761           << RHS->getSourceRange();
15762           return;
15763         }
15764         RHS = cast->getSubExpr();
15765       }
15766     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15767       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15768         return;
15769     }
15770   }
15771 }
15772 
15773 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15774 
15775 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15776                                         SourceLocation StmtLoc,
15777                                         const NullStmt *Body) {
15778   // Do not warn if the body is a macro that expands to nothing, e.g:
15779   //
15780   // #define CALL(x)
15781   // if (condition)
15782   //   CALL(0);
15783   if (Body->hasLeadingEmptyMacro())
15784     return false;
15785 
15786   // Get line numbers of statement and body.
15787   bool StmtLineInvalid;
15788   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15789                                                       &StmtLineInvalid);
15790   if (StmtLineInvalid)
15791     return false;
15792 
15793   bool BodyLineInvalid;
15794   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15795                                                       &BodyLineInvalid);
15796   if (BodyLineInvalid)
15797     return false;
15798 
15799   // Warn if null statement and body are on the same line.
15800   if (StmtLine != BodyLine)
15801     return false;
15802 
15803   return true;
15804 }
15805 
15806 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15807                                  const Stmt *Body,
15808                                  unsigned DiagID) {
15809   // Since this is a syntactic check, don't emit diagnostic for template
15810   // instantiations, this just adds noise.
15811   if (CurrentInstantiationScope)
15812     return;
15813 
15814   // The body should be a null statement.
15815   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15816   if (!NBody)
15817     return;
15818 
15819   // Do the usual checks.
15820   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15821     return;
15822 
15823   Diag(NBody->getSemiLoc(), DiagID);
15824   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15825 }
15826 
15827 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15828                                  const Stmt *PossibleBody) {
15829   assert(!CurrentInstantiationScope); // Ensured by caller
15830 
15831   SourceLocation StmtLoc;
15832   const Stmt *Body;
15833   unsigned DiagID;
15834   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15835     StmtLoc = FS->getRParenLoc();
15836     Body = FS->getBody();
15837     DiagID = diag::warn_empty_for_body;
15838   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15839     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15840     Body = WS->getBody();
15841     DiagID = diag::warn_empty_while_body;
15842   } else
15843     return; // Neither `for' nor `while'.
15844 
15845   // The body should be a null statement.
15846   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15847   if (!NBody)
15848     return;
15849 
15850   // Skip expensive checks if diagnostic is disabled.
15851   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15852     return;
15853 
15854   // Do the usual checks.
15855   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15856     return;
15857 
15858   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15859   // noise level low, emit diagnostics only if for/while is followed by a
15860   // CompoundStmt, e.g.:
15861   //    for (int i = 0; i < n; i++);
15862   //    {
15863   //      a(i);
15864   //    }
15865   // or if for/while is followed by a statement with more indentation
15866   // than for/while itself:
15867   //    for (int i = 0; i < n; i++);
15868   //      a(i);
15869   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15870   if (!ProbableTypo) {
15871     bool BodyColInvalid;
15872     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15873         PossibleBody->getBeginLoc(), &BodyColInvalid);
15874     if (BodyColInvalid)
15875       return;
15876 
15877     bool StmtColInvalid;
15878     unsigned StmtCol =
15879         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15880     if (StmtColInvalid)
15881       return;
15882 
15883     if (BodyCol > StmtCol)
15884       ProbableTypo = true;
15885   }
15886 
15887   if (ProbableTypo) {
15888     Diag(NBody->getSemiLoc(), DiagID);
15889     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15890   }
15891 }
15892 
15893 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15894 
15895 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15896 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15897                              SourceLocation OpLoc) {
15898   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15899     return;
15900 
15901   if (inTemplateInstantiation())
15902     return;
15903 
15904   // Strip parens and casts away.
15905   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15906   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15907 
15908   // Check for a call expression
15909   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15910   if (!CE || CE->getNumArgs() != 1)
15911     return;
15912 
15913   // Check for a call to std::move
15914   if (!CE->isCallToStdMove())
15915     return;
15916 
15917   // Get argument from std::move
15918   RHSExpr = CE->getArg(0);
15919 
15920   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15921   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15922 
15923   // Two DeclRefExpr's, check that the decls are the same.
15924   if (LHSDeclRef && RHSDeclRef) {
15925     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15926       return;
15927     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15928         RHSDeclRef->getDecl()->getCanonicalDecl())
15929       return;
15930 
15931     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15932                                         << LHSExpr->getSourceRange()
15933                                         << RHSExpr->getSourceRange();
15934     return;
15935   }
15936 
15937   // Member variables require a different approach to check for self moves.
15938   // MemberExpr's are the same if every nested MemberExpr refers to the same
15939   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15940   // the base Expr's are CXXThisExpr's.
15941   const Expr *LHSBase = LHSExpr;
15942   const Expr *RHSBase = RHSExpr;
15943   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15944   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15945   if (!LHSME || !RHSME)
15946     return;
15947 
15948   while (LHSME && RHSME) {
15949     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15950         RHSME->getMemberDecl()->getCanonicalDecl())
15951       return;
15952 
15953     LHSBase = LHSME->getBase();
15954     RHSBase = RHSME->getBase();
15955     LHSME = dyn_cast<MemberExpr>(LHSBase);
15956     RHSME = dyn_cast<MemberExpr>(RHSBase);
15957   }
15958 
15959   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15960   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15961   if (LHSDeclRef && RHSDeclRef) {
15962     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15963       return;
15964     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15965         RHSDeclRef->getDecl()->getCanonicalDecl())
15966       return;
15967 
15968     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15969                                         << LHSExpr->getSourceRange()
15970                                         << RHSExpr->getSourceRange();
15971     return;
15972   }
15973 
15974   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15975     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15976                                         << LHSExpr->getSourceRange()
15977                                         << RHSExpr->getSourceRange();
15978 }
15979 
15980 //===--- Layout compatibility ----------------------------------------------//
15981 
15982 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15983 
15984 /// Check if two enumeration types are layout-compatible.
15985 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15986   // C++11 [dcl.enum] p8:
15987   // Two enumeration types are layout-compatible if they have the same
15988   // underlying type.
15989   return ED1->isComplete() && ED2->isComplete() &&
15990          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15991 }
15992 
15993 /// Check if two fields are layout-compatible.
15994 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15995                                FieldDecl *Field2) {
15996   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15997     return false;
15998 
15999   if (Field1->isBitField() != Field2->isBitField())
16000     return false;
16001 
16002   if (Field1->isBitField()) {
16003     // Make sure that the bit-fields are the same length.
16004     unsigned Bits1 = Field1->getBitWidthValue(C);
16005     unsigned Bits2 = Field2->getBitWidthValue(C);
16006 
16007     if (Bits1 != Bits2)
16008       return false;
16009   }
16010 
16011   return true;
16012 }
16013 
16014 /// Check if two standard-layout structs are layout-compatible.
16015 /// (C++11 [class.mem] p17)
16016 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16017                                      RecordDecl *RD2) {
16018   // If both records are C++ classes, check that base classes match.
16019   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16020     // If one of records is a CXXRecordDecl we are in C++ mode,
16021     // thus the other one is a CXXRecordDecl, too.
16022     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16023     // Check number of base classes.
16024     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16025       return false;
16026 
16027     // Check the base classes.
16028     for (CXXRecordDecl::base_class_const_iterator
16029                Base1 = D1CXX->bases_begin(),
16030            BaseEnd1 = D1CXX->bases_end(),
16031               Base2 = D2CXX->bases_begin();
16032          Base1 != BaseEnd1;
16033          ++Base1, ++Base2) {
16034       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16035         return false;
16036     }
16037   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16038     // If only RD2 is a C++ class, it should have zero base classes.
16039     if (D2CXX->getNumBases() > 0)
16040       return false;
16041   }
16042 
16043   // Check the fields.
16044   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16045                              Field2End = RD2->field_end(),
16046                              Field1 = RD1->field_begin(),
16047                              Field1End = RD1->field_end();
16048   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16049     if (!isLayoutCompatible(C, *Field1, *Field2))
16050       return false;
16051   }
16052   if (Field1 != Field1End || Field2 != Field2End)
16053     return false;
16054 
16055   return true;
16056 }
16057 
16058 /// Check if two standard-layout unions are layout-compatible.
16059 /// (C++11 [class.mem] p18)
16060 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16061                                     RecordDecl *RD2) {
16062   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16063   for (auto *Field2 : RD2->fields())
16064     UnmatchedFields.insert(Field2);
16065 
16066   for (auto *Field1 : RD1->fields()) {
16067     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16068         I = UnmatchedFields.begin(),
16069         E = UnmatchedFields.end();
16070 
16071     for ( ; I != E; ++I) {
16072       if (isLayoutCompatible(C, Field1, *I)) {
16073         bool Result = UnmatchedFields.erase(*I);
16074         (void) Result;
16075         assert(Result);
16076         break;
16077       }
16078     }
16079     if (I == E)
16080       return false;
16081   }
16082 
16083   return UnmatchedFields.empty();
16084 }
16085 
16086 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16087                                RecordDecl *RD2) {
16088   if (RD1->isUnion() != RD2->isUnion())
16089     return false;
16090 
16091   if (RD1->isUnion())
16092     return isLayoutCompatibleUnion(C, RD1, RD2);
16093   else
16094     return isLayoutCompatibleStruct(C, RD1, RD2);
16095 }
16096 
16097 /// Check if two types are layout-compatible in C++11 sense.
16098 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16099   if (T1.isNull() || T2.isNull())
16100     return false;
16101 
16102   // C++11 [basic.types] p11:
16103   // If two types T1 and T2 are the same type, then T1 and T2 are
16104   // layout-compatible types.
16105   if (C.hasSameType(T1, T2))
16106     return true;
16107 
16108   T1 = T1.getCanonicalType().getUnqualifiedType();
16109   T2 = T2.getCanonicalType().getUnqualifiedType();
16110 
16111   const Type::TypeClass TC1 = T1->getTypeClass();
16112   const Type::TypeClass TC2 = T2->getTypeClass();
16113 
16114   if (TC1 != TC2)
16115     return false;
16116 
16117   if (TC1 == Type::Enum) {
16118     return isLayoutCompatible(C,
16119                               cast<EnumType>(T1)->getDecl(),
16120                               cast<EnumType>(T2)->getDecl());
16121   } else if (TC1 == Type::Record) {
16122     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16123       return false;
16124 
16125     return isLayoutCompatible(C,
16126                               cast<RecordType>(T1)->getDecl(),
16127                               cast<RecordType>(T2)->getDecl());
16128   }
16129 
16130   return false;
16131 }
16132 
16133 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16134 
16135 /// Given a type tag expression find the type tag itself.
16136 ///
16137 /// \param TypeExpr Type tag expression, as it appears in user's code.
16138 ///
16139 /// \param VD Declaration of an identifier that appears in a type tag.
16140 ///
16141 /// \param MagicValue Type tag magic value.
16142 ///
16143 /// \param isConstantEvaluated whether the evalaution should be performed in
16144 
16145 /// constant context.
16146 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16147                             const ValueDecl **VD, uint64_t *MagicValue,
16148                             bool isConstantEvaluated) {
16149   while(true) {
16150     if (!TypeExpr)
16151       return false;
16152 
16153     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16154 
16155     switch (TypeExpr->getStmtClass()) {
16156     case Stmt::UnaryOperatorClass: {
16157       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16158       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16159         TypeExpr = UO->getSubExpr();
16160         continue;
16161       }
16162       return false;
16163     }
16164 
16165     case Stmt::DeclRefExprClass: {
16166       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16167       *VD = DRE->getDecl();
16168       return true;
16169     }
16170 
16171     case Stmt::IntegerLiteralClass: {
16172       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16173       llvm::APInt MagicValueAPInt = IL->getValue();
16174       if (MagicValueAPInt.getActiveBits() <= 64) {
16175         *MagicValue = MagicValueAPInt.getZExtValue();
16176         return true;
16177       } else
16178         return false;
16179     }
16180 
16181     case Stmt::BinaryConditionalOperatorClass:
16182     case Stmt::ConditionalOperatorClass: {
16183       const AbstractConditionalOperator *ACO =
16184           cast<AbstractConditionalOperator>(TypeExpr);
16185       bool Result;
16186       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16187                                                      isConstantEvaluated)) {
16188         if (Result)
16189           TypeExpr = ACO->getTrueExpr();
16190         else
16191           TypeExpr = ACO->getFalseExpr();
16192         continue;
16193       }
16194       return false;
16195     }
16196 
16197     case Stmt::BinaryOperatorClass: {
16198       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16199       if (BO->getOpcode() == BO_Comma) {
16200         TypeExpr = BO->getRHS();
16201         continue;
16202       }
16203       return false;
16204     }
16205 
16206     default:
16207       return false;
16208     }
16209   }
16210 }
16211 
16212 /// Retrieve the C type corresponding to type tag TypeExpr.
16213 ///
16214 /// \param TypeExpr Expression that specifies a type tag.
16215 ///
16216 /// \param MagicValues Registered magic values.
16217 ///
16218 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16219 ///        kind.
16220 ///
16221 /// \param TypeInfo Information about the corresponding C type.
16222 ///
16223 /// \param isConstantEvaluated whether the evalaution should be performed in
16224 /// constant context.
16225 ///
16226 /// \returns true if the corresponding C type was found.
16227 static bool GetMatchingCType(
16228     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16229     const ASTContext &Ctx,
16230     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16231         *MagicValues,
16232     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16233     bool isConstantEvaluated) {
16234   FoundWrongKind = false;
16235 
16236   // Variable declaration that has type_tag_for_datatype attribute.
16237   const ValueDecl *VD = nullptr;
16238 
16239   uint64_t MagicValue;
16240 
16241   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16242     return false;
16243 
16244   if (VD) {
16245     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16246       if (I->getArgumentKind() != ArgumentKind) {
16247         FoundWrongKind = true;
16248         return false;
16249       }
16250       TypeInfo.Type = I->getMatchingCType();
16251       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16252       TypeInfo.MustBeNull = I->getMustBeNull();
16253       return true;
16254     }
16255     return false;
16256   }
16257 
16258   if (!MagicValues)
16259     return false;
16260 
16261   llvm::DenseMap<Sema::TypeTagMagicValue,
16262                  Sema::TypeTagData>::const_iterator I =
16263       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16264   if (I == MagicValues->end())
16265     return false;
16266 
16267   TypeInfo = I->second;
16268   return true;
16269 }
16270 
16271 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16272                                       uint64_t MagicValue, QualType Type,
16273                                       bool LayoutCompatible,
16274                                       bool MustBeNull) {
16275   if (!TypeTagForDatatypeMagicValues)
16276     TypeTagForDatatypeMagicValues.reset(
16277         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16278 
16279   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16280   (*TypeTagForDatatypeMagicValues)[Magic] =
16281       TypeTagData(Type, LayoutCompatible, MustBeNull);
16282 }
16283 
16284 static bool IsSameCharType(QualType T1, QualType T2) {
16285   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16286   if (!BT1)
16287     return false;
16288 
16289   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16290   if (!BT2)
16291     return false;
16292 
16293   BuiltinType::Kind T1Kind = BT1->getKind();
16294   BuiltinType::Kind T2Kind = BT2->getKind();
16295 
16296   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16297          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16298          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16299          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16300 }
16301 
16302 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16303                                     const ArrayRef<const Expr *> ExprArgs,
16304                                     SourceLocation CallSiteLoc) {
16305   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16306   bool IsPointerAttr = Attr->getIsPointer();
16307 
16308   // Retrieve the argument representing the 'type_tag'.
16309   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16310   if (TypeTagIdxAST >= ExprArgs.size()) {
16311     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16312         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16313     return;
16314   }
16315   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16316   bool FoundWrongKind;
16317   TypeTagData TypeInfo;
16318   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16319                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16320                         TypeInfo, isConstantEvaluated())) {
16321     if (FoundWrongKind)
16322       Diag(TypeTagExpr->getExprLoc(),
16323            diag::warn_type_tag_for_datatype_wrong_kind)
16324         << TypeTagExpr->getSourceRange();
16325     return;
16326   }
16327 
16328   // Retrieve the argument representing the 'arg_idx'.
16329   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16330   if (ArgumentIdxAST >= ExprArgs.size()) {
16331     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16332         << 1 << Attr->getArgumentIdx().getSourceIndex();
16333     return;
16334   }
16335   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16336   if (IsPointerAttr) {
16337     // Skip implicit cast of pointer to `void *' (as a function argument).
16338     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16339       if (ICE->getType()->isVoidPointerType() &&
16340           ICE->getCastKind() == CK_BitCast)
16341         ArgumentExpr = ICE->getSubExpr();
16342   }
16343   QualType ArgumentType = ArgumentExpr->getType();
16344 
16345   // Passing a `void*' pointer shouldn't trigger a warning.
16346   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16347     return;
16348 
16349   if (TypeInfo.MustBeNull) {
16350     // Type tag with matching void type requires a null pointer.
16351     if (!ArgumentExpr->isNullPointerConstant(Context,
16352                                              Expr::NPC_ValueDependentIsNotNull)) {
16353       Diag(ArgumentExpr->getExprLoc(),
16354            diag::warn_type_safety_null_pointer_required)
16355           << ArgumentKind->getName()
16356           << ArgumentExpr->getSourceRange()
16357           << TypeTagExpr->getSourceRange();
16358     }
16359     return;
16360   }
16361 
16362   QualType RequiredType = TypeInfo.Type;
16363   if (IsPointerAttr)
16364     RequiredType = Context.getPointerType(RequiredType);
16365 
16366   bool mismatch = false;
16367   if (!TypeInfo.LayoutCompatible) {
16368     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16369 
16370     // C++11 [basic.fundamental] p1:
16371     // Plain char, signed char, and unsigned char are three distinct types.
16372     //
16373     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16374     // char' depending on the current char signedness mode.
16375     if (mismatch)
16376       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16377                                            RequiredType->getPointeeType())) ||
16378           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16379         mismatch = false;
16380   } else
16381     if (IsPointerAttr)
16382       mismatch = !isLayoutCompatible(Context,
16383                                      ArgumentType->getPointeeType(),
16384                                      RequiredType->getPointeeType());
16385     else
16386       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16387 
16388   if (mismatch)
16389     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16390         << ArgumentType << ArgumentKind
16391         << TypeInfo.LayoutCompatible << RequiredType
16392         << ArgumentExpr->getSourceRange()
16393         << TypeTagExpr->getSourceRange();
16394 }
16395 
16396 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16397                                          CharUnits Alignment) {
16398   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16399 }
16400 
16401 void Sema::DiagnoseMisalignedMembers() {
16402   for (MisalignedMember &m : MisalignedMembers) {
16403     const NamedDecl *ND = m.RD;
16404     if (ND->getName().empty()) {
16405       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16406         ND = TD;
16407     }
16408     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16409         << m.MD << ND << m.E->getSourceRange();
16410   }
16411   MisalignedMembers.clear();
16412 }
16413 
16414 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16415   E = E->IgnoreParens();
16416   if (!T->isPointerType() && !T->isIntegerType())
16417     return;
16418   if (isa<UnaryOperator>(E) &&
16419       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16420     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16421     if (isa<MemberExpr>(Op)) {
16422       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16423       if (MA != MisalignedMembers.end() &&
16424           (T->isIntegerType() ||
16425            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16426                                    Context.getTypeAlignInChars(
16427                                        T->getPointeeType()) <= MA->Alignment))))
16428         MisalignedMembers.erase(MA);
16429     }
16430   }
16431 }
16432 
16433 void Sema::RefersToMemberWithReducedAlignment(
16434     Expr *E,
16435     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16436         Action) {
16437   const auto *ME = dyn_cast<MemberExpr>(E);
16438   if (!ME)
16439     return;
16440 
16441   // No need to check expressions with an __unaligned-qualified type.
16442   if (E->getType().getQualifiers().hasUnaligned())
16443     return;
16444 
16445   // For a chain of MemberExpr like "a.b.c.d" this list
16446   // will keep FieldDecl's like [d, c, b].
16447   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16448   const MemberExpr *TopME = nullptr;
16449   bool AnyIsPacked = false;
16450   do {
16451     QualType BaseType = ME->getBase()->getType();
16452     if (BaseType->isDependentType())
16453       return;
16454     if (ME->isArrow())
16455       BaseType = BaseType->getPointeeType();
16456     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16457     if (RD->isInvalidDecl())
16458       return;
16459 
16460     ValueDecl *MD = ME->getMemberDecl();
16461     auto *FD = dyn_cast<FieldDecl>(MD);
16462     // We do not care about non-data members.
16463     if (!FD || FD->isInvalidDecl())
16464       return;
16465 
16466     AnyIsPacked =
16467         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16468     ReverseMemberChain.push_back(FD);
16469 
16470     TopME = ME;
16471     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16472   } while (ME);
16473   assert(TopME && "We did not compute a topmost MemberExpr!");
16474 
16475   // Not the scope of this diagnostic.
16476   if (!AnyIsPacked)
16477     return;
16478 
16479   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16480   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16481   // TODO: The innermost base of the member expression may be too complicated.
16482   // For now, just disregard these cases. This is left for future
16483   // improvement.
16484   if (!DRE && !isa<CXXThisExpr>(TopBase))
16485       return;
16486 
16487   // Alignment expected by the whole expression.
16488   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16489 
16490   // No need to do anything else with this case.
16491   if (ExpectedAlignment.isOne())
16492     return;
16493 
16494   // Synthesize offset of the whole access.
16495   CharUnits Offset;
16496   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16497        I++) {
16498     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16499   }
16500 
16501   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16502   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16503       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16504 
16505   // The base expression of the innermost MemberExpr may give
16506   // stronger guarantees than the class containing the member.
16507   if (DRE && !TopME->isArrow()) {
16508     const ValueDecl *VD = DRE->getDecl();
16509     if (!VD->getType()->isReferenceType())
16510       CompleteObjectAlignment =
16511           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16512   }
16513 
16514   // Check if the synthesized offset fulfills the alignment.
16515   if (Offset % ExpectedAlignment != 0 ||
16516       // It may fulfill the offset it but the effective alignment may still be
16517       // lower than the expected expression alignment.
16518       CompleteObjectAlignment < ExpectedAlignment) {
16519     // If this happens, we want to determine a sensible culprit of this.
16520     // Intuitively, watching the chain of member expressions from right to
16521     // left, we start with the required alignment (as required by the field
16522     // type) but some packed attribute in that chain has reduced the alignment.
16523     // It may happen that another packed structure increases it again. But if
16524     // we are here such increase has not been enough. So pointing the first
16525     // FieldDecl that either is packed or else its RecordDecl is,
16526     // seems reasonable.
16527     FieldDecl *FD = nullptr;
16528     CharUnits Alignment;
16529     for (FieldDecl *FDI : ReverseMemberChain) {
16530       if (FDI->hasAttr<PackedAttr>() ||
16531           FDI->getParent()->hasAttr<PackedAttr>()) {
16532         FD = FDI;
16533         Alignment = std::min(
16534             Context.getTypeAlignInChars(FD->getType()),
16535             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16536         break;
16537       }
16538     }
16539     assert(FD && "We did not find a packed FieldDecl!");
16540     Action(E, FD->getParent(), FD, Alignment);
16541   }
16542 }
16543 
16544 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16545   using namespace std::placeholders;
16546 
16547   RefersToMemberWithReducedAlignment(
16548       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16549                      _2, _3, _4));
16550 }
16551 
16552 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16553                                             ExprResult CallResult) {
16554   if (checkArgCount(*this, TheCall, 1))
16555     return ExprError();
16556 
16557   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16558   if (MatrixArg.isInvalid())
16559     return MatrixArg;
16560   Expr *Matrix = MatrixArg.get();
16561 
16562   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16563   if (!MType) {
16564     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16565     return ExprError();
16566   }
16567 
16568   // Create returned matrix type by swapping rows and columns of the argument
16569   // matrix type.
16570   QualType ResultType = Context.getConstantMatrixType(
16571       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16572 
16573   // Change the return type to the type of the returned matrix.
16574   TheCall->setType(ResultType);
16575 
16576   // Update call argument to use the possibly converted matrix argument.
16577   TheCall->setArg(0, Matrix);
16578   return CallResult;
16579 }
16580 
16581 // Get and verify the matrix dimensions.
16582 static llvm::Optional<unsigned>
16583 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16584   SourceLocation ErrorPos;
16585   Optional<llvm::APSInt> Value =
16586       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16587   if (!Value) {
16588     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16589         << Name;
16590     return {};
16591   }
16592   uint64_t Dim = Value->getZExtValue();
16593   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16594     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16595         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16596     return {};
16597   }
16598   return Dim;
16599 }
16600 
16601 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16602                                                   ExprResult CallResult) {
16603   if (!getLangOpts().MatrixTypes) {
16604     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16605     return ExprError();
16606   }
16607 
16608   if (checkArgCount(*this, TheCall, 4))
16609     return ExprError();
16610 
16611   unsigned PtrArgIdx = 0;
16612   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16613   Expr *RowsExpr = TheCall->getArg(1);
16614   Expr *ColumnsExpr = TheCall->getArg(2);
16615   Expr *StrideExpr = TheCall->getArg(3);
16616 
16617   bool ArgError = false;
16618 
16619   // Check pointer argument.
16620   {
16621     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16622     if (PtrConv.isInvalid())
16623       return PtrConv;
16624     PtrExpr = PtrConv.get();
16625     TheCall->setArg(0, PtrExpr);
16626     if (PtrExpr->isTypeDependent()) {
16627       TheCall->setType(Context.DependentTy);
16628       return TheCall;
16629     }
16630   }
16631 
16632   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16633   QualType ElementTy;
16634   if (!PtrTy) {
16635     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16636         << PtrArgIdx + 1;
16637     ArgError = true;
16638   } else {
16639     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16640 
16641     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16642       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16643           << PtrArgIdx + 1;
16644       ArgError = true;
16645     }
16646   }
16647 
16648   // Apply default Lvalue conversions and convert the expression to size_t.
16649   auto ApplyArgumentConversions = [this](Expr *E) {
16650     ExprResult Conv = DefaultLvalueConversion(E);
16651     if (Conv.isInvalid())
16652       return Conv;
16653 
16654     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16655   };
16656 
16657   // Apply conversion to row and column expressions.
16658   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16659   if (!RowsConv.isInvalid()) {
16660     RowsExpr = RowsConv.get();
16661     TheCall->setArg(1, RowsExpr);
16662   } else
16663     RowsExpr = nullptr;
16664 
16665   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16666   if (!ColumnsConv.isInvalid()) {
16667     ColumnsExpr = ColumnsConv.get();
16668     TheCall->setArg(2, ColumnsExpr);
16669   } else
16670     ColumnsExpr = nullptr;
16671 
16672   // If any any part of the result matrix type is still pending, just use
16673   // Context.DependentTy, until all parts are resolved.
16674   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16675       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16676     TheCall->setType(Context.DependentTy);
16677     return CallResult;
16678   }
16679 
16680   // Check row and column dimensions.
16681   llvm::Optional<unsigned> MaybeRows;
16682   if (RowsExpr)
16683     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16684 
16685   llvm::Optional<unsigned> MaybeColumns;
16686   if (ColumnsExpr)
16687     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16688 
16689   // Check stride argument.
16690   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16691   if (StrideConv.isInvalid())
16692     return ExprError();
16693   StrideExpr = StrideConv.get();
16694   TheCall->setArg(3, StrideExpr);
16695 
16696   if (MaybeRows) {
16697     if (Optional<llvm::APSInt> Value =
16698             StrideExpr->getIntegerConstantExpr(Context)) {
16699       uint64_t Stride = Value->getZExtValue();
16700       if (Stride < *MaybeRows) {
16701         Diag(StrideExpr->getBeginLoc(),
16702              diag::err_builtin_matrix_stride_too_small);
16703         ArgError = true;
16704       }
16705     }
16706   }
16707 
16708   if (ArgError || !MaybeRows || !MaybeColumns)
16709     return ExprError();
16710 
16711   TheCall->setType(
16712       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16713   return CallResult;
16714 }
16715 
16716 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16717                                                    ExprResult CallResult) {
16718   if (checkArgCount(*this, TheCall, 3))
16719     return ExprError();
16720 
16721   unsigned PtrArgIdx = 1;
16722   Expr *MatrixExpr = TheCall->getArg(0);
16723   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16724   Expr *StrideExpr = TheCall->getArg(2);
16725 
16726   bool ArgError = false;
16727 
16728   {
16729     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16730     if (MatrixConv.isInvalid())
16731       return MatrixConv;
16732     MatrixExpr = MatrixConv.get();
16733     TheCall->setArg(0, MatrixExpr);
16734   }
16735   if (MatrixExpr->isTypeDependent()) {
16736     TheCall->setType(Context.DependentTy);
16737     return TheCall;
16738   }
16739 
16740   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16741   if (!MatrixTy) {
16742     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16743     ArgError = true;
16744   }
16745 
16746   {
16747     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16748     if (PtrConv.isInvalid())
16749       return PtrConv;
16750     PtrExpr = PtrConv.get();
16751     TheCall->setArg(1, PtrExpr);
16752     if (PtrExpr->isTypeDependent()) {
16753       TheCall->setType(Context.DependentTy);
16754       return TheCall;
16755     }
16756   }
16757 
16758   // Check pointer argument.
16759   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16760   if (!PtrTy) {
16761     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16762         << PtrArgIdx + 1;
16763     ArgError = true;
16764   } else {
16765     QualType ElementTy = PtrTy->getPointeeType();
16766     if (ElementTy.isConstQualified()) {
16767       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16768       ArgError = true;
16769     }
16770     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16771     if (MatrixTy &&
16772         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16773       Diag(PtrExpr->getBeginLoc(),
16774            diag::err_builtin_matrix_pointer_arg_mismatch)
16775           << ElementTy << MatrixTy->getElementType();
16776       ArgError = true;
16777     }
16778   }
16779 
16780   // Apply default Lvalue conversions and convert the stride expression to
16781   // size_t.
16782   {
16783     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16784     if (StrideConv.isInvalid())
16785       return StrideConv;
16786 
16787     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16788     if (StrideConv.isInvalid())
16789       return StrideConv;
16790     StrideExpr = StrideConv.get();
16791     TheCall->setArg(2, StrideExpr);
16792   }
16793 
16794   // Check stride argument.
16795   if (MatrixTy) {
16796     if (Optional<llvm::APSInt> Value =
16797             StrideExpr->getIntegerConstantExpr(Context)) {
16798       uint64_t Stride = Value->getZExtValue();
16799       if (Stride < MatrixTy->getNumRows()) {
16800         Diag(StrideExpr->getBeginLoc(),
16801              diag::err_builtin_matrix_stride_too_small);
16802         ArgError = true;
16803       }
16804     }
16805   }
16806 
16807   if (ArgError)
16808     return ExprError();
16809 
16810   return CallResult;
16811 }
16812 
16813 /// \brief Enforce the bounds of a TCB
16814 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16815 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16816 /// and enforce_tcb_leaf attributes.
16817 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16818                                const FunctionDecl *Callee) {
16819   const FunctionDecl *Caller = getCurFunctionDecl();
16820 
16821   // Calls to builtins are not enforced.
16822   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16823       Callee->getBuiltinID() != 0)
16824     return;
16825 
16826   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16827   // all TCBs the callee is a part of.
16828   llvm::StringSet<> CalleeTCBs;
16829   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16830            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16831   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16832            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16833 
16834   // Go through the TCBs the caller is a part of and emit warnings if Caller
16835   // is in a TCB that the Callee is not.
16836   for_each(
16837       Caller->specific_attrs<EnforceTCBAttr>(),
16838       [&](const auto *A) {
16839         StringRef CallerTCB = A->getTCBName();
16840         if (CalleeTCBs.count(CallerTCB) == 0) {
16841           this->Diag(TheCall->getExprLoc(),
16842                      diag::warn_tcb_enforcement_violation) << Callee
16843                                                            << CallerTCB;
16844         }
16845       });
16846 }
16847