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   case PPC::BI__builtin_altivec_vcntmbb:
3477   case PPC::BI__builtin_altivec_vcntmbh:
3478   case PPC::BI__builtin_altivec_vcntmbw:
3479   case PPC::BI__builtin_altivec_vcntmbd:
3480     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3481 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3482   case PPC::BI__builtin_##Name: \
3483     return SemaBuiltinPPCMMACall(TheCall, Types);
3484 #include "clang/Basic/BuiltinsPPC.def"
3485   }
3486   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3487 }
3488 
3489 // Check if the given type is a non-pointer PPC MMA type. This function is used
3490 // in Sema to prevent invalid uses of restricted PPC MMA types.
3491 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3492   if (Type->isPointerType() || Type->isArrayType())
3493     return false;
3494 
3495   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3496 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3497   if (false
3498 #include "clang/Basic/PPCTypes.def"
3499      ) {
3500     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3501     return true;
3502   }
3503   return false;
3504 }
3505 
3506 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3507                                           CallExpr *TheCall) {
3508   // position of memory order and scope arguments in the builtin
3509   unsigned OrderIndex, ScopeIndex;
3510   switch (BuiltinID) {
3511   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3512   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3513   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3514   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3515     OrderIndex = 2;
3516     ScopeIndex = 3;
3517     break;
3518   case AMDGPU::BI__builtin_amdgcn_fence:
3519     OrderIndex = 0;
3520     ScopeIndex = 1;
3521     break;
3522   default:
3523     return false;
3524   }
3525 
3526   ExprResult Arg = TheCall->getArg(OrderIndex);
3527   auto ArgExpr = Arg.get();
3528   Expr::EvalResult ArgResult;
3529 
3530   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3531     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3532            << ArgExpr->getType();
3533   auto Ord = ArgResult.Val.getInt().getZExtValue();
3534 
3535   // Check validity of memory ordering as per C11 / C++11's memody model.
3536   // Only fence needs check. Atomic dec/inc allow all memory orders.
3537   if (!llvm::isValidAtomicOrderingCABI(Ord))
3538     return Diag(ArgExpr->getBeginLoc(),
3539                 diag::warn_atomic_op_has_invalid_memory_order)
3540            << ArgExpr->getSourceRange();
3541   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3542   case llvm::AtomicOrderingCABI::relaxed:
3543   case llvm::AtomicOrderingCABI::consume:
3544     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3545       return Diag(ArgExpr->getBeginLoc(),
3546                   diag::warn_atomic_op_has_invalid_memory_order)
3547              << ArgExpr->getSourceRange();
3548     break;
3549   case llvm::AtomicOrderingCABI::acquire:
3550   case llvm::AtomicOrderingCABI::release:
3551   case llvm::AtomicOrderingCABI::acq_rel:
3552   case llvm::AtomicOrderingCABI::seq_cst:
3553     break;
3554   }
3555 
3556   Arg = TheCall->getArg(ScopeIndex);
3557   ArgExpr = Arg.get();
3558   Expr::EvalResult ArgResult1;
3559   // Check that sync scope is a constant literal
3560   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3561     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3562            << ArgExpr->getType();
3563 
3564   return false;
3565 }
3566 
3567 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3568   llvm::APSInt Result;
3569 
3570   // We can't check the value of a dependent argument.
3571   Expr *Arg = TheCall->getArg(ArgNum);
3572   if (Arg->isTypeDependent() || Arg->isValueDependent())
3573     return false;
3574 
3575   // Check constant-ness first.
3576   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3577     return true;
3578 
3579   int64_t Val = Result.getSExtValue();
3580   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3581     return false;
3582 
3583   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3584          << Arg->getSourceRange();
3585 }
3586 
3587 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3588                                          unsigned BuiltinID,
3589                                          CallExpr *TheCall) {
3590   // CodeGenFunction can also detect this, but this gives a better error
3591   // message.
3592   bool FeatureMissing = false;
3593   SmallVector<StringRef> ReqFeatures;
3594   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3595   Features.split(ReqFeatures, ',');
3596 
3597   // Check if each required feature is included
3598   for (StringRef F : ReqFeatures) {
3599     if (TI.hasFeature(F))
3600       continue;
3601 
3602     // If the feature is 64bit, alter the string so it will print better in
3603     // the diagnostic.
3604     if (F == "64bit")
3605       F = "RV64";
3606 
3607     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3608     F.consume_front("experimental-");
3609     std::string FeatureStr = F.str();
3610     FeatureStr[0] = std::toupper(FeatureStr[0]);
3611 
3612     // Error message
3613     FeatureMissing = true;
3614     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3615         << TheCall->getSourceRange() << StringRef(FeatureStr);
3616   }
3617 
3618   if (FeatureMissing)
3619     return true;
3620 
3621   switch (BuiltinID) {
3622   case RISCV::BI__builtin_rvv_vsetvli:
3623     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3624            CheckRISCVLMUL(TheCall, 2);
3625   case RISCV::BI__builtin_rvv_vsetvlimax:
3626     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3627            CheckRISCVLMUL(TheCall, 1);
3628   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3629   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3630   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3631   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3632   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3633   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3634   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3635   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3636   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3637   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3638   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3639   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3640   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3641   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3642   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3643   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3644   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3645   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3646   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3647   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3648   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3649   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3650   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3651   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3652   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3653   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3654   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3655   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3656   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3657   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3658     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3659   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3660   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3661   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3662   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3663   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3664   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3665   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3666   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3667   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3668   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3669   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3670   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3671   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3672   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3673   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3674   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3675   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3676   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3677   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3678   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3679     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3680   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3681   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3682   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3683   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3684   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3685   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3686   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3687   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3688   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3689   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3690     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3691   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3692   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3693   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3694   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3695   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3696   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3697   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3698   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3699   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3700   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3701   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3702   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3703   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3704   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3705   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3706   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3707   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3708   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3709   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3710   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3711   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3712   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3713   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3714   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3715   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3716   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3717   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3718   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3719   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3720   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3721     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3722   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3723   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3724   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3725   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3726   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3727   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3728   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3729   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3730   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3731   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3732   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3733   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3734   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3735   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3736   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3737   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3738   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3739   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3740   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3741   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3742     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3743   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3744   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3745   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3746   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3747   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3748   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3749   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3750   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3751   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3752   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3753     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3754   }
3755 
3756   return false;
3757 }
3758 
3759 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3760                                            CallExpr *TheCall) {
3761   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3762     Expr *Arg = TheCall->getArg(0);
3763     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3764       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3765         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3766                << Arg->getSourceRange();
3767   }
3768 
3769   // For intrinsics which take an immediate value as part of the instruction,
3770   // range check them here.
3771   unsigned i = 0, l = 0, u = 0;
3772   switch (BuiltinID) {
3773   default: return false;
3774   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3775   case SystemZ::BI__builtin_s390_verimb:
3776   case SystemZ::BI__builtin_s390_verimh:
3777   case SystemZ::BI__builtin_s390_verimf:
3778   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3779   case SystemZ::BI__builtin_s390_vfaeb:
3780   case SystemZ::BI__builtin_s390_vfaeh:
3781   case SystemZ::BI__builtin_s390_vfaef:
3782   case SystemZ::BI__builtin_s390_vfaebs:
3783   case SystemZ::BI__builtin_s390_vfaehs:
3784   case SystemZ::BI__builtin_s390_vfaefs:
3785   case SystemZ::BI__builtin_s390_vfaezb:
3786   case SystemZ::BI__builtin_s390_vfaezh:
3787   case SystemZ::BI__builtin_s390_vfaezf:
3788   case SystemZ::BI__builtin_s390_vfaezbs:
3789   case SystemZ::BI__builtin_s390_vfaezhs:
3790   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3791   case SystemZ::BI__builtin_s390_vfisb:
3792   case SystemZ::BI__builtin_s390_vfidb:
3793     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3794            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3795   case SystemZ::BI__builtin_s390_vftcisb:
3796   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3797   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3798   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3799   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3800   case SystemZ::BI__builtin_s390_vstrcb:
3801   case SystemZ::BI__builtin_s390_vstrch:
3802   case SystemZ::BI__builtin_s390_vstrcf:
3803   case SystemZ::BI__builtin_s390_vstrczb:
3804   case SystemZ::BI__builtin_s390_vstrczh:
3805   case SystemZ::BI__builtin_s390_vstrczf:
3806   case SystemZ::BI__builtin_s390_vstrcbs:
3807   case SystemZ::BI__builtin_s390_vstrchs:
3808   case SystemZ::BI__builtin_s390_vstrcfs:
3809   case SystemZ::BI__builtin_s390_vstrczbs:
3810   case SystemZ::BI__builtin_s390_vstrczhs:
3811   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3812   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3813   case SystemZ::BI__builtin_s390_vfminsb:
3814   case SystemZ::BI__builtin_s390_vfmaxsb:
3815   case SystemZ::BI__builtin_s390_vfmindb:
3816   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3817   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3818   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3819   case SystemZ::BI__builtin_s390_vclfnhs:
3820   case SystemZ::BI__builtin_s390_vclfnls:
3821   case SystemZ::BI__builtin_s390_vcfn:
3822   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3823   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3824   }
3825   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3826 }
3827 
3828 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3829 /// This checks that the target supports __builtin_cpu_supports and
3830 /// that the string argument is constant and valid.
3831 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3832                                    CallExpr *TheCall) {
3833   Expr *Arg = TheCall->getArg(0);
3834 
3835   // Check if the argument is a string literal.
3836   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3837     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3838            << Arg->getSourceRange();
3839 
3840   // Check the contents of the string.
3841   StringRef Feature =
3842       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3843   if (!TI.validateCpuSupports(Feature))
3844     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3845            << Arg->getSourceRange();
3846   return false;
3847 }
3848 
3849 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3850 /// This checks that the target supports __builtin_cpu_is and
3851 /// that the string argument is constant and valid.
3852 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3853   Expr *Arg = TheCall->getArg(0);
3854 
3855   // Check if the argument is a string literal.
3856   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3857     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3858            << Arg->getSourceRange();
3859 
3860   // Check the contents of the string.
3861   StringRef Feature =
3862       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3863   if (!TI.validateCpuIs(Feature))
3864     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3865            << Arg->getSourceRange();
3866   return false;
3867 }
3868 
3869 // Check if the rounding mode is legal.
3870 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3871   // Indicates if this instruction has rounding control or just SAE.
3872   bool HasRC = false;
3873 
3874   unsigned ArgNum = 0;
3875   switch (BuiltinID) {
3876   default:
3877     return false;
3878   case X86::BI__builtin_ia32_vcvttsd2si32:
3879   case X86::BI__builtin_ia32_vcvttsd2si64:
3880   case X86::BI__builtin_ia32_vcvttsd2usi32:
3881   case X86::BI__builtin_ia32_vcvttsd2usi64:
3882   case X86::BI__builtin_ia32_vcvttss2si32:
3883   case X86::BI__builtin_ia32_vcvttss2si64:
3884   case X86::BI__builtin_ia32_vcvttss2usi32:
3885   case X86::BI__builtin_ia32_vcvttss2usi64:
3886   case X86::BI__builtin_ia32_vcvttsh2si32:
3887   case X86::BI__builtin_ia32_vcvttsh2si64:
3888   case X86::BI__builtin_ia32_vcvttsh2usi32:
3889   case X86::BI__builtin_ia32_vcvttsh2usi64:
3890     ArgNum = 1;
3891     break;
3892   case X86::BI__builtin_ia32_maxpd512:
3893   case X86::BI__builtin_ia32_maxps512:
3894   case X86::BI__builtin_ia32_minpd512:
3895   case X86::BI__builtin_ia32_minps512:
3896   case X86::BI__builtin_ia32_maxph512:
3897   case X86::BI__builtin_ia32_minph512:
3898     ArgNum = 2;
3899     break;
3900   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3901   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3902   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3903   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3904   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3905   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3906   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3907   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3908   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3909   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3910   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3911   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3912   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3913   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3914   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3915   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3916   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3917   case X86::BI__builtin_ia32_exp2pd_mask:
3918   case X86::BI__builtin_ia32_exp2ps_mask:
3919   case X86::BI__builtin_ia32_getexppd512_mask:
3920   case X86::BI__builtin_ia32_getexpps512_mask:
3921   case X86::BI__builtin_ia32_getexpph512_mask:
3922   case X86::BI__builtin_ia32_rcp28pd_mask:
3923   case X86::BI__builtin_ia32_rcp28ps_mask:
3924   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3925   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3926   case X86::BI__builtin_ia32_vcomisd:
3927   case X86::BI__builtin_ia32_vcomiss:
3928   case X86::BI__builtin_ia32_vcomish:
3929   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3930     ArgNum = 3;
3931     break;
3932   case X86::BI__builtin_ia32_cmppd512_mask:
3933   case X86::BI__builtin_ia32_cmpps512_mask:
3934   case X86::BI__builtin_ia32_cmpsd_mask:
3935   case X86::BI__builtin_ia32_cmpss_mask:
3936   case X86::BI__builtin_ia32_cmpsh_mask:
3937   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3938   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3939   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3940   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3941   case X86::BI__builtin_ia32_getexpss128_round_mask:
3942   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3943   case X86::BI__builtin_ia32_getmantpd512_mask:
3944   case X86::BI__builtin_ia32_getmantps512_mask:
3945   case X86::BI__builtin_ia32_getmantph512_mask:
3946   case X86::BI__builtin_ia32_maxsd_round_mask:
3947   case X86::BI__builtin_ia32_maxss_round_mask:
3948   case X86::BI__builtin_ia32_maxsh_round_mask:
3949   case X86::BI__builtin_ia32_minsd_round_mask:
3950   case X86::BI__builtin_ia32_minss_round_mask:
3951   case X86::BI__builtin_ia32_minsh_round_mask:
3952   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3953   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3954   case X86::BI__builtin_ia32_reducepd512_mask:
3955   case X86::BI__builtin_ia32_reduceps512_mask:
3956   case X86::BI__builtin_ia32_reduceph512_mask:
3957   case X86::BI__builtin_ia32_rndscalepd_mask:
3958   case X86::BI__builtin_ia32_rndscaleps_mask:
3959   case X86::BI__builtin_ia32_rndscaleph_mask:
3960   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3961   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3962     ArgNum = 4;
3963     break;
3964   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3965   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3966   case X86::BI__builtin_ia32_fixupimmps512_mask:
3967   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3968   case X86::BI__builtin_ia32_fixupimmsd_mask:
3969   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3970   case X86::BI__builtin_ia32_fixupimmss_mask:
3971   case X86::BI__builtin_ia32_fixupimmss_maskz:
3972   case X86::BI__builtin_ia32_getmantsd_round_mask:
3973   case X86::BI__builtin_ia32_getmantss_round_mask:
3974   case X86::BI__builtin_ia32_getmantsh_round_mask:
3975   case X86::BI__builtin_ia32_rangepd512_mask:
3976   case X86::BI__builtin_ia32_rangeps512_mask:
3977   case X86::BI__builtin_ia32_rangesd128_round_mask:
3978   case X86::BI__builtin_ia32_rangess128_round_mask:
3979   case X86::BI__builtin_ia32_reducesd_mask:
3980   case X86::BI__builtin_ia32_reducess_mask:
3981   case X86::BI__builtin_ia32_reducesh_mask:
3982   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3983   case X86::BI__builtin_ia32_rndscaless_round_mask:
3984   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3985     ArgNum = 5;
3986     break;
3987   case X86::BI__builtin_ia32_vcvtsd2si64:
3988   case X86::BI__builtin_ia32_vcvtsd2si32:
3989   case X86::BI__builtin_ia32_vcvtsd2usi32:
3990   case X86::BI__builtin_ia32_vcvtsd2usi64:
3991   case X86::BI__builtin_ia32_vcvtss2si32:
3992   case X86::BI__builtin_ia32_vcvtss2si64:
3993   case X86::BI__builtin_ia32_vcvtss2usi32:
3994   case X86::BI__builtin_ia32_vcvtss2usi64:
3995   case X86::BI__builtin_ia32_vcvtsh2si32:
3996   case X86::BI__builtin_ia32_vcvtsh2si64:
3997   case X86::BI__builtin_ia32_vcvtsh2usi32:
3998   case X86::BI__builtin_ia32_vcvtsh2usi64:
3999   case X86::BI__builtin_ia32_sqrtpd512:
4000   case X86::BI__builtin_ia32_sqrtps512:
4001   case X86::BI__builtin_ia32_sqrtph512:
4002     ArgNum = 1;
4003     HasRC = true;
4004     break;
4005   case X86::BI__builtin_ia32_addph512:
4006   case X86::BI__builtin_ia32_divph512:
4007   case X86::BI__builtin_ia32_mulph512:
4008   case X86::BI__builtin_ia32_subph512:
4009   case X86::BI__builtin_ia32_addpd512:
4010   case X86::BI__builtin_ia32_addps512:
4011   case X86::BI__builtin_ia32_divpd512:
4012   case X86::BI__builtin_ia32_divps512:
4013   case X86::BI__builtin_ia32_mulpd512:
4014   case X86::BI__builtin_ia32_mulps512:
4015   case X86::BI__builtin_ia32_subpd512:
4016   case X86::BI__builtin_ia32_subps512:
4017   case X86::BI__builtin_ia32_cvtsi2sd64:
4018   case X86::BI__builtin_ia32_cvtsi2ss32:
4019   case X86::BI__builtin_ia32_cvtsi2ss64:
4020   case X86::BI__builtin_ia32_cvtusi2sd64:
4021   case X86::BI__builtin_ia32_cvtusi2ss32:
4022   case X86::BI__builtin_ia32_cvtusi2ss64:
4023   case X86::BI__builtin_ia32_vcvtusi2sh:
4024   case X86::BI__builtin_ia32_vcvtusi642sh:
4025   case X86::BI__builtin_ia32_vcvtsi2sh:
4026   case X86::BI__builtin_ia32_vcvtsi642sh:
4027     ArgNum = 2;
4028     HasRC = true;
4029     break;
4030   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4031   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4032   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4033   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4034   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4035   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4036   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4037   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4038   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4039   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4040   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4041   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4042   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4043   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4044   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4045   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4046   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4047   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4048   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4049   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4050   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4051   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4052   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4053   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4054   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4055   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4056   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4057   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4058   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4059     ArgNum = 3;
4060     HasRC = true;
4061     break;
4062   case X86::BI__builtin_ia32_addsh_round_mask:
4063   case X86::BI__builtin_ia32_addss_round_mask:
4064   case X86::BI__builtin_ia32_addsd_round_mask:
4065   case X86::BI__builtin_ia32_divsh_round_mask:
4066   case X86::BI__builtin_ia32_divss_round_mask:
4067   case X86::BI__builtin_ia32_divsd_round_mask:
4068   case X86::BI__builtin_ia32_mulsh_round_mask:
4069   case X86::BI__builtin_ia32_mulss_round_mask:
4070   case X86::BI__builtin_ia32_mulsd_round_mask:
4071   case X86::BI__builtin_ia32_subsh_round_mask:
4072   case X86::BI__builtin_ia32_subss_round_mask:
4073   case X86::BI__builtin_ia32_subsd_round_mask:
4074   case X86::BI__builtin_ia32_scalefph512_mask:
4075   case X86::BI__builtin_ia32_scalefpd512_mask:
4076   case X86::BI__builtin_ia32_scalefps512_mask:
4077   case X86::BI__builtin_ia32_scalefsd_round_mask:
4078   case X86::BI__builtin_ia32_scalefss_round_mask:
4079   case X86::BI__builtin_ia32_scalefsh_round_mask:
4080   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4081   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4082   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4083   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4084   case X86::BI__builtin_ia32_sqrtss_round_mask:
4085   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4086   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4087   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4088   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4089   case X86::BI__builtin_ia32_vfmaddss3_mask:
4090   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4091   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4092   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4093   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4094   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4095   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4096   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4097   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4098   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4099   case X86::BI__builtin_ia32_vfmaddps512_mask:
4100   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4101   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4102   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4103   case X86::BI__builtin_ia32_vfmaddph512_mask:
4104   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4105   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4106   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4107   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4108   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4109   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4110   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4111   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4112   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4113   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4114   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4115   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4116   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4117   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4118   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4119   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4120   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4121   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4122   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4123   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4124   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4125   case X86::BI__builtin_ia32_vfmulcsh_mask:
4126   case X86::BI__builtin_ia32_vfmulcph512_mask:
4127   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4128   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4129     ArgNum = 4;
4130     HasRC = true;
4131     break;
4132   }
4133 
4134   llvm::APSInt Result;
4135 
4136   // We can't check the value of a dependent argument.
4137   Expr *Arg = TheCall->getArg(ArgNum);
4138   if (Arg->isTypeDependent() || Arg->isValueDependent())
4139     return false;
4140 
4141   // Check constant-ness first.
4142   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4143     return true;
4144 
4145   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4146   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4147   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4148   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4149   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4150       Result == 8/*ROUND_NO_EXC*/ ||
4151       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4152       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4153     return false;
4154 
4155   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4156          << Arg->getSourceRange();
4157 }
4158 
4159 // Check if the gather/scatter scale is legal.
4160 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4161                                              CallExpr *TheCall) {
4162   unsigned ArgNum = 0;
4163   switch (BuiltinID) {
4164   default:
4165     return false;
4166   case X86::BI__builtin_ia32_gatherpfdpd:
4167   case X86::BI__builtin_ia32_gatherpfdps:
4168   case X86::BI__builtin_ia32_gatherpfqpd:
4169   case X86::BI__builtin_ia32_gatherpfqps:
4170   case X86::BI__builtin_ia32_scatterpfdpd:
4171   case X86::BI__builtin_ia32_scatterpfdps:
4172   case X86::BI__builtin_ia32_scatterpfqpd:
4173   case X86::BI__builtin_ia32_scatterpfqps:
4174     ArgNum = 3;
4175     break;
4176   case X86::BI__builtin_ia32_gatherd_pd:
4177   case X86::BI__builtin_ia32_gatherd_pd256:
4178   case X86::BI__builtin_ia32_gatherq_pd:
4179   case X86::BI__builtin_ia32_gatherq_pd256:
4180   case X86::BI__builtin_ia32_gatherd_ps:
4181   case X86::BI__builtin_ia32_gatherd_ps256:
4182   case X86::BI__builtin_ia32_gatherq_ps:
4183   case X86::BI__builtin_ia32_gatherq_ps256:
4184   case X86::BI__builtin_ia32_gatherd_q:
4185   case X86::BI__builtin_ia32_gatherd_q256:
4186   case X86::BI__builtin_ia32_gatherq_q:
4187   case X86::BI__builtin_ia32_gatherq_q256:
4188   case X86::BI__builtin_ia32_gatherd_d:
4189   case X86::BI__builtin_ia32_gatherd_d256:
4190   case X86::BI__builtin_ia32_gatherq_d:
4191   case X86::BI__builtin_ia32_gatherq_d256:
4192   case X86::BI__builtin_ia32_gather3div2df:
4193   case X86::BI__builtin_ia32_gather3div2di:
4194   case X86::BI__builtin_ia32_gather3div4df:
4195   case X86::BI__builtin_ia32_gather3div4di:
4196   case X86::BI__builtin_ia32_gather3div4sf:
4197   case X86::BI__builtin_ia32_gather3div4si:
4198   case X86::BI__builtin_ia32_gather3div8sf:
4199   case X86::BI__builtin_ia32_gather3div8si:
4200   case X86::BI__builtin_ia32_gather3siv2df:
4201   case X86::BI__builtin_ia32_gather3siv2di:
4202   case X86::BI__builtin_ia32_gather3siv4df:
4203   case X86::BI__builtin_ia32_gather3siv4di:
4204   case X86::BI__builtin_ia32_gather3siv4sf:
4205   case X86::BI__builtin_ia32_gather3siv4si:
4206   case X86::BI__builtin_ia32_gather3siv8sf:
4207   case X86::BI__builtin_ia32_gather3siv8si:
4208   case X86::BI__builtin_ia32_gathersiv8df:
4209   case X86::BI__builtin_ia32_gathersiv16sf:
4210   case X86::BI__builtin_ia32_gatherdiv8df:
4211   case X86::BI__builtin_ia32_gatherdiv16sf:
4212   case X86::BI__builtin_ia32_gathersiv8di:
4213   case X86::BI__builtin_ia32_gathersiv16si:
4214   case X86::BI__builtin_ia32_gatherdiv8di:
4215   case X86::BI__builtin_ia32_gatherdiv16si:
4216   case X86::BI__builtin_ia32_scatterdiv2df:
4217   case X86::BI__builtin_ia32_scatterdiv2di:
4218   case X86::BI__builtin_ia32_scatterdiv4df:
4219   case X86::BI__builtin_ia32_scatterdiv4di:
4220   case X86::BI__builtin_ia32_scatterdiv4sf:
4221   case X86::BI__builtin_ia32_scatterdiv4si:
4222   case X86::BI__builtin_ia32_scatterdiv8sf:
4223   case X86::BI__builtin_ia32_scatterdiv8si:
4224   case X86::BI__builtin_ia32_scattersiv2df:
4225   case X86::BI__builtin_ia32_scattersiv2di:
4226   case X86::BI__builtin_ia32_scattersiv4df:
4227   case X86::BI__builtin_ia32_scattersiv4di:
4228   case X86::BI__builtin_ia32_scattersiv4sf:
4229   case X86::BI__builtin_ia32_scattersiv4si:
4230   case X86::BI__builtin_ia32_scattersiv8sf:
4231   case X86::BI__builtin_ia32_scattersiv8si:
4232   case X86::BI__builtin_ia32_scattersiv8df:
4233   case X86::BI__builtin_ia32_scattersiv16sf:
4234   case X86::BI__builtin_ia32_scatterdiv8df:
4235   case X86::BI__builtin_ia32_scatterdiv16sf:
4236   case X86::BI__builtin_ia32_scattersiv8di:
4237   case X86::BI__builtin_ia32_scattersiv16si:
4238   case X86::BI__builtin_ia32_scatterdiv8di:
4239   case X86::BI__builtin_ia32_scatterdiv16si:
4240     ArgNum = 4;
4241     break;
4242   }
4243 
4244   llvm::APSInt Result;
4245 
4246   // We can't check the value of a dependent argument.
4247   Expr *Arg = TheCall->getArg(ArgNum);
4248   if (Arg->isTypeDependent() || Arg->isValueDependent())
4249     return false;
4250 
4251   // Check constant-ness first.
4252   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4253     return true;
4254 
4255   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4256     return false;
4257 
4258   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4259          << Arg->getSourceRange();
4260 }
4261 
4262 enum { TileRegLow = 0, TileRegHigh = 7 };
4263 
4264 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4265                                              ArrayRef<int> ArgNums) {
4266   for (int ArgNum : ArgNums) {
4267     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4268       return true;
4269   }
4270   return false;
4271 }
4272 
4273 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4274                                         ArrayRef<int> ArgNums) {
4275   // Because the max number of tile register is TileRegHigh + 1, so here we use
4276   // each bit to represent the usage of them in bitset.
4277   std::bitset<TileRegHigh + 1> ArgValues;
4278   for (int ArgNum : ArgNums) {
4279     Expr *Arg = TheCall->getArg(ArgNum);
4280     if (Arg->isTypeDependent() || Arg->isValueDependent())
4281       continue;
4282 
4283     llvm::APSInt Result;
4284     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4285       return true;
4286     int ArgExtValue = Result.getExtValue();
4287     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4288            "Incorrect tile register num.");
4289     if (ArgValues.test(ArgExtValue))
4290       return Diag(TheCall->getBeginLoc(),
4291                   diag::err_x86_builtin_tile_arg_duplicate)
4292              << TheCall->getArg(ArgNum)->getSourceRange();
4293     ArgValues.set(ArgExtValue);
4294   }
4295   return false;
4296 }
4297 
4298 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4299                                                 ArrayRef<int> ArgNums) {
4300   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4301          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4302 }
4303 
4304 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4305   switch (BuiltinID) {
4306   default:
4307     return false;
4308   case X86::BI__builtin_ia32_tileloadd64:
4309   case X86::BI__builtin_ia32_tileloaddt164:
4310   case X86::BI__builtin_ia32_tilestored64:
4311   case X86::BI__builtin_ia32_tilezero:
4312     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4313   case X86::BI__builtin_ia32_tdpbssd:
4314   case X86::BI__builtin_ia32_tdpbsud:
4315   case X86::BI__builtin_ia32_tdpbusd:
4316   case X86::BI__builtin_ia32_tdpbuud:
4317   case X86::BI__builtin_ia32_tdpbf16ps:
4318     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4319   }
4320 }
4321 static bool isX86_32Builtin(unsigned BuiltinID) {
4322   // These builtins only work on x86-32 targets.
4323   switch (BuiltinID) {
4324   case X86::BI__builtin_ia32_readeflags_u32:
4325   case X86::BI__builtin_ia32_writeeflags_u32:
4326     return true;
4327   }
4328 
4329   return false;
4330 }
4331 
4332 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4333                                        CallExpr *TheCall) {
4334   if (BuiltinID == X86::BI__builtin_cpu_supports)
4335     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4336 
4337   if (BuiltinID == X86::BI__builtin_cpu_is)
4338     return SemaBuiltinCpuIs(*this, TI, TheCall);
4339 
4340   // Check for 32-bit only builtins on a 64-bit target.
4341   const llvm::Triple &TT = TI.getTriple();
4342   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4343     return Diag(TheCall->getCallee()->getBeginLoc(),
4344                 diag::err_32_bit_builtin_64_bit_tgt);
4345 
4346   // If the intrinsic has rounding or SAE make sure its valid.
4347   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4348     return true;
4349 
4350   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4351   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4352     return true;
4353 
4354   // If the intrinsic has a tile arguments, make sure they are valid.
4355   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4356     return true;
4357 
4358   // For intrinsics which take an immediate value as part of the instruction,
4359   // range check them here.
4360   int i = 0, l = 0, u = 0;
4361   switch (BuiltinID) {
4362   default:
4363     return false;
4364   case X86::BI__builtin_ia32_vec_ext_v2si:
4365   case X86::BI__builtin_ia32_vec_ext_v2di:
4366   case X86::BI__builtin_ia32_vextractf128_pd256:
4367   case X86::BI__builtin_ia32_vextractf128_ps256:
4368   case X86::BI__builtin_ia32_vextractf128_si256:
4369   case X86::BI__builtin_ia32_extract128i256:
4370   case X86::BI__builtin_ia32_extractf64x4_mask:
4371   case X86::BI__builtin_ia32_extracti64x4_mask:
4372   case X86::BI__builtin_ia32_extractf32x8_mask:
4373   case X86::BI__builtin_ia32_extracti32x8_mask:
4374   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4375   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4376   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4377   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4378     i = 1; l = 0; u = 1;
4379     break;
4380   case X86::BI__builtin_ia32_vec_set_v2di:
4381   case X86::BI__builtin_ia32_vinsertf128_pd256:
4382   case X86::BI__builtin_ia32_vinsertf128_ps256:
4383   case X86::BI__builtin_ia32_vinsertf128_si256:
4384   case X86::BI__builtin_ia32_insert128i256:
4385   case X86::BI__builtin_ia32_insertf32x8:
4386   case X86::BI__builtin_ia32_inserti32x8:
4387   case X86::BI__builtin_ia32_insertf64x4:
4388   case X86::BI__builtin_ia32_inserti64x4:
4389   case X86::BI__builtin_ia32_insertf64x2_256:
4390   case X86::BI__builtin_ia32_inserti64x2_256:
4391   case X86::BI__builtin_ia32_insertf32x4_256:
4392   case X86::BI__builtin_ia32_inserti32x4_256:
4393     i = 2; l = 0; u = 1;
4394     break;
4395   case X86::BI__builtin_ia32_vpermilpd:
4396   case X86::BI__builtin_ia32_vec_ext_v4hi:
4397   case X86::BI__builtin_ia32_vec_ext_v4si:
4398   case X86::BI__builtin_ia32_vec_ext_v4sf:
4399   case X86::BI__builtin_ia32_vec_ext_v4di:
4400   case X86::BI__builtin_ia32_extractf32x4_mask:
4401   case X86::BI__builtin_ia32_extracti32x4_mask:
4402   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4403   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4404     i = 1; l = 0; u = 3;
4405     break;
4406   case X86::BI_mm_prefetch:
4407   case X86::BI__builtin_ia32_vec_ext_v8hi:
4408   case X86::BI__builtin_ia32_vec_ext_v8si:
4409     i = 1; l = 0; u = 7;
4410     break;
4411   case X86::BI__builtin_ia32_sha1rnds4:
4412   case X86::BI__builtin_ia32_blendpd:
4413   case X86::BI__builtin_ia32_shufpd:
4414   case X86::BI__builtin_ia32_vec_set_v4hi:
4415   case X86::BI__builtin_ia32_vec_set_v4si:
4416   case X86::BI__builtin_ia32_vec_set_v4di:
4417   case X86::BI__builtin_ia32_shuf_f32x4_256:
4418   case X86::BI__builtin_ia32_shuf_f64x2_256:
4419   case X86::BI__builtin_ia32_shuf_i32x4_256:
4420   case X86::BI__builtin_ia32_shuf_i64x2_256:
4421   case X86::BI__builtin_ia32_insertf64x2_512:
4422   case X86::BI__builtin_ia32_inserti64x2_512:
4423   case X86::BI__builtin_ia32_insertf32x4:
4424   case X86::BI__builtin_ia32_inserti32x4:
4425     i = 2; l = 0; u = 3;
4426     break;
4427   case X86::BI__builtin_ia32_vpermil2pd:
4428   case X86::BI__builtin_ia32_vpermil2pd256:
4429   case X86::BI__builtin_ia32_vpermil2ps:
4430   case X86::BI__builtin_ia32_vpermil2ps256:
4431     i = 3; l = 0; u = 3;
4432     break;
4433   case X86::BI__builtin_ia32_cmpb128_mask:
4434   case X86::BI__builtin_ia32_cmpw128_mask:
4435   case X86::BI__builtin_ia32_cmpd128_mask:
4436   case X86::BI__builtin_ia32_cmpq128_mask:
4437   case X86::BI__builtin_ia32_cmpb256_mask:
4438   case X86::BI__builtin_ia32_cmpw256_mask:
4439   case X86::BI__builtin_ia32_cmpd256_mask:
4440   case X86::BI__builtin_ia32_cmpq256_mask:
4441   case X86::BI__builtin_ia32_cmpb512_mask:
4442   case X86::BI__builtin_ia32_cmpw512_mask:
4443   case X86::BI__builtin_ia32_cmpd512_mask:
4444   case X86::BI__builtin_ia32_cmpq512_mask:
4445   case X86::BI__builtin_ia32_ucmpb128_mask:
4446   case X86::BI__builtin_ia32_ucmpw128_mask:
4447   case X86::BI__builtin_ia32_ucmpd128_mask:
4448   case X86::BI__builtin_ia32_ucmpq128_mask:
4449   case X86::BI__builtin_ia32_ucmpb256_mask:
4450   case X86::BI__builtin_ia32_ucmpw256_mask:
4451   case X86::BI__builtin_ia32_ucmpd256_mask:
4452   case X86::BI__builtin_ia32_ucmpq256_mask:
4453   case X86::BI__builtin_ia32_ucmpb512_mask:
4454   case X86::BI__builtin_ia32_ucmpw512_mask:
4455   case X86::BI__builtin_ia32_ucmpd512_mask:
4456   case X86::BI__builtin_ia32_ucmpq512_mask:
4457   case X86::BI__builtin_ia32_vpcomub:
4458   case X86::BI__builtin_ia32_vpcomuw:
4459   case X86::BI__builtin_ia32_vpcomud:
4460   case X86::BI__builtin_ia32_vpcomuq:
4461   case X86::BI__builtin_ia32_vpcomb:
4462   case X86::BI__builtin_ia32_vpcomw:
4463   case X86::BI__builtin_ia32_vpcomd:
4464   case X86::BI__builtin_ia32_vpcomq:
4465   case X86::BI__builtin_ia32_vec_set_v8hi:
4466   case X86::BI__builtin_ia32_vec_set_v8si:
4467     i = 2; l = 0; u = 7;
4468     break;
4469   case X86::BI__builtin_ia32_vpermilpd256:
4470   case X86::BI__builtin_ia32_roundps:
4471   case X86::BI__builtin_ia32_roundpd:
4472   case X86::BI__builtin_ia32_roundps256:
4473   case X86::BI__builtin_ia32_roundpd256:
4474   case X86::BI__builtin_ia32_getmantpd128_mask:
4475   case X86::BI__builtin_ia32_getmantpd256_mask:
4476   case X86::BI__builtin_ia32_getmantps128_mask:
4477   case X86::BI__builtin_ia32_getmantps256_mask:
4478   case X86::BI__builtin_ia32_getmantpd512_mask:
4479   case X86::BI__builtin_ia32_getmantps512_mask:
4480   case X86::BI__builtin_ia32_getmantph128_mask:
4481   case X86::BI__builtin_ia32_getmantph256_mask:
4482   case X86::BI__builtin_ia32_getmantph512_mask:
4483   case X86::BI__builtin_ia32_vec_ext_v16qi:
4484   case X86::BI__builtin_ia32_vec_ext_v16hi:
4485     i = 1; l = 0; u = 15;
4486     break;
4487   case X86::BI__builtin_ia32_pblendd128:
4488   case X86::BI__builtin_ia32_blendps:
4489   case X86::BI__builtin_ia32_blendpd256:
4490   case X86::BI__builtin_ia32_shufpd256:
4491   case X86::BI__builtin_ia32_roundss:
4492   case X86::BI__builtin_ia32_roundsd:
4493   case X86::BI__builtin_ia32_rangepd128_mask:
4494   case X86::BI__builtin_ia32_rangepd256_mask:
4495   case X86::BI__builtin_ia32_rangepd512_mask:
4496   case X86::BI__builtin_ia32_rangeps128_mask:
4497   case X86::BI__builtin_ia32_rangeps256_mask:
4498   case X86::BI__builtin_ia32_rangeps512_mask:
4499   case X86::BI__builtin_ia32_getmantsd_round_mask:
4500   case X86::BI__builtin_ia32_getmantss_round_mask:
4501   case X86::BI__builtin_ia32_getmantsh_round_mask:
4502   case X86::BI__builtin_ia32_vec_set_v16qi:
4503   case X86::BI__builtin_ia32_vec_set_v16hi:
4504     i = 2; l = 0; u = 15;
4505     break;
4506   case X86::BI__builtin_ia32_vec_ext_v32qi:
4507     i = 1; l = 0; u = 31;
4508     break;
4509   case X86::BI__builtin_ia32_cmpps:
4510   case X86::BI__builtin_ia32_cmpss:
4511   case X86::BI__builtin_ia32_cmppd:
4512   case X86::BI__builtin_ia32_cmpsd:
4513   case X86::BI__builtin_ia32_cmpps256:
4514   case X86::BI__builtin_ia32_cmppd256:
4515   case X86::BI__builtin_ia32_cmpps128_mask:
4516   case X86::BI__builtin_ia32_cmppd128_mask:
4517   case X86::BI__builtin_ia32_cmpps256_mask:
4518   case X86::BI__builtin_ia32_cmppd256_mask:
4519   case X86::BI__builtin_ia32_cmpps512_mask:
4520   case X86::BI__builtin_ia32_cmppd512_mask:
4521   case X86::BI__builtin_ia32_cmpsd_mask:
4522   case X86::BI__builtin_ia32_cmpss_mask:
4523   case X86::BI__builtin_ia32_vec_set_v32qi:
4524     i = 2; l = 0; u = 31;
4525     break;
4526   case X86::BI__builtin_ia32_permdf256:
4527   case X86::BI__builtin_ia32_permdi256:
4528   case X86::BI__builtin_ia32_permdf512:
4529   case X86::BI__builtin_ia32_permdi512:
4530   case X86::BI__builtin_ia32_vpermilps:
4531   case X86::BI__builtin_ia32_vpermilps256:
4532   case X86::BI__builtin_ia32_vpermilpd512:
4533   case X86::BI__builtin_ia32_vpermilps512:
4534   case X86::BI__builtin_ia32_pshufd:
4535   case X86::BI__builtin_ia32_pshufd256:
4536   case X86::BI__builtin_ia32_pshufd512:
4537   case X86::BI__builtin_ia32_pshufhw:
4538   case X86::BI__builtin_ia32_pshufhw256:
4539   case X86::BI__builtin_ia32_pshufhw512:
4540   case X86::BI__builtin_ia32_pshuflw:
4541   case X86::BI__builtin_ia32_pshuflw256:
4542   case X86::BI__builtin_ia32_pshuflw512:
4543   case X86::BI__builtin_ia32_vcvtps2ph:
4544   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4545   case X86::BI__builtin_ia32_vcvtps2ph256:
4546   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4547   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4548   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4549   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4550   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4551   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4552   case X86::BI__builtin_ia32_rndscaleps_mask:
4553   case X86::BI__builtin_ia32_rndscalepd_mask:
4554   case X86::BI__builtin_ia32_rndscaleph_mask:
4555   case X86::BI__builtin_ia32_reducepd128_mask:
4556   case X86::BI__builtin_ia32_reducepd256_mask:
4557   case X86::BI__builtin_ia32_reducepd512_mask:
4558   case X86::BI__builtin_ia32_reduceps128_mask:
4559   case X86::BI__builtin_ia32_reduceps256_mask:
4560   case X86::BI__builtin_ia32_reduceps512_mask:
4561   case X86::BI__builtin_ia32_reduceph128_mask:
4562   case X86::BI__builtin_ia32_reduceph256_mask:
4563   case X86::BI__builtin_ia32_reduceph512_mask:
4564   case X86::BI__builtin_ia32_prold512:
4565   case X86::BI__builtin_ia32_prolq512:
4566   case X86::BI__builtin_ia32_prold128:
4567   case X86::BI__builtin_ia32_prold256:
4568   case X86::BI__builtin_ia32_prolq128:
4569   case X86::BI__builtin_ia32_prolq256:
4570   case X86::BI__builtin_ia32_prord512:
4571   case X86::BI__builtin_ia32_prorq512:
4572   case X86::BI__builtin_ia32_prord128:
4573   case X86::BI__builtin_ia32_prord256:
4574   case X86::BI__builtin_ia32_prorq128:
4575   case X86::BI__builtin_ia32_prorq256:
4576   case X86::BI__builtin_ia32_fpclasspd128_mask:
4577   case X86::BI__builtin_ia32_fpclasspd256_mask:
4578   case X86::BI__builtin_ia32_fpclassps128_mask:
4579   case X86::BI__builtin_ia32_fpclassps256_mask:
4580   case X86::BI__builtin_ia32_fpclassps512_mask:
4581   case X86::BI__builtin_ia32_fpclasspd512_mask:
4582   case X86::BI__builtin_ia32_fpclassph128_mask:
4583   case X86::BI__builtin_ia32_fpclassph256_mask:
4584   case X86::BI__builtin_ia32_fpclassph512_mask:
4585   case X86::BI__builtin_ia32_fpclasssd_mask:
4586   case X86::BI__builtin_ia32_fpclassss_mask:
4587   case X86::BI__builtin_ia32_fpclasssh_mask:
4588   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4589   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4590   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4591   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4592   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4593   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4594   case X86::BI__builtin_ia32_kshiftliqi:
4595   case X86::BI__builtin_ia32_kshiftlihi:
4596   case X86::BI__builtin_ia32_kshiftlisi:
4597   case X86::BI__builtin_ia32_kshiftlidi:
4598   case X86::BI__builtin_ia32_kshiftriqi:
4599   case X86::BI__builtin_ia32_kshiftrihi:
4600   case X86::BI__builtin_ia32_kshiftrisi:
4601   case X86::BI__builtin_ia32_kshiftridi:
4602     i = 1; l = 0; u = 255;
4603     break;
4604   case X86::BI__builtin_ia32_vperm2f128_pd256:
4605   case X86::BI__builtin_ia32_vperm2f128_ps256:
4606   case X86::BI__builtin_ia32_vperm2f128_si256:
4607   case X86::BI__builtin_ia32_permti256:
4608   case X86::BI__builtin_ia32_pblendw128:
4609   case X86::BI__builtin_ia32_pblendw256:
4610   case X86::BI__builtin_ia32_blendps256:
4611   case X86::BI__builtin_ia32_pblendd256:
4612   case X86::BI__builtin_ia32_palignr128:
4613   case X86::BI__builtin_ia32_palignr256:
4614   case X86::BI__builtin_ia32_palignr512:
4615   case X86::BI__builtin_ia32_alignq512:
4616   case X86::BI__builtin_ia32_alignd512:
4617   case X86::BI__builtin_ia32_alignd128:
4618   case X86::BI__builtin_ia32_alignd256:
4619   case X86::BI__builtin_ia32_alignq128:
4620   case X86::BI__builtin_ia32_alignq256:
4621   case X86::BI__builtin_ia32_vcomisd:
4622   case X86::BI__builtin_ia32_vcomiss:
4623   case X86::BI__builtin_ia32_shuf_f32x4:
4624   case X86::BI__builtin_ia32_shuf_f64x2:
4625   case X86::BI__builtin_ia32_shuf_i32x4:
4626   case X86::BI__builtin_ia32_shuf_i64x2:
4627   case X86::BI__builtin_ia32_shufpd512:
4628   case X86::BI__builtin_ia32_shufps:
4629   case X86::BI__builtin_ia32_shufps256:
4630   case X86::BI__builtin_ia32_shufps512:
4631   case X86::BI__builtin_ia32_dbpsadbw128:
4632   case X86::BI__builtin_ia32_dbpsadbw256:
4633   case X86::BI__builtin_ia32_dbpsadbw512:
4634   case X86::BI__builtin_ia32_vpshldd128:
4635   case X86::BI__builtin_ia32_vpshldd256:
4636   case X86::BI__builtin_ia32_vpshldd512:
4637   case X86::BI__builtin_ia32_vpshldq128:
4638   case X86::BI__builtin_ia32_vpshldq256:
4639   case X86::BI__builtin_ia32_vpshldq512:
4640   case X86::BI__builtin_ia32_vpshldw128:
4641   case X86::BI__builtin_ia32_vpshldw256:
4642   case X86::BI__builtin_ia32_vpshldw512:
4643   case X86::BI__builtin_ia32_vpshrdd128:
4644   case X86::BI__builtin_ia32_vpshrdd256:
4645   case X86::BI__builtin_ia32_vpshrdd512:
4646   case X86::BI__builtin_ia32_vpshrdq128:
4647   case X86::BI__builtin_ia32_vpshrdq256:
4648   case X86::BI__builtin_ia32_vpshrdq512:
4649   case X86::BI__builtin_ia32_vpshrdw128:
4650   case X86::BI__builtin_ia32_vpshrdw256:
4651   case X86::BI__builtin_ia32_vpshrdw512:
4652     i = 2; l = 0; u = 255;
4653     break;
4654   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4655   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4656   case X86::BI__builtin_ia32_fixupimmps512_mask:
4657   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4658   case X86::BI__builtin_ia32_fixupimmsd_mask:
4659   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4660   case X86::BI__builtin_ia32_fixupimmss_mask:
4661   case X86::BI__builtin_ia32_fixupimmss_maskz:
4662   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4663   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4664   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4665   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4666   case X86::BI__builtin_ia32_fixupimmps128_mask:
4667   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4668   case X86::BI__builtin_ia32_fixupimmps256_mask:
4669   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4670   case X86::BI__builtin_ia32_pternlogd512_mask:
4671   case X86::BI__builtin_ia32_pternlogd512_maskz:
4672   case X86::BI__builtin_ia32_pternlogq512_mask:
4673   case X86::BI__builtin_ia32_pternlogq512_maskz:
4674   case X86::BI__builtin_ia32_pternlogd128_mask:
4675   case X86::BI__builtin_ia32_pternlogd128_maskz:
4676   case X86::BI__builtin_ia32_pternlogd256_mask:
4677   case X86::BI__builtin_ia32_pternlogd256_maskz:
4678   case X86::BI__builtin_ia32_pternlogq128_mask:
4679   case X86::BI__builtin_ia32_pternlogq128_maskz:
4680   case X86::BI__builtin_ia32_pternlogq256_mask:
4681   case X86::BI__builtin_ia32_pternlogq256_maskz:
4682     i = 3; l = 0; u = 255;
4683     break;
4684   case X86::BI__builtin_ia32_gatherpfdpd:
4685   case X86::BI__builtin_ia32_gatherpfdps:
4686   case X86::BI__builtin_ia32_gatherpfqpd:
4687   case X86::BI__builtin_ia32_gatherpfqps:
4688   case X86::BI__builtin_ia32_scatterpfdpd:
4689   case X86::BI__builtin_ia32_scatterpfdps:
4690   case X86::BI__builtin_ia32_scatterpfqpd:
4691   case X86::BI__builtin_ia32_scatterpfqps:
4692     i = 4; l = 2; u = 3;
4693     break;
4694   case X86::BI__builtin_ia32_reducesd_mask:
4695   case X86::BI__builtin_ia32_reducess_mask:
4696   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4697   case X86::BI__builtin_ia32_rndscaless_round_mask:
4698   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4699   case X86::BI__builtin_ia32_reducesh_mask:
4700     i = 4; l = 0; u = 255;
4701     break;
4702   }
4703 
4704   // Note that we don't force a hard error on the range check here, allowing
4705   // template-generated or macro-generated dead code to potentially have out-of-
4706   // range values. These need to code generate, but don't need to necessarily
4707   // make any sense. We use a warning that defaults to an error.
4708   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4709 }
4710 
4711 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4712 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4713 /// Returns true when the format fits the function and the FormatStringInfo has
4714 /// been populated.
4715 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4716                                FormatStringInfo *FSI) {
4717   FSI->HasVAListArg = Format->getFirstArg() == 0;
4718   FSI->FormatIdx = Format->getFormatIdx() - 1;
4719   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4720 
4721   // The way the format attribute works in GCC, the implicit this argument
4722   // of member functions is counted. However, it doesn't appear in our own
4723   // lists, so decrement format_idx in that case.
4724   if (IsCXXMember) {
4725     if(FSI->FormatIdx == 0)
4726       return false;
4727     --FSI->FormatIdx;
4728     if (FSI->FirstDataArg != 0)
4729       --FSI->FirstDataArg;
4730   }
4731   return true;
4732 }
4733 
4734 /// Checks if a the given expression evaluates to null.
4735 ///
4736 /// Returns true if the value evaluates to null.
4737 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4738   // If the expression has non-null type, it doesn't evaluate to null.
4739   if (auto nullability
4740         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4741     if (*nullability == NullabilityKind::NonNull)
4742       return false;
4743   }
4744 
4745   // As a special case, transparent unions initialized with zero are
4746   // considered null for the purposes of the nonnull attribute.
4747   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4748     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4749       if (const CompoundLiteralExpr *CLE =
4750           dyn_cast<CompoundLiteralExpr>(Expr))
4751         if (const InitListExpr *ILE =
4752             dyn_cast<InitListExpr>(CLE->getInitializer()))
4753           Expr = ILE->getInit(0);
4754   }
4755 
4756   bool Result;
4757   return (!Expr->isValueDependent() &&
4758           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4759           !Result);
4760 }
4761 
4762 static void CheckNonNullArgument(Sema &S,
4763                                  const Expr *ArgExpr,
4764                                  SourceLocation CallSiteLoc) {
4765   if (CheckNonNullExpr(S, ArgExpr))
4766     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4767                           S.PDiag(diag::warn_null_arg)
4768                               << ArgExpr->getSourceRange());
4769 }
4770 
4771 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4772   FormatStringInfo FSI;
4773   if ((GetFormatStringType(Format) == FST_NSString) &&
4774       getFormatStringInfo(Format, false, &FSI)) {
4775     Idx = FSI.FormatIdx;
4776     return true;
4777   }
4778   return false;
4779 }
4780 
4781 /// Diagnose use of %s directive in an NSString which is being passed
4782 /// as formatting string to formatting method.
4783 static void
4784 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4785                                         const NamedDecl *FDecl,
4786                                         Expr **Args,
4787                                         unsigned NumArgs) {
4788   unsigned Idx = 0;
4789   bool Format = false;
4790   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4791   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4792     Idx = 2;
4793     Format = true;
4794   }
4795   else
4796     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4797       if (S.GetFormatNSStringIdx(I, Idx)) {
4798         Format = true;
4799         break;
4800       }
4801     }
4802   if (!Format || NumArgs <= Idx)
4803     return;
4804   const Expr *FormatExpr = Args[Idx];
4805   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4806     FormatExpr = CSCE->getSubExpr();
4807   const StringLiteral *FormatString;
4808   if (const ObjCStringLiteral *OSL =
4809       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4810     FormatString = OSL->getString();
4811   else
4812     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4813   if (!FormatString)
4814     return;
4815   if (S.FormatStringHasSArg(FormatString)) {
4816     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4817       << "%s" << 1 << 1;
4818     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4819       << FDecl->getDeclName();
4820   }
4821 }
4822 
4823 /// Determine whether the given type has a non-null nullability annotation.
4824 static bool isNonNullType(ASTContext &ctx, QualType type) {
4825   if (auto nullability = type->getNullability(ctx))
4826     return *nullability == NullabilityKind::NonNull;
4827 
4828   return false;
4829 }
4830 
4831 static void CheckNonNullArguments(Sema &S,
4832                                   const NamedDecl *FDecl,
4833                                   const FunctionProtoType *Proto,
4834                                   ArrayRef<const Expr *> Args,
4835                                   SourceLocation CallSiteLoc) {
4836   assert((FDecl || Proto) && "Need a function declaration or prototype");
4837 
4838   // Already checked by by constant evaluator.
4839   if (S.isConstantEvaluated())
4840     return;
4841   // Check the attributes attached to the method/function itself.
4842   llvm::SmallBitVector NonNullArgs;
4843   if (FDecl) {
4844     // Handle the nonnull attribute on the function/method declaration itself.
4845     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4846       if (!NonNull->args_size()) {
4847         // Easy case: all pointer arguments are nonnull.
4848         for (const auto *Arg : Args)
4849           if (S.isValidPointerAttrType(Arg->getType()))
4850             CheckNonNullArgument(S, Arg, CallSiteLoc);
4851         return;
4852       }
4853 
4854       for (const ParamIdx &Idx : NonNull->args()) {
4855         unsigned IdxAST = Idx.getASTIndex();
4856         if (IdxAST >= Args.size())
4857           continue;
4858         if (NonNullArgs.empty())
4859           NonNullArgs.resize(Args.size());
4860         NonNullArgs.set(IdxAST);
4861       }
4862     }
4863   }
4864 
4865   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4866     // Handle the nonnull attribute on the parameters of the
4867     // function/method.
4868     ArrayRef<ParmVarDecl*> parms;
4869     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4870       parms = FD->parameters();
4871     else
4872       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4873 
4874     unsigned ParamIndex = 0;
4875     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4876          I != E; ++I, ++ParamIndex) {
4877       const ParmVarDecl *PVD = *I;
4878       if (PVD->hasAttr<NonNullAttr>() ||
4879           isNonNullType(S.Context, PVD->getType())) {
4880         if (NonNullArgs.empty())
4881           NonNullArgs.resize(Args.size());
4882 
4883         NonNullArgs.set(ParamIndex);
4884       }
4885     }
4886   } else {
4887     // If we have a non-function, non-method declaration but no
4888     // function prototype, try to dig out the function prototype.
4889     if (!Proto) {
4890       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4891         QualType type = VD->getType().getNonReferenceType();
4892         if (auto pointerType = type->getAs<PointerType>())
4893           type = pointerType->getPointeeType();
4894         else if (auto blockType = type->getAs<BlockPointerType>())
4895           type = blockType->getPointeeType();
4896         // FIXME: data member pointers?
4897 
4898         // Dig out the function prototype, if there is one.
4899         Proto = type->getAs<FunctionProtoType>();
4900       }
4901     }
4902 
4903     // Fill in non-null argument information from the nullability
4904     // information on the parameter types (if we have them).
4905     if (Proto) {
4906       unsigned Index = 0;
4907       for (auto paramType : Proto->getParamTypes()) {
4908         if (isNonNullType(S.Context, paramType)) {
4909           if (NonNullArgs.empty())
4910             NonNullArgs.resize(Args.size());
4911 
4912           NonNullArgs.set(Index);
4913         }
4914 
4915         ++Index;
4916       }
4917     }
4918   }
4919 
4920   // Check for non-null arguments.
4921   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4922        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4923     if (NonNullArgs[ArgIndex])
4924       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4925   }
4926 }
4927 
4928 /// Warn if a pointer or reference argument passed to a function points to an
4929 /// object that is less aligned than the parameter. This can happen when
4930 /// creating a typedef with a lower alignment than the original type and then
4931 /// calling functions defined in terms of the original type.
4932 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4933                              StringRef ParamName, QualType ArgTy,
4934                              QualType ParamTy) {
4935 
4936   // If a function accepts a pointer or reference type
4937   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4938     return;
4939 
4940   // If the parameter is a pointer type, get the pointee type for the
4941   // argument too. If the parameter is a reference type, don't try to get
4942   // the pointee type for the argument.
4943   if (ParamTy->isPointerType())
4944     ArgTy = ArgTy->getPointeeType();
4945 
4946   // Remove reference or pointer
4947   ParamTy = ParamTy->getPointeeType();
4948 
4949   // Find expected alignment, and the actual alignment of the passed object.
4950   // getTypeAlignInChars requires complete types
4951   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4952       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4953       ArgTy->isUndeducedType())
4954     return;
4955 
4956   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4957   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4958 
4959   // If the argument is less aligned than the parameter, there is a
4960   // potential alignment issue.
4961   if (ArgAlign < ParamAlign)
4962     Diag(Loc, diag::warn_param_mismatched_alignment)
4963         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4964         << ParamName << FDecl;
4965 }
4966 
4967 /// Handles the checks for format strings, non-POD arguments to vararg
4968 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4969 /// attributes.
4970 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4971                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4972                      bool IsMemberFunction, SourceLocation Loc,
4973                      SourceRange Range, VariadicCallType CallType) {
4974   // FIXME: We should check as much as we can in the template definition.
4975   if (CurContext->isDependentContext())
4976     return;
4977 
4978   // Printf and scanf checking.
4979   llvm::SmallBitVector CheckedVarArgs;
4980   if (FDecl) {
4981     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4982       // Only create vector if there are format attributes.
4983       CheckedVarArgs.resize(Args.size());
4984 
4985       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4986                            CheckedVarArgs);
4987     }
4988   }
4989 
4990   // Refuse POD arguments that weren't caught by the format string
4991   // checks above.
4992   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4993   if (CallType != VariadicDoesNotApply &&
4994       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4995     unsigned NumParams = Proto ? Proto->getNumParams()
4996                        : FDecl && isa<FunctionDecl>(FDecl)
4997                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4998                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4999                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5000                        : 0;
5001 
5002     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5003       // Args[ArgIdx] can be null in malformed code.
5004       if (const Expr *Arg = Args[ArgIdx]) {
5005         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5006           checkVariadicArgument(Arg, CallType);
5007       }
5008     }
5009   }
5010 
5011   if (FDecl || Proto) {
5012     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5013 
5014     // Type safety checking.
5015     if (FDecl) {
5016       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5017         CheckArgumentWithTypeTag(I, Args, Loc);
5018     }
5019   }
5020 
5021   // Check that passed arguments match the alignment of original arguments.
5022   // Try to get the missing prototype from the declaration.
5023   if (!Proto && FDecl) {
5024     const auto *FT = FDecl->getFunctionType();
5025     if (isa_and_nonnull<FunctionProtoType>(FT))
5026       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5027   }
5028   if (Proto) {
5029     // For variadic functions, we may have more args than parameters.
5030     // For some K&R functions, we may have less args than parameters.
5031     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5032     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5033       // Args[ArgIdx] can be null in malformed code.
5034       if (const Expr *Arg = Args[ArgIdx]) {
5035         if (Arg->containsErrors())
5036           continue;
5037 
5038         QualType ParamTy = Proto->getParamType(ArgIdx);
5039         QualType ArgTy = Arg->getType();
5040         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5041                           ArgTy, ParamTy);
5042       }
5043     }
5044   }
5045 
5046   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5047     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5048     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5049     if (!Arg->isValueDependent()) {
5050       Expr::EvalResult Align;
5051       if (Arg->EvaluateAsInt(Align, Context)) {
5052         const llvm::APSInt &I = Align.Val.getInt();
5053         if (!I.isPowerOf2())
5054           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5055               << Arg->getSourceRange();
5056 
5057         if (I > Sema::MaximumAlignment)
5058           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5059               << Arg->getSourceRange() << Sema::MaximumAlignment;
5060       }
5061     }
5062   }
5063 
5064   if (FD)
5065     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5066 }
5067 
5068 /// CheckConstructorCall - Check a constructor call for correctness and safety
5069 /// properties not enforced by the C type system.
5070 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5071                                 ArrayRef<const Expr *> Args,
5072                                 const FunctionProtoType *Proto,
5073                                 SourceLocation Loc) {
5074   VariadicCallType CallType =
5075       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5076 
5077   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5078   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5079                     Context.getPointerType(Ctor->getThisObjectType()));
5080 
5081   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5082             Loc, SourceRange(), CallType);
5083 }
5084 
5085 /// CheckFunctionCall - Check a direct function call for various correctness
5086 /// and safety properties not strictly enforced by the C type system.
5087 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5088                              const FunctionProtoType *Proto) {
5089   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5090                               isa<CXXMethodDecl>(FDecl);
5091   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5092                           IsMemberOperatorCall;
5093   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5094                                                   TheCall->getCallee());
5095   Expr** Args = TheCall->getArgs();
5096   unsigned NumArgs = TheCall->getNumArgs();
5097 
5098   Expr *ImplicitThis = nullptr;
5099   if (IsMemberOperatorCall) {
5100     // If this is a call to a member operator, hide the first argument
5101     // from checkCall.
5102     // FIXME: Our choice of AST representation here is less than ideal.
5103     ImplicitThis = Args[0];
5104     ++Args;
5105     --NumArgs;
5106   } else if (IsMemberFunction)
5107     ImplicitThis =
5108         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5109 
5110   if (ImplicitThis) {
5111     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5112     // used.
5113     QualType ThisType = ImplicitThis->getType();
5114     if (!ThisType->isPointerType()) {
5115       assert(!ThisType->isReferenceType());
5116       ThisType = Context.getPointerType(ThisType);
5117     }
5118 
5119     QualType ThisTypeFromDecl =
5120         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5121 
5122     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5123                       ThisTypeFromDecl);
5124   }
5125 
5126   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5127             IsMemberFunction, TheCall->getRParenLoc(),
5128             TheCall->getCallee()->getSourceRange(), CallType);
5129 
5130   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5131   // None of the checks below are needed for functions that don't have
5132   // simple names (e.g., C++ conversion functions).
5133   if (!FnInfo)
5134     return false;
5135 
5136   CheckTCBEnforcement(TheCall, FDecl);
5137 
5138   CheckAbsoluteValueFunction(TheCall, FDecl);
5139   CheckMaxUnsignedZero(TheCall, FDecl);
5140 
5141   if (getLangOpts().ObjC)
5142     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5143 
5144   unsigned CMId = FDecl->getMemoryFunctionKind();
5145 
5146   // Handle memory setting and copying functions.
5147   switch (CMId) {
5148   case 0:
5149     return false;
5150   case Builtin::BIstrlcpy: // fallthrough
5151   case Builtin::BIstrlcat:
5152     CheckStrlcpycatArguments(TheCall, FnInfo);
5153     break;
5154   case Builtin::BIstrncat:
5155     CheckStrncatArguments(TheCall, FnInfo);
5156     break;
5157   case Builtin::BIfree:
5158     CheckFreeArguments(TheCall);
5159     break;
5160   default:
5161     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5162   }
5163 
5164   return false;
5165 }
5166 
5167 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5168                                ArrayRef<const Expr *> Args) {
5169   VariadicCallType CallType =
5170       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5171 
5172   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5173             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5174             CallType);
5175 
5176   return false;
5177 }
5178 
5179 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5180                             const FunctionProtoType *Proto) {
5181   QualType Ty;
5182   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5183     Ty = V->getType().getNonReferenceType();
5184   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5185     Ty = F->getType().getNonReferenceType();
5186   else
5187     return false;
5188 
5189   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5190       !Ty->isFunctionProtoType())
5191     return false;
5192 
5193   VariadicCallType CallType;
5194   if (!Proto || !Proto->isVariadic()) {
5195     CallType = VariadicDoesNotApply;
5196   } else if (Ty->isBlockPointerType()) {
5197     CallType = VariadicBlock;
5198   } else { // Ty->isFunctionPointerType()
5199     CallType = VariadicFunction;
5200   }
5201 
5202   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5203             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5204             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5205             TheCall->getCallee()->getSourceRange(), CallType);
5206 
5207   return false;
5208 }
5209 
5210 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5211 /// such as function pointers returned from functions.
5212 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5213   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5214                                                   TheCall->getCallee());
5215   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5216             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5217             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5218             TheCall->getCallee()->getSourceRange(), CallType);
5219 
5220   return false;
5221 }
5222 
5223 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5224   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5225     return false;
5226 
5227   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5228   switch (Op) {
5229   case AtomicExpr::AO__c11_atomic_init:
5230   case AtomicExpr::AO__opencl_atomic_init:
5231     llvm_unreachable("There is no ordering argument for an init");
5232 
5233   case AtomicExpr::AO__c11_atomic_load:
5234   case AtomicExpr::AO__opencl_atomic_load:
5235   case AtomicExpr::AO__atomic_load_n:
5236   case AtomicExpr::AO__atomic_load:
5237     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5238            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5239 
5240   case AtomicExpr::AO__c11_atomic_store:
5241   case AtomicExpr::AO__opencl_atomic_store:
5242   case AtomicExpr::AO__atomic_store:
5243   case AtomicExpr::AO__atomic_store_n:
5244     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5245            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5246            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5247 
5248   default:
5249     return true;
5250   }
5251 }
5252 
5253 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5254                                          AtomicExpr::AtomicOp Op) {
5255   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5256   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5257   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5258   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5259                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5260                          Op);
5261 }
5262 
5263 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5264                                  SourceLocation RParenLoc, MultiExprArg Args,
5265                                  AtomicExpr::AtomicOp Op,
5266                                  AtomicArgumentOrder ArgOrder) {
5267   // All the non-OpenCL operations take one of the following forms.
5268   // The OpenCL operations take the __c11 forms with one extra argument for
5269   // synchronization scope.
5270   enum {
5271     // C    __c11_atomic_init(A *, C)
5272     Init,
5273 
5274     // C    __c11_atomic_load(A *, int)
5275     Load,
5276 
5277     // void __atomic_load(A *, CP, int)
5278     LoadCopy,
5279 
5280     // void __atomic_store(A *, CP, int)
5281     Copy,
5282 
5283     // C    __c11_atomic_add(A *, M, int)
5284     Arithmetic,
5285 
5286     // C    __atomic_exchange_n(A *, CP, int)
5287     Xchg,
5288 
5289     // void __atomic_exchange(A *, C *, CP, int)
5290     GNUXchg,
5291 
5292     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5293     C11CmpXchg,
5294 
5295     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5296     GNUCmpXchg
5297   } Form = Init;
5298 
5299   const unsigned NumForm = GNUCmpXchg + 1;
5300   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5301   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5302   // where:
5303   //   C is an appropriate type,
5304   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5305   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5306   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5307   //   the int parameters are for orderings.
5308 
5309   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5310       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5311       "need to update code for modified forms");
5312   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5313                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5314                         AtomicExpr::AO__atomic_load,
5315                 "need to update code for modified C11 atomics");
5316   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5317                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5318   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5319                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5320                IsOpenCL;
5321   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5322              Op == AtomicExpr::AO__atomic_store_n ||
5323              Op == AtomicExpr::AO__atomic_exchange_n ||
5324              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5325   bool IsAddSub = false;
5326 
5327   switch (Op) {
5328   case AtomicExpr::AO__c11_atomic_init:
5329   case AtomicExpr::AO__opencl_atomic_init:
5330     Form = Init;
5331     break;
5332 
5333   case AtomicExpr::AO__c11_atomic_load:
5334   case AtomicExpr::AO__opencl_atomic_load:
5335   case AtomicExpr::AO__atomic_load_n:
5336     Form = Load;
5337     break;
5338 
5339   case AtomicExpr::AO__atomic_load:
5340     Form = LoadCopy;
5341     break;
5342 
5343   case AtomicExpr::AO__c11_atomic_store:
5344   case AtomicExpr::AO__opencl_atomic_store:
5345   case AtomicExpr::AO__atomic_store:
5346   case AtomicExpr::AO__atomic_store_n:
5347     Form = Copy;
5348     break;
5349 
5350   case AtomicExpr::AO__c11_atomic_fetch_add:
5351   case AtomicExpr::AO__c11_atomic_fetch_sub:
5352   case AtomicExpr::AO__opencl_atomic_fetch_add:
5353   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5354   case AtomicExpr::AO__atomic_fetch_add:
5355   case AtomicExpr::AO__atomic_fetch_sub:
5356   case AtomicExpr::AO__atomic_add_fetch:
5357   case AtomicExpr::AO__atomic_sub_fetch:
5358     IsAddSub = true;
5359     Form = Arithmetic;
5360     break;
5361   case AtomicExpr::AO__c11_atomic_fetch_and:
5362   case AtomicExpr::AO__c11_atomic_fetch_or:
5363   case AtomicExpr::AO__c11_atomic_fetch_xor:
5364   case AtomicExpr::AO__opencl_atomic_fetch_and:
5365   case AtomicExpr::AO__opencl_atomic_fetch_or:
5366   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5367   case AtomicExpr::AO__atomic_fetch_and:
5368   case AtomicExpr::AO__atomic_fetch_or:
5369   case AtomicExpr::AO__atomic_fetch_xor:
5370   case AtomicExpr::AO__atomic_fetch_nand:
5371   case AtomicExpr::AO__atomic_and_fetch:
5372   case AtomicExpr::AO__atomic_or_fetch:
5373   case AtomicExpr::AO__atomic_xor_fetch:
5374   case AtomicExpr::AO__atomic_nand_fetch:
5375     Form = Arithmetic;
5376     break;
5377   case AtomicExpr::AO__c11_atomic_fetch_min:
5378   case AtomicExpr::AO__c11_atomic_fetch_max:
5379   case AtomicExpr::AO__opencl_atomic_fetch_min:
5380   case AtomicExpr::AO__opencl_atomic_fetch_max:
5381   case AtomicExpr::AO__atomic_min_fetch:
5382   case AtomicExpr::AO__atomic_max_fetch:
5383   case AtomicExpr::AO__atomic_fetch_min:
5384   case AtomicExpr::AO__atomic_fetch_max:
5385     Form = Arithmetic;
5386     break;
5387 
5388   case AtomicExpr::AO__c11_atomic_exchange:
5389   case AtomicExpr::AO__opencl_atomic_exchange:
5390   case AtomicExpr::AO__atomic_exchange_n:
5391     Form = Xchg;
5392     break;
5393 
5394   case AtomicExpr::AO__atomic_exchange:
5395     Form = GNUXchg;
5396     break;
5397 
5398   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5399   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5400   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5401   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5402     Form = C11CmpXchg;
5403     break;
5404 
5405   case AtomicExpr::AO__atomic_compare_exchange:
5406   case AtomicExpr::AO__atomic_compare_exchange_n:
5407     Form = GNUCmpXchg;
5408     break;
5409   }
5410 
5411   unsigned AdjustedNumArgs = NumArgs[Form];
5412   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5413     ++AdjustedNumArgs;
5414   // Check we have the right number of arguments.
5415   if (Args.size() < AdjustedNumArgs) {
5416     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5417         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5418         << ExprRange;
5419     return ExprError();
5420   } else if (Args.size() > AdjustedNumArgs) {
5421     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5422          diag::err_typecheck_call_too_many_args)
5423         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5424         << ExprRange;
5425     return ExprError();
5426   }
5427 
5428   // Inspect the first argument of the atomic operation.
5429   Expr *Ptr = Args[0];
5430   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5431   if (ConvertedPtr.isInvalid())
5432     return ExprError();
5433 
5434   Ptr = ConvertedPtr.get();
5435   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5436   if (!pointerType) {
5437     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5438         << Ptr->getType() << Ptr->getSourceRange();
5439     return ExprError();
5440   }
5441 
5442   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5443   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5444   QualType ValType = AtomTy; // 'C'
5445   if (IsC11) {
5446     if (!AtomTy->isAtomicType()) {
5447       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5448           << Ptr->getType() << Ptr->getSourceRange();
5449       return ExprError();
5450     }
5451     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5452         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5453       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5454           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5455           << Ptr->getSourceRange();
5456       return ExprError();
5457     }
5458     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5459   } else if (Form != Load && Form != LoadCopy) {
5460     if (ValType.isConstQualified()) {
5461       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5462           << Ptr->getType() << Ptr->getSourceRange();
5463       return ExprError();
5464     }
5465   }
5466 
5467   // For an arithmetic operation, the implied arithmetic must be well-formed.
5468   if (Form == Arithmetic) {
5469     // gcc does not enforce these rules for GNU atomics, but we do so for
5470     // sanity.
5471     auto IsAllowedValueType = [&](QualType ValType) {
5472       if (ValType->isIntegerType())
5473         return true;
5474       if (ValType->isPointerType())
5475         return true;
5476       if (!ValType->isFloatingType())
5477         return false;
5478       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5479       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5480           &Context.getTargetInfo().getLongDoubleFormat() ==
5481               &llvm::APFloat::x87DoubleExtended())
5482         return false;
5483       return true;
5484     };
5485     if (IsAddSub && !IsAllowedValueType(ValType)) {
5486       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5487           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5488       return ExprError();
5489     }
5490     if (!IsAddSub && !ValType->isIntegerType()) {
5491       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5492           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5493       return ExprError();
5494     }
5495     if (IsC11 && ValType->isPointerType() &&
5496         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5497                             diag::err_incomplete_type)) {
5498       return ExprError();
5499     }
5500   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5501     // For __atomic_*_n operations, the value type must be a scalar integral or
5502     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5503     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5504         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5505     return ExprError();
5506   }
5507 
5508   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5509       !AtomTy->isScalarType()) {
5510     // For GNU atomics, require a trivially-copyable type. This is not part of
5511     // the GNU atomics specification, but we enforce it for sanity.
5512     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5513         << Ptr->getType() << Ptr->getSourceRange();
5514     return ExprError();
5515   }
5516 
5517   switch (ValType.getObjCLifetime()) {
5518   case Qualifiers::OCL_None:
5519   case Qualifiers::OCL_ExplicitNone:
5520     // okay
5521     break;
5522 
5523   case Qualifiers::OCL_Weak:
5524   case Qualifiers::OCL_Strong:
5525   case Qualifiers::OCL_Autoreleasing:
5526     // FIXME: Can this happen? By this point, ValType should be known
5527     // to be trivially copyable.
5528     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5529         << ValType << Ptr->getSourceRange();
5530     return ExprError();
5531   }
5532 
5533   // All atomic operations have an overload which takes a pointer to a volatile
5534   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5535   // into the result or the other operands. Similarly atomic_load takes a
5536   // pointer to a const 'A'.
5537   ValType.removeLocalVolatile();
5538   ValType.removeLocalConst();
5539   QualType ResultType = ValType;
5540   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5541       Form == Init)
5542     ResultType = Context.VoidTy;
5543   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5544     ResultType = Context.BoolTy;
5545 
5546   // The type of a parameter passed 'by value'. In the GNU atomics, such
5547   // arguments are actually passed as pointers.
5548   QualType ByValType = ValType; // 'CP'
5549   bool IsPassedByAddress = false;
5550   if (!IsC11 && !IsN) {
5551     ByValType = Ptr->getType();
5552     IsPassedByAddress = true;
5553   }
5554 
5555   SmallVector<Expr *, 5> APIOrderedArgs;
5556   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5557     APIOrderedArgs.push_back(Args[0]);
5558     switch (Form) {
5559     case Init:
5560     case Load:
5561       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5562       break;
5563     case LoadCopy:
5564     case Copy:
5565     case Arithmetic:
5566     case Xchg:
5567       APIOrderedArgs.push_back(Args[2]); // Val1
5568       APIOrderedArgs.push_back(Args[1]); // Order
5569       break;
5570     case GNUXchg:
5571       APIOrderedArgs.push_back(Args[2]); // Val1
5572       APIOrderedArgs.push_back(Args[3]); // Val2
5573       APIOrderedArgs.push_back(Args[1]); // Order
5574       break;
5575     case C11CmpXchg:
5576       APIOrderedArgs.push_back(Args[2]); // Val1
5577       APIOrderedArgs.push_back(Args[4]); // Val2
5578       APIOrderedArgs.push_back(Args[1]); // Order
5579       APIOrderedArgs.push_back(Args[3]); // OrderFail
5580       break;
5581     case GNUCmpXchg:
5582       APIOrderedArgs.push_back(Args[2]); // Val1
5583       APIOrderedArgs.push_back(Args[4]); // Val2
5584       APIOrderedArgs.push_back(Args[5]); // Weak
5585       APIOrderedArgs.push_back(Args[1]); // Order
5586       APIOrderedArgs.push_back(Args[3]); // OrderFail
5587       break;
5588     }
5589   } else
5590     APIOrderedArgs.append(Args.begin(), Args.end());
5591 
5592   // The first argument's non-CV pointer type is used to deduce the type of
5593   // subsequent arguments, except for:
5594   //  - weak flag (always converted to bool)
5595   //  - memory order (always converted to int)
5596   //  - scope  (always converted to int)
5597   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5598     QualType Ty;
5599     if (i < NumVals[Form] + 1) {
5600       switch (i) {
5601       case 0:
5602         // The first argument is always a pointer. It has a fixed type.
5603         // It is always dereferenced, a nullptr is undefined.
5604         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5605         // Nothing else to do: we already know all we want about this pointer.
5606         continue;
5607       case 1:
5608         // The second argument is the non-atomic operand. For arithmetic, this
5609         // is always passed by value, and for a compare_exchange it is always
5610         // passed by address. For the rest, GNU uses by-address and C11 uses
5611         // by-value.
5612         assert(Form != Load);
5613         if (Form == Arithmetic && ValType->isPointerType())
5614           Ty = Context.getPointerDiffType();
5615         else if (Form == Init || Form == Arithmetic)
5616           Ty = ValType;
5617         else if (Form == Copy || Form == Xchg) {
5618           if (IsPassedByAddress) {
5619             // The value pointer is always dereferenced, a nullptr is undefined.
5620             CheckNonNullArgument(*this, APIOrderedArgs[i],
5621                                  ExprRange.getBegin());
5622           }
5623           Ty = ByValType;
5624         } else {
5625           Expr *ValArg = APIOrderedArgs[i];
5626           // The value pointer is always dereferenced, a nullptr is undefined.
5627           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5628           LangAS AS = LangAS::Default;
5629           // Keep address space of non-atomic pointer type.
5630           if (const PointerType *PtrTy =
5631                   ValArg->getType()->getAs<PointerType>()) {
5632             AS = PtrTy->getPointeeType().getAddressSpace();
5633           }
5634           Ty = Context.getPointerType(
5635               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5636         }
5637         break;
5638       case 2:
5639         // The third argument to compare_exchange / GNU exchange is the desired
5640         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5641         if (IsPassedByAddress)
5642           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5643         Ty = ByValType;
5644         break;
5645       case 3:
5646         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5647         Ty = Context.BoolTy;
5648         break;
5649       }
5650     } else {
5651       // The order(s) and scope are always converted to int.
5652       Ty = Context.IntTy;
5653     }
5654 
5655     InitializedEntity Entity =
5656         InitializedEntity::InitializeParameter(Context, Ty, false);
5657     ExprResult Arg = APIOrderedArgs[i];
5658     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5659     if (Arg.isInvalid())
5660       return true;
5661     APIOrderedArgs[i] = Arg.get();
5662   }
5663 
5664   // Permute the arguments into a 'consistent' order.
5665   SmallVector<Expr*, 5> SubExprs;
5666   SubExprs.push_back(Ptr);
5667   switch (Form) {
5668   case Init:
5669     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5670     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5671     break;
5672   case Load:
5673     SubExprs.push_back(APIOrderedArgs[1]); // Order
5674     break;
5675   case LoadCopy:
5676   case Copy:
5677   case Arithmetic:
5678   case Xchg:
5679     SubExprs.push_back(APIOrderedArgs[2]); // Order
5680     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5681     break;
5682   case GNUXchg:
5683     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5684     SubExprs.push_back(APIOrderedArgs[3]); // Order
5685     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5686     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5687     break;
5688   case C11CmpXchg:
5689     SubExprs.push_back(APIOrderedArgs[3]); // Order
5690     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5691     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5692     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5693     break;
5694   case GNUCmpXchg:
5695     SubExprs.push_back(APIOrderedArgs[4]); // Order
5696     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5697     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5698     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5699     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5700     break;
5701   }
5702 
5703   if (SubExprs.size() >= 2 && Form != Init) {
5704     if (Optional<llvm::APSInt> Result =
5705             SubExprs[1]->getIntegerConstantExpr(Context))
5706       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5707         Diag(SubExprs[1]->getBeginLoc(),
5708              diag::warn_atomic_op_has_invalid_memory_order)
5709             << SubExprs[1]->getSourceRange();
5710   }
5711 
5712   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5713     auto *Scope = Args[Args.size() - 1];
5714     if (Optional<llvm::APSInt> Result =
5715             Scope->getIntegerConstantExpr(Context)) {
5716       if (!ScopeModel->isValid(Result->getZExtValue()))
5717         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5718             << Scope->getSourceRange();
5719     }
5720     SubExprs.push_back(Scope);
5721   }
5722 
5723   AtomicExpr *AE = new (Context)
5724       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5725 
5726   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5727        Op == AtomicExpr::AO__c11_atomic_store ||
5728        Op == AtomicExpr::AO__opencl_atomic_load ||
5729        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5730       Context.AtomicUsesUnsupportedLibcall(AE))
5731     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5732         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5733              Op == AtomicExpr::AO__opencl_atomic_load)
5734                 ? 0
5735                 : 1);
5736 
5737   if (ValType->isExtIntType()) {
5738     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5739     return ExprError();
5740   }
5741 
5742   return AE;
5743 }
5744 
5745 /// checkBuiltinArgument - Given a call to a builtin function, perform
5746 /// normal type-checking on the given argument, updating the call in
5747 /// place.  This is useful when a builtin function requires custom
5748 /// type-checking for some of its arguments but not necessarily all of
5749 /// them.
5750 ///
5751 /// Returns true on error.
5752 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5753   FunctionDecl *Fn = E->getDirectCallee();
5754   assert(Fn && "builtin call without direct callee!");
5755 
5756   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5757   InitializedEntity Entity =
5758     InitializedEntity::InitializeParameter(S.Context, Param);
5759 
5760   ExprResult Arg = E->getArg(0);
5761   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5762   if (Arg.isInvalid())
5763     return true;
5764 
5765   E->setArg(ArgIndex, Arg.get());
5766   return false;
5767 }
5768 
5769 /// We have a call to a function like __sync_fetch_and_add, which is an
5770 /// overloaded function based on the pointer type of its first argument.
5771 /// The main BuildCallExpr routines have already promoted the types of
5772 /// arguments because all of these calls are prototyped as void(...).
5773 ///
5774 /// This function goes through and does final semantic checking for these
5775 /// builtins, as well as generating any warnings.
5776 ExprResult
5777 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5778   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5779   Expr *Callee = TheCall->getCallee();
5780   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5781   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5782 
5783   // Ensure that we have at least one argument to do type inference from.
5784   if (TheCall->getNumArgs() < 1) {
5785     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5786         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5787     return ExprError();
5788   }
5789 
5790   // Inspect the first argument of the atomic builtin.  This should always be
5791   // a pointer type, whose element is an integral scalar or pointer type.
5792   // Because it is a pointer type, we don't have to worry about any implicit
5793   // casts here.
5794   // FIXME: We don't allow floating point scalars as input.
5795   Expr *FirstArg = TheCall->getArg(0);
5796   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5797   if (FirstArgResult.isInvalid())
5798     return ExprError();
5799   FirstArg = FirstArgResult.get();
5800   TheCall->setArg(0, FirstArg);
5801 
5802   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5803   if (!pointerType) {
5804     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5805         << FirstArg->getType() << FirstArg->getSourceRange();
5806     return ExprError();
5807   }
5808 
5809   QualType ValType = pointerType->getPointeeType();
5810   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5811       !ValType->isBlockPointerType()) {
5812     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5813         << FirstArg->getType() << FirstArg->getSourceRange();
5814     return ExprError();
5815   }
5816 
5817   if (ValType.isConstQualified()) {
5818     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5819         << FirstArg->getType() << FirstArg->getSourceRange();
5820     return ExprError();
5821   }
5822 
5823   switch (ValType.getObjCLifetime()) {
5824   case Qualifiers::OCL_None:
5825   case Qualifiers::OCL_ExplicitNone:
5826     // okay
5827     break;
5828 
5829   case Qualifiers::OCL_Weak:
5830   case Qualifiers::OCL_Strong:
5831   case Qualifiers::OCL_Autoreleasing:
5832     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5833         << ValType << FirstArg->getSourceRange();
5834     return ExprError();
5835   }
5836 
5837   // Strip any qualifiers off ValType.
5838   ValType = ValType.getUnqualifiedType();
5839 
5840   // The majority of builtins return a value, but a few have special return
5841   // types, so allow them to override appropriately below.
5842   QualType ResultType = ValType;
5843 
5844   // We need to figure out which concrete builtin this maps onto.  For example,
5845   // __sync_fetch_and_add with a 2 byte object turns into
5846   // __sync_fetch_and_add_2.
5847 #define BUILTIN_ROW(x) \
5848   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5849     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5850 
5851   static const unsigned BuiltinIndices[][5] = {
5852     BUILTIN_ROW(__sync_fetch_and_add),
5853     BUILTIN_ROW(__sync_fetch_and_sub),
5854     BUILTIN_ROW(__sync_fetch_and_or),
5855     BUILTIN_ROW(__sync_fetch_and_and),
5856     BUILTIN_ROW(__sync_fetch_and_xor),
5857     BUILTIN_ROW(__sync_fetch_and_nand),
5858 
5859     BUILTIN_ROW(__sync_add_and_fetch),
5860     BUILTIN_ROW(__sync_sub_and_fetch),
5861     BUILTIN_ROW(__sync_and_and_fetch),
5862     BUILTIN_ROW(__sync_or_and_fetch),
5863     BUILTIN_ROW(__sync_xor_and_fetch),
5864     BUILTIN_ROW(__sync_nand_and_fetch),
5865 
5866     BUILTIN_ROW(__sync_val_compare_and_swap),
5867     BUILTIN_ROW(__sync_bool_compare_and_swap),
5868     BUILTIN_ROW(__sync_lock_test_and_set),
5869     BUILTIN_ROW(__sync_lock_release),
5870     BUILTIN_ROW(__sync_swap)
5871   };
5872 #undef BUILTIN_ROW
5873 
5874   // Determine the index of the size.
5875   unsigned SizeIndex;
5876   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5877   case 1: SizeIndex = 0; break;
5878   case 2: SizeIndex = 1; break;
5879   case 4: SizeIndex = 2; break;
5880   case 8: SizeIndex = 3; break;
5881   case 16: SizeIndex = 4; break;
5882   default:
5883     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5884         << FirstArg->getType() << FirstArg->getSourceRange();
5885     return ExprError();
5886   }
5887 
5888   // Each of these builtins has one pointer argument, followed by some number of
5889   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5890   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5891   // as the number of fixed args.
5892   unsigned BuiltinID = FDecl->getBuiltinID();
5893   unsigned BuiltinIndex, NumFixed = 1;
5894   bool WarnAboutSemanticsChange = false;
5895   switch (BuiltinID) {
5896   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5897   case Builtin::BI__sync_fetch_and_add:
5898   case Builtin::BI__sync_fetch_and_add_1:
5899   case Builtin::BI__sync_fetch_and_add_2:
5900   case Builtin::BI__sync_fetch_and_add_4:
5901   case Builtin::BI__sync_fetch_and_add_8:
5902   case Builtin::BI__sync_fetch_and_add_16:
5903     BuiltinIndex = 0;
5904     break;
5905 
5906   case Builtin::BI__sync_fetch_and_sub:
5907   case Builtin::BI__sync_fetch_and_sub_1:
5908   case Builtin::BI__sync_fetch_and_sub_2:
5909   case Builtin::BI__sync_fetch_and_sub_4:
5910   case Builtin::BI__sync_fetch_and_sub_8:
5911   case Builtin::BI__sync_fetch_and_sub_16:
5912     BuiltinIndex = 1;
5913     break;
5914 
5915   case Builtin::BI__sync_fetch_and_or:
5916   case Builtin::BI__sync_fetch_and_or_1:
5917   case Builtin::BI__sync_fetch_and_or_2:
5918   case Builtin::BI__sync_fetch_and_or_4:
5919   case Builtin::BI__sync_fetch_and_or_8:
5920   case Builtin::BI__sync_fetch_and_or_16:
5921     BuiltinIndex = 2;
5922     break;
5923 
5924   case Builtin::BI__sync_fetch_and_and:
5925   case Builtin::BI__sync_fetch_and_and_1:
5926   case Builtin::BI__sync_fetch_and_and_2:
5927   case Builtin::BI__sync_fetch_and_and_4:
5928   case Builtin::BI__sync_fetch_and_and_8:
5929   case Builtin::BI__sync_fetch_and_and_16:
5930     BuiltinIndex = 3;
5931     break;
5932 
5933   case Builtin::BI__sync_fetch_and_xor:
5934   case Builtin::BI__sync_fetch_and_xor_1:
5935   case Builtin::BI__sync_fetch_and_xor_2:
5936   case Builtin::BI__sync_fetch_and_xor_4:
5937   case Builtin::BI__sync_fetch_and_xor_8:
5938   case Builtin::BI__sync_fetch_and_xor_16:
5939     BuiltinIndex = 4;
5940     break;
5941 
5942   case Builtin::BI__sync_fetch_and_nand:
5943   case Builtin::BI__sync_fetch_and_nand_1:
5944   case Builtin::BI__sync_fetch_and_nand_2:
5945   case Builtin::BI__sync_fetch_and_nand_4:
5946   case Builtin::BI__sync_fetch_and_nand_8:
5947   case Builtin::BI__sync_fetch_and_nand_16:
5948     BuiltinIndex = 5;
5949     WarnAboutSemanticsChange = true;
5950     break;
5951 
5952   case Builtin::BI__sync_add_and_fetch:
5953   case Builtin::BI__sync_add_and_fetch_1:
5954   case Builtin::BI__sync_add_and_fetch_2:
5955   case Builtin::BI__sync_add_and_fetch_4:
5956   case Builtin::BI__sync_add_and_fetch_8:
5957   case Builtin::BI__sync_add_and_fetch_16:
5958     BuiltinIndex = 6;
5959     break;
5960 
5961   case Builtin::BI__sync_sub_and_fetch:
5962   case Builtin::BI__sync_sub_and_fetch_1:
5963   case Builtin::BI__sync_sub_and_fetch_2:
5964   case Builtin::BI__sync_sub_and_fetch_4:
5965   case Builtin::BI__sync_sub_and_fetch_8:
5966   case Builtin::BI__sync_sub_and_fetch_16:
5967     BuiltinIndex = 7;
5968     break;
5969 
5970   case Builtin::BI__sync_and_and_fetch:
5971   case Builtin::BI__sync_and_and_fetch_1:
5972   case Builtin::BI__sync_and_and_fetch_2:
5973   case Builtin::BI__sync_and_and_fetch_4:
5974   case Builtin::BI__sync_and_and_fetch_8:
5975   case Builtin::BI__sync_and_and_fetch_16:
5976     BuiltinIndex = 8;
5977     break;
5978 
5979   case Builtin::BI__sync_or_and_fetch:
5980   case Builtin::BI__sync_or_and_fetch_1:
5981   case Builtin::BI__sync_or_and_fetch_2:
5982   case Builtin::BI__sync_or_and_fetch_4:
5983   case Builtin::BI__sync_or_and_fetch_8:
5984   case Builtin::BI__sync_or_and_fetch_16:
5985     BuiltinIndex = 9;
5986     break;
5987 
5988   case Builtin::BI__sync_xor_and_fetch:
5989   case Builtin::BI__sync_xor_and_fetch_1:
5990   case Builtin::BI__sync_xor_and_fetch_2:
5991   case Builtin::BI__sync_xor_and_fetch_4:
5992   case Builtin::BI__sync_xor_and_fetch_8:
5993   case Builtin::BI__sync_xor_and_fetch_16:
5994     BuiltinIndex = 10;
5995     break;
5996 
5997   case Builtin::BI__sync_nand_and_fetch:
5998   case Builtin::BI__sync_nand_and_fetch_1:
5999   case Builtin::BI__sync_nand_and_fetch_2:
6000   case Builtin::BI__sync_nand_and_fetch_4:
6001   case Builtin::BI__sync_nand_and_fetch_8:
6002   case Builtin::BI__sync_nand_and_fetch_16:
6003     BuiltinIndex = 11;
6004     WarnAboutSemanticsChange = true;
6005     break;
6006 
6007   case Builtin::BI__sync_val_compare_and_swap:
6008   case Builtin::BI__sync_val_compare_and_swap_1:
6009   case Builtin::BI__sync_val_compare_and_swap_2:
6010   case Builtin::BI__sync_val_compare_and_swap_4:
6011   case Builtin::BI__sync_val_compare_and_swap_8:
6012   case Builtin::BI__sync_val_compare_and_swap_16:
6013     BuiltinIndex = 12;
6014     NumFixed = 2;
6015     break;
6016 
6017   case Builtin::BI__sync_bool_compare_and_swap:
6018   case Builtin::BI__sync_bool_compare_and_swap_1:
6019   case Builtin::BI__sync_bool_compare_and_swap_2:
6020   case Builtin::BI__sync_bool_compare_and_swap_4:
6021   case Builtin::BI__sync_bool_compare_and_swap_8:
6022   case Builtin::BI__sync_bool_compare_and_swap_16:
6023     BuiltinIndex = 13;
6024     NumFixed = 2;
6025     ResultType = Context.BoolTy;
6026     break;
6027 
6028   case Builtin::BI__sync_lock_test_and_set:
6029   case Builtin::BI__sync_lock_test_and_set_1:
6030   case Builtin::BI__sync_lock_test_and_set_2:
6031   case Builtin::BI__sync_lock_test_and_set_4:
6032   case Builtin::BI__sync_lock_test_and_set_8:
6033   case Builtin::BI__sync_lock_test_and_set_16:
6034     BuiltinIndex = 14;
6035     break;
6036 
6037   case Builtin::BI__sync_lock_release:
6038   case Builtin::BI__sync_lock_release_1:
6039   case Builtin::BI__sync_lock_release_2:
6040   case Builtin::BI__sync_lock_release_4:
6041   case Builtin::BI__sync_lock_release_8:
6042   case Builtin::BI__sync_lock_release_16:
6043     BuiltinIndex = 15;
6044     NumFixed = 0;
6045     ResultType = Context.VoidTy;
6046     break;
6047 
6048   case Builtin::BI__sync_swap:
6049   case Builtin::BI__sync_swap_1:
6050   case Builtin::BI__sync_swap_2:
6051   case Builtin::BI__sync_swap_4:
6052   case Builtin::BI__sync_swap_8:
6053   case Builtin::BI__sync_swap_16:
6054     BuiltinIndex = 16;
6055     break;
6056   }
6057 
6058   // Now that we know how many fixed arguments we expect, first check that we
6059   // have at least that many.
6060   if (TheCall->getNumArgs() < 1+NumFixed) {
6061     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6062         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6063         << Callee->getSourceRange();
6064     return ExprError();
6065   }
6066 
6067   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6068       << Callee->getSourceRange();
6069 
6070   if (WarnAboutSemanticsChange) {
6071     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6072         << Callee->getSourceRange();
6073   }
6074 
6075   // Get the decl for the concrete builtin from this, we can tell what the
6076   // concrete integer type we should convert to is.
6077   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6078   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6079   FunctionDecl *NewBuiltinDecl;
6080   if (NewBuiltinID == BuiltinID)
6081     NewBuiltinDecl = FDecl;
6082   else {
6083     // Perform builtin lookup to avoid redeclaring it.
6084     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6085     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6086     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6087     assert(Res.getFoundDecl());
6088     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6089     if (!NewBuiltinDecl)
6090       return ExprError();
6091   }
6092 
6093   // The first argument --- the pointer --- has a fixed type; we
6094   // deduce the types of the rest of the arguments accordingly.  Walk
6095   // the remaining arguments, converting them to the deduced value type.
6096   for (unsigned i = 0; i != NumFixed; ++i) {
6097     ExprResult Arg = TheCall->getArg(i+1);
6098 
6099     // GCC does an implicit conversion to the pointer or integer ValType.  This
6100     // can fail in some cases (1i -> int**), check for this error case now.
6101     // Initialize the argument.
6102     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6103                                                    ValType, /*consume*/ false);
6104     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6105     if (Arg.isInvalid())
6106       return ExprError();
6107 
6108     // Okay, we have something that *can* be converted to the right type.  Check
6109     // to see if there is a potentially weird extension going on here.  This can
6110     // happen when you do an atomic operation on something like an char* and
6111     // pass in 42.  The 42 gets converted to char.  This is even more strange
6112     // for things like 45.123 -> char, etc.
6113     // FIXME: Do this check.
6114     TheCall->setArg(i+1, Arg.get());
6115   }
6116 
6117   // Create a new DeclRefExpr to refer to the new decl.
6118   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6119       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6120       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6121       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6122 
6123   // Set the callee in the CallExpr.
6124   // FIXME: This loses syntactic information.
6125   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6126   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6127                                               CK_BuiltinFnToFnPtr);
6128   TheCall->setCallee(PromotedCall.get());
6129 
6130   // Change the result type of the call to match the original value type. This
6131   // is arbitrary, but the codegen for these builtins ins design to handle it
6132   // gracefully.
6133   TheCall->setType(ResultType);
6134 
6135   // Prohibit use of _ExtInt with atomic builtins.
6136   // The arguments would have already been converted to the first argument's
6137   // type, so only need to check the first argument.
6138   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6139   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6140     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6141     return ExprError();
6142   }
6143 
6144   return TheCallResult;
6145 }
6146 
6147 /// SemaBuiltinNontemporalOverloaded - We have a call to
6148 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6149 /// overloaded function based on the pointer type of its last argument.
6150 ///
6151 /// This function goes through and does final semantic checking for these
6152 /// builtins.
6153 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6154   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6155   DeclRefExpr *DRE =
6156       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6157   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6158   unsigned BuiltinID = FDecl->getBuiltinID();
6159   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6160           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6161          "Unexpected nontemporal load/store builtin!");
6162   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6163   unsigned numArgs = isStore ? 2 : 1;
6164 
6165   // Ensure that we have the proper number of arguments.
6166   if (checkArgCount(*this, TheCall, numArgs))
6167     return ExprError();
6168 
6169   // Inspect the last argument of the nontemporal builtin.  This should always
6170   // be a pointer type, from which we imply the type of the memory access.
6171   // Because it is a pointer type, we don't have to worry about any implicit
6172   // casts here.
6173   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6174   ExprResult PointerArgResult =
6175       DefaultFunctionArrayLvalueConversion(PointerArg);
6176 
6177   if (PointerArgResult.isInvalid())
6178     return ExprError();
6179   PointerArg = PointerArgResult.get();
6180   TheCall->setArg(numArgs - 1, PointerArg);
6181 
6182   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6183   if (!pointerType) {
6184     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6185         << PointerArg->getType() << PointerArg->getSourceRange();
6186     return ExprError();
6187   }
6188 
6189   QualType ValType = pointerType->getPointeeType();
6190 
6191   // Strip any qualifiers off ValType.
6192   ValType = ValType.getUnqualifiedType();
6193   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6194       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6195       !ValType->isVectorType()) {
6196     Diag(DRE->getBeginLoc(),
6197          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6198         << PointerArg->getType() << PointerArg->getSourceRange();
6199     return ExprError();
6200   }
6201 
6202   if (!isStore) {
6203     TheCall->setType(ValType);
6204     return TheCallResult;
6205   }
6206 
6207   ExprResult ValArg = TheCall->getArg(0);
6208   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6209       Context, ValType, /*consume*/ false);
6210   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6211   if (ValArg.isInvalid())
6212     return ExprError();
6213 
6214   TheCall->setArg(0, ValArg.get());
6215   TheCall->setType(Context.VoidTy);
6216   return TheCallResult;
6217 }
6218 
6219 /// CheckObjCString - Checks that the argument to the builtin
6220 /// CFString constructor is correct
6221 /// Note: It might also make sense to do the UTF-16 conversion here (would
6222 /// simplify the backend).
6223 bool Sema::CheckObjCString(Expr *Arg) {
6224   Arg = Arg->IgnoreParenCasts();
6225   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6226 
6227   if (!Literal || !Literal->isAscii()) {
6228     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6229         << Arg->getSourceRange();
6230     return true;
6231   }
6232 
6233   if (Literal->containsNonAsciiOrNull()) {
6234     StringRef String = Literal->getString();
6235     unsigned NumBytes = String.size();
6236     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6237     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6238     llvm::UTF16 *ToPtr = &ToBuf[0];
6239 
6240     llvm::ConversionResult Result =
6241         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6242                                  ToPtr + NumBytes, llvm::strictConversion);
6243     // Check for conversion failure.
6244     if (Result != llvm::conversionOK)
6245       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6246           << Arg->getSourceRange();
6247   }
6248   return false;
6249 }
6250 
6251 /// CheckObjCString - Checks that the format string argument to the os_log()
6252 /// and os_trace() functions is correct, and converts it to const char *.
6253 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6254   Arg = Arg->IgnoreParenCasts();
6255   auto *Literal = dyn_cast<StringLiteral>(Arg);
6256   if (!Literal) {
6257     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6258       Literal = ObjcLiteral->getString();
6259     }
6260   }
6261 
6262   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6263     return ExprError(
6264         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6265         << Arg->getSourceRange());
6266   }
6267 
6268   ExprResult Result(Literal);
6269   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6270   InitializedEntity Entity =
6271       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6272   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6273   return Result;
6274 }
6275 
6276 /// Check that the user is calling the appropriate va_start builtin for the
6277 /// target and calling convention.
6278 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6279   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6280   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6281   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6282                     TT.getArch() == llvm::Triple::aarch64_32);
6283   bool IsWindows = TT.isOSWindows();
6284   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6285   if (IsX64 || IsAArch64) {
6286     CallingConv CC = CC_C;
6287     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6288       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6289     if (IsMSVAStart) {
6290       // Don't allow this in System V ABI functions.
6291       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6292         return S.Diag(Fn->getBeginLoc(),
6293                       diag::err_ms_va_start_used_in_sysv_function);
6294     } else {
6295       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6296       // On x64 Windows, don't allow this in System V ABI functions.
6297       // (Yes, that means there's no corresponding way to support variadic
6298       // System V ABI functions on Windows.)
6299       if ((IsWindows && CC == CC_X86_64SysV) ||
6300           (!IsWindows && CC == CC_Win64))
6301         return S.Diag(Fn->getBeginLoc(),
6302                       diag::err_va_start_used_in_wrong_abi_function)
6303                << !IsWindows;
6304     }
6305     return false;
6306   }
6307 
6308   if (IsMSVAStart)
6309     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6310   return false;
6311 }
6312 
6313 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6314                                              ParmVarDecl **LastParam = nullptr) {
6315   // Determine whether the current function, block, or obj-c method is variadic
6316   // and get its parameter list.
6317   bool IsVariadic = false;
6318   ArrayRef<ParmVarDecl *> Params;
6319   DeclContext *Caller = S.CurContext;
6320   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6321     IsVariadic = Block->isVariadic();
6322     Params = Block->parameters();
6323   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6324     IsVariadic = FD->isVariadic();
6325     Params = FD->parameters();
6326   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6327     IsVariadic = MD->isVariadic();
6328     // FIXME: This isn't correct for methods (results in bogus warning).
6329     Params = MD->parameters();
6330   } else if (isa<CapturedDecl>(Caller)) {
6331     // We don't support va_start in a CapturedDecl.
6332     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6333     return true;
6334   } else {
6335     // This must be some other declcontext that parses exprs.
6336     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6337     return true;
6338   }
6339 
6340   if (!IsVariadic) {
6341     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6342     return true;
6343   }
6344 
6345   if (LastParam)
6346     *LastParam = Params.empty() ? nullptr : Params.back();
6347 
6348   return false;
6349 }
6350 
6351 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6352 /// for validity.  Emit an error and return true on failure; return false
6353 /// on success.
6354 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6355   Expr *Fn = TheCall->getCallee();
6356 
6357   if (checkVAStartABI(*this, BuiltinID, Fn))
6358     return true;
6359 
6360   if (checkArgCount(*this, TheCall, 2))
6361     return true;
6362 
6363   // Type-check the first argument normally.
6364   if (checkBuiltinArgument(*this, TheCall, 0))
6365     return true;
6366 
6367   // Check that the current function is variadic, and get its last parameter.
6368   ParmVarDecl *LastParam;
6369   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6370     return true;
6371 
6372   // Verify that the second argument to the builtin is the last argument of the
6373   // current function or method.
6374   bool SecondArgIsLastNamedArgument = false;
6375   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6376 
6377   // These are valid if SecondArgIsLastNamedArgument is false after the next
6378   // block.
6379   QualType Type;
6380   SourceLocation ParamLoc;
6381   bool IsCRegister = false;
6382 
6383   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6384     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6385       SecondArgIsLastNamedArgument = PV == LastParam;
6386 
6387       Type = PV->getType();
6388       ParamLoc = PV->getLocation();
6389       IsCRegister =
6390           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6391     }
6392   }
6393 
6394   if (!SecondArgIsLastNamedArgument)
6395     Diag(TheCall->getArg(1)->getBeginLoc(),
6396          diag::warn_second_arg_of_va_start_not_last_named_param);
6397   else if (IsCRegister || Type->isReferenceType() ||
6398            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6399              // Promotable integers are UB, but enumerations need a bit of
6400              // extra checking to see what their promotable type actually is.
6401              if (!Type->isPromotableIntegerType())
6402                return false;
6403              if (!Type->isEnumeralType())
6404                return true;
6405              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6406              return !(ED &&
6407                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6408            }()) {
6409     unsigned Reason = 0;
6410     if (Type->isReferenceType())  Reason = 1;
6411     else if (IsCRegister)         Reason = 2;
6412     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6413     Diag(ParamLoc, diag::note_parameter_type) << Type;
6414   }
6415 
6416   TheCall->setType(Context.VoidTy);
6417   return false;
6418 }
6419 
6420 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6421   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6422     const LangOptions &LO = getLangOpts();
6423 
6424     if (LO.CPlusPlus)
6425       return Arg->getType()
6426                  .getCanonicalType()
6427                  .getTypePtr()
6428                  ->getPointeeType()
6429                  .withoutLocalFastQualifiers() == Context.CharTy;
6430 
6431     // In C, allow aliasing through `char *`, this is required for AArch64 at
6432     // least.
6433     return true;
6434   };
6435 
6436   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6437   //                 const char *named_addr);
6438 
6439   Expr *Func = Call->getCallee();
6440 
6441   if (Call->getNumArgs() < 3)
6442     return Diag(Call->getEndLoc(),
6443                 diag::err_typecheck_call_too_few_args_at_least)
6444            << 0 /*function call*/ << 3 << Call->getNumArgs();
6445 
6446   // Type-check the first argument normally.
6447   if (checkBuiltinArgument(*this, Call, 0))
6448     return true;
6449 
6450   // Check that the current function is variadic.
6451   if (checkVAStartIsInVariadicFunction(*this, Func))
6452     return true;
6453 
6454   // __va_start on Windows does not validate the parameter qualifiers
6455 
6456   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6457   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6458 
6459   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6460   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6461 
6462   const QualType &ConstCharPtrTy =
6463       Context.getPointerType(Context.CharTy.withConst());
6464   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6465     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6466         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6467         << 0                                      /* qualifier difference */
6468         << 3                                      /* parameter mismatch */
6469         << 2 << Arg1->getType() << ConstCharPtrTy;
6470 
6471   const QualType SizeTy = Context.getSizeType();
6472   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6473     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6474         << Arg2->getType() << SizeTy << 1 /* different class */
6475         << 0                              /* qualifier difference */
6476         << 3                              /* parameter mismatch */
6477         << 3 << Arg2->getType() << SizeTy;
6478 
6479   return false;
6480 }
6481 
6482 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6483 /// friends.  This is declared to take (...), so we have to check everything.
6484 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6485   if (checkArgCount(*this, TheCall, 2))
6486     return true;
6487 
6488   ExprResult OrigArg0 = TheCall->getArg(0);
6489   ExprResult OrigArg1 = TheCall->getArg(1);
6490 
6491   // Do standard promotions between the two arguments, returning their common
6492   // type.
6493   QualType Res = UsualArithmeticConversions(
6494       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6495   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6496     return true;
6497 
6498   // Make sure any conversions are pushed back into the call; this is
6499   // type safe since unordered compare builtins are declared as "_Bool
6500   // foo(...)".
6501   TheCall->setArg(0, OrigArg0.get());
6502   TheCall->setArg(1, OrigArg1.get());
6503 
6504   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6505     return false;
6506 
6507   // If the common type isn't a real floating type, then the arguments were
6508   // invalid for this operation.
6509   if (Res.isNull() || !Res->isRealFloatingType())
6510     return Diag(OrigArg0.get()->getBeginLoc(),
6511                 diag::err_typecheck_call_invalid_ordered_compare)
6512            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6513            << SourceRange(OrigArg0.get()->getBeginLoc(),
6514                           OrigArg1.get()->getEndLoc());
6515 
6516   return false;
6517 }
6518 
6519 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6520 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6521 /// to check everything. We expect the last argument to be a floating point
6522 /// value.
6523 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6524   if (checkArgCount(*this, TheCall, NumArgs))
6525     return true;
6526 
6527   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6528   // on all preceding parameters just being int.  Try all of those.
6529   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6530     Expr *Arg = TheCall->getArg(i);
6531 
6532     if (Arg->isTypeDependent())
6533       return false;
6534 
6535     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6536 
6537     if (Res.isInvalid())
6538       return true;
6539     TheCall->setArg(i, Res.get());
6540   }
6541 
6542   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6543 
6544   if (OrigArg->isTypeDependent())
6545     return false;
6546 
6547   // Usual Unary Conversions will convert half to float, which we want for
6548   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6549   // type how it is, but do normal L->Rvalue conversions.
6550   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6551     OrigArg = UsualUnaryConversions(OrigArg).get();
6552   else
6553     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6554   TheCall->setArg(NumArgs - 1, OrigArg);
6555 
6556   // This operation requires a non-_Complex floating-point number.
6557   if (!OrigArg->getType()->isRealFloatingType())
6558     return Diag(OrigArg->getBeginLoc(),
6559                 diag::err_typecheck_call_invalid_unary_fp)
6560            << OrigArg->getType() << OrigArg->getSourceRange();
6561 
6562   return false;
6563 }
6564 
6565 /// Perform semantic analysis for a call to __builtin_complex.
6566 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6567   if (checkArgCount(*this, TheCall, 2))
6568     return true;
6569 
6570   bool Dependent = false;
6571   for (unsigned I = 0; I != 2; ++I) {
6572     Expr *Arg = TheCall->getArg(I);
6573     QualType T = Arg->getType();
6574     if (T->isDependentType()) {
6575       Dependent = true;
6576       continue;
6577     }
6578 
6579     // Despite supporting _Complex int, GCC requires a real floating point type
6580     // for the operands of __builtin_complex.
6581     if (!T->isRealFloatingType()) {
6582       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6583              << Arg->getType() << Arg->getSourceRange();
6584     }
6585 
6586     ExprResult Converted = DefaultLvalueConversion(Arg);
6587     if (Converted.isInvalid())
6588       return true;
6589     TheCall->setArg(I, Converted.get());
6590   }
6591 
6592   if (Dependent) {
6593     TheCall->setType(Context.DependentTy);
6594     return false;
6595   }
6596 
6597   Expr *Real = TheCall->getArg(0);
6598   Expr *Imag = TheCall->getArg(1);
6599   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6600     return Diag(Real->getBeginLoc(),
6601                 diag::err_typecheck_call_different_arg_types)
6602            << Real->getType() << Imag->getType()
6603            << Real->getSourceRange() << Imag->getSourceRange();
6604   }
6605 
6606   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6607   // don't allow this builtin to form those types either.
6608   // FIXME: Should we allow these types?
6609   if (Real->getType()->isFloat16Type())
6610     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6611            << "_Float16";
6612   if (Real->getType()->isHalfType())
6613     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6614            << "half";
6615 
6616   TheCall->setType(Context.getComplexType(Real->getType()));
6617   return false;
6618 }
6619 
6620 // Customized Sema Checking for VSX builtins that have the following signature:
6621 // vector [...] builtinName(vector [...], vector [...], const int);
6622 // Which takes the same type of vectors (any legal vector type) for the first
6623 // two arguments and takes compile time constant for the third argument.
6624 // Example builtins are :
6625 // vector double vec_xxpermdi(vector double, vector double, int);
6626 // vector short vec_xxsldwi(vector short, vector short, int);
6627 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6628   unsigned ExpectedNumArgs = 3;
6629   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6630     return true;
6631 
6632   // Check the third argument is a compile time constant
6633   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6634     return Diag(TheCall->getBeginLoc(),
6635                 diag::err_vsx_builtin_nonconstant_argument)
6636            << 3 /* argument index */ << TheCall->getDirectCallee()
6637            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6638                           TheCall->getArg(2)->getEndLoc());
6639 
6640   QualType Arg1Ty = TheCall->getArg(0)->getType();
6641   QualType Arg2Ty = TheCall->getArg(1)->getType();
6642 
6643   // Check the type of argument 1 and argument 2 are vectors.
6644   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6645   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6646       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6647     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6648            << TheCall->getDirectCallee()
6649            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6650                           TheCall->getArg(1)->getEndLoc());
6651   }
6652 
6653   // Check the first two arguments are the same type.
6654   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6655     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6656            << TheCall->getDirectCallee()
6657            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6658                           TheCall->getArg(1)->getEndLoc());
6659   }
6660 
6661   // When default clang type checking is turned off and the customized type
6662   // checking is used, the returning type of the function must be explicitly
6663   // set. Otherwise it is _Bool by default.
6664   TheCall->setType(Arg1Ty);
6665 
6666   return false;
6667 }
6668 
6669 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6670 // This is declared to take (...), so we have to check everything.
6671 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6672   if (TheCall->getNumArgs() < 2)
6673     return ExprError(Diag(TheCall->getEndLoc(),
6674                           diag::err_typecheck_call_too_few_args_at_least)
6675                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6676                      << TheCall->getSourceRange());
6677 
6678   // Determine which of the following types of shufflevector we're checking:
6679   // 1) unary, vector mask: (lhs, mask)
6680   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6681   QualType resType = TheCall->getArg(0)->getType();
6682   unsigned numElements = 0;
6683 
6684   if (!TheCall->getArg(0)->isTypeDependent() &&
6685       !TheCall->getArg(1)->isTypeDependent()) {
6686     QualType LHSType = TheCall->getArg(0)->getType();
6687     QualType RHSType = TheCall->getArg(1)->getType();
6688 
6689     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6690       return ExprError(
6691           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6692           << TheCall->getDirectCallee()
6693           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6694                          TheCall->getArg(1)->getEndLoc()));
6695 
6696     numElements = LHSType->castAs<VectorType>()->getNumElements();
6697     unsigned numResElements = TheCall->getNumArgs() - 2;
6698 
6699     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6700     // with mask.  If so, verify that RHS is an integer vector type with the
6701     // same number of elts as lhs.
6702     if (TheCall->getNumArgs() == 2) {
6703       if (!RHSType->hasIntegerRepresentation() ||
6704           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6705         return ExprError(Diag(TheCall->getBeginLoc(),
6706                               diag::err_vec_builtin_incompatible_vector)
6707                          << TheCall->getDirectCallee()
6708                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6709                                         TheCall->getArg(1)->getEndLoc()));
6710     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6711       return ExprError(Diag(TheCall->getBeginLoc(),
6712                             diag::err_vec_builtin_incompatible_vector)
6713                        << TheCall->getDirectCallee()
6714                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6715                                       TheCall->getArg(1)->getEndLoc()));
6716     } else if (numElements != numResElements) {
6717       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6718       resType = Context.getVectorType(eltType, numResElements,
6719                                       VectorType::GenericVector);
6720     }
6721   }
6722 
6723   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6724     if (TheCall->getArg(i)->isTypeDependent() ||
6725         TheCall->getArg(i)->isValueDependent())
6726       continue;
6727 
6728     Optional<llvm::APSInt> Result;
6729     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6730       return ExprError(Diag(TheCall->getBeginLoc(),
6731                             diag::err_shufflevector_nonconstant_argument)
6732                        << TheCall->getArg(i)->getSourceRange());
6733 
6734     // Allow -1 which will be translated to undef in the IR.
6735     if (Result->isSigned() && Result->isAllOnesValue())
6736       continue;
6737 
6738     if (Result->getActiveBits() > 64 ||
6739         Result->getZExtValue() >= numElements * 2)
6740       return ExprError(Diag(TheCall->getBeginLoc(),
6741                             diag::err_shufflevector_argument_too_large)
6742                        << TheCall->getArg(i)->getSourceRange());
6743   }
6744 
6745   SmallVector<Expr*, 32> exprs;
6746 
6747   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6748     exprs.push_back(TheCall->getArg(i));
6749     TheCall->setArg(i, nullptr);
6750   }
6751 
6752   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6753                                          TheCall->getCallee()->getBeginLoc(),
6754                                          TheCall->getRParenLoc());
6755 }
6756 
6757 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6758 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6759                                        SourceLocation BuiltinLoc,
6760                                        SourceLocation RParenLoc) {
6761   ExprValueKind VK = VK_PRValue;
6762   ExprObjectKind OK = OK_Ordinary;
6763   QualType DstTy = TInfo->getType();
6764   QualType SrcTy = E->getType();
6765 
6766   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6767     return ExprError(Diag(BuiltinLoc,
6768                           diag::err_convertvector_non_vector)
6769                      << E->getSourceRange());
6770   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6771     return ExprError(Diag(BuiltinLoc,
6772                           diag::err_convertvector_non_vector_type));
6773 
6774   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6775     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6776     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6777     if (SrcElts != DstElts)
6778       return ExprError(Diag(BuiltinLoc,
6779                             diag::err_convertvector_incompatible_vector)
6780                        << E->getSourceRange());
6781   }
6782 
6783   return new (Context)
6784       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6785 }
6786 
6787 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6788 // This is declared to take (const void*, ...) and can take two
6789 // optional constant int args.
6790 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6791   unsigned NumArgs = TheCall->getNumArgs();
6792 
6793   if (NumArgs > 3)
6794     return Diag(TheCall->getEndLoc(),
6795                 diag::err_typecheck_call_too_many_args_at_most)
6796            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6797 
6798   // Argument 0 is checked for us and the remaining arguments must be
6799   // constant integers.
6800   for (unsigned i = 1; i != NumArgs; ++i)
6801     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6802       return true;
6803 
6804   return false;
6805 }
6806 
6807 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6808 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6809   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6810     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6811            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6812   if (checkArgCount(*this, TheCall, 1))
6813     return true;
6814   Expr *Arg = TheCall->getArg(0);
6815   if (Arg->isInstantiationDependent())
6816     return false;
6817 
6818   QualType ArgTy = Arg->getType();
6819   if (!ArgTy->hasFloatingRepresentation())
6820     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6821            << ArgTy;
6822   if (Arg->isLValue()) {
6823     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6824     TheCall->setArg(0, FirstArg.get());
6825   }
6826   TheCall->setType(TheCall->getArg(0)->getType());
6827   return false;
6828 }
6829 
6830 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6831 // __assume does not evaluate its arguments, and should warn if its argument
6832 // has side effects.
6833 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6834   Expr *Arg = TheCall->getArg(0);
6835   if (Arg->isInstantiationDependent()) return false;
6836 
6837   if (Arg->HasSideEffects(Context))
6838     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6839         << Arg->getSourceRange()
6840         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6841 
6842   return false;
6843 }
6844 
6845 /// Handle __builtin_alloca_with_align. This is declared
6846 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6847 /// than 8.
6848 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6849   // The alignment must be a constant integer.
6850   Expr *Arg = TheCall->getArg(1);
6851 
6852   // We can't check the value of a dependent argument.
6853   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6854     if (const auto *UE =
6855             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6856       if (UE->getKind() == UETT_AlignOf ||
6857           UE->getKind() == UETT_PreferredAlignOf)
6858         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6859             << Arg->getSourceRange();
6860 
6861     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6862 
6863     if (!Result.isPowerOf2())
6864       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6865              << Arg->getSourceRange();
6866 
6867     if (Result < Context.getCharWidth())
6868       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6869              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6870 
6871     if (Result > std::numeric_limits<int32_t>::max())
6872       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6873              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6874   }
6875 
6876   return false;
6877 }
6878 
6879 /// Handle __builtin_assume_aligned. This is declared
6880 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6881 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6882   unsigned NumArgs = TheCall->getNumArgs();
6883 
6884   if (NumArgs > 3)
6885     return Diag(TheCall->getEndLoc(),
6886                 diag::err_typecheck_call_too_many_args_at_most)
6887            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6888 
6889   // The alignment must be a constant integer.
6890   Expr *Arg = TheCall->getArg(1);
6891 
6892   // We can't check the value of a dependent argument.
6893   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6894     llvm::APSInt Result;
6895     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6896       return true;
6897 
6898     if (!Result.isPowerOf2())
6899       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6900              << Arg->getSourceRange();
6901 
6902     if (Result > Sema::MaximumAlignment)
6903       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6904           << Arg->getSourceRange() << Sema::MaximumAlignment;
6905   }
6906 
6907   if (NumArgs > 2) {
6908     ExprResult Arg(TheCall->getArg(2));
6909     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6910       Context.getSizeType(), false);
6911     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6912     if (Arg.isInvalid()) return true;
6913     TheCall->setArg(2, Arg.get());
6914   }
6915 
6916   return false;
6917 }
6918 
6919 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6920   unsigned BuiltinID =
6921       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6922   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6923 
6924   unsigned NumArgs = TheCall->getNumArgs();
6925   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6926   if (NumArgs < NumRequiredArgs) {
6927     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6928            << 0 /* function call */ << NumRequiredArgs << NumArgs
6929            << TheCall->getSourceRange();
6930   }
6931   if (NumArgs >= NumRequiredArgs + 0x100) {
6932     return Diag(TheCall->getEndLoc(),
6933                 diag::err_typecheck_call_too_many_args_at_most)
6934            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6935            << TheCall->getSourceRange();
6936   }
6937   unsigned i = 0;
6938 
6939   // For formatting call, check buffer arg.
6940   if (!IsSizeCall) {
6941     ExprResult Arg(TheCall->getArg(i));
6942     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6943         Context, Context.VoidPtrTy, false);
6944     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6945     if (Arg.isInvalid())
6946       return true;
6947     TheCall->setArg(i, Arg.get());
6948     i++;
6949   }
6950 
6951   // Check string literal arg.
6952   unsigned FormatIdx = i;
6953   {
6954     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6955     if (Arg.isInvalid())
6956       return true;
6957     TheCall->setArg(i, Arg.get());
6958     i++;
6959   }
6960 
6961   // Make sure variadic args are scalar.
6962   unsigned FirstDataArg = i;
6963   while (i < NumArgs) {
6964     ExprResult Arg = DefaultVariadicArgumentPromotion(
6965         TheCall->getArg(i), VariadicFunction, nullptr);
6966     if (Arg.isInvalid())
6967       return true;
6968     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6969     if (ArgSize.getQuantity() >= 0x100) {
6970       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6971              << i << (int)ArgSize.getQuantity() << 0xff
6972              << TheCall->getSourceRange();
6973     }
6974     TheCall->setArg(i, Arg.get());
6975     i++;
6976   }
6977 
6978   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6979   // call to avoid duplicate diagnostics.
6980   if (!IsSizeCall) {
6981     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6982     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6983     bool Success = CheckFormatArguments(
6984         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6985         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6986         CheckedVarArgs);
6987     if (!Success)
6988       return true;
6989   }
6990 
6991   if (IsSizeCall) {
6992     TheCall->setType(Context.getSizeType());
6993   } else {
6994     TheCall->setType(Context.VoidPtrTy);
6995   }
6996   return false;
6997 }
6998 
6999 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7000 /// TheCall is a constant expression.
7001 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7002                                   llvm::APSInt &Result) {
7003   Expr *Arg = TheCall->getArg(ArgNum);
7004   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7005   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7006 
7007   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7008 
7009   Optional<llvm::APSInt> R;
7010   if (!(R = Arg->getIntegerConstantExpr(Context)))
7011     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7012            << FDecl->getDeclName() << Arg->getSourceRange();
7013   Result = *R;
7014   return false;
7015 }
7016 
7017 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7018 /// TheCall is a constant expression in the range [Low, High].
7019 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7020                                        int Low, int High, bool RangeIsError) {
7021   if (isConstantEvaluated())
7022     return false;
7023   llvm::APSInt Result;
7024 
7025   // We can't check the value of a dependent argument.
7026   Expr *Arg = TheCall->getArg(ArgNum);
7027   if (Arg->isTypeDependent() || Arg->isValueDependent())
7028     return false;
7029 
7030   // Check constant-ness first.
7031   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7032     return true;
7033 
7034   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7035     if (RangeIsError)
7036       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7037              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7038     else
7039       // Defer the warning until we know if the code will be emitted so that
7040       // dead code can ignore this.
7041       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7042                           PDiag(diag::warn_argument_invalid_range)
7043                               << toString(Result, 10) << Low << High
7044                               << Arg->getSourceRange());
7045   }
7046 
7047   return false;
7048 }
7049 
7050 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7051 /// TheCall is a constant expression is a multiple of Num..
7052 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7053                                           unsigned Num) {
7054   llvm::APSInt Result;
7055 
7056   // We can't check the value of a dependent argument.
7057   Expr *Arg = TheCall->getArg(ArgNum);
7058   if (Arg->isTypeDependent() || Arg->isValueDependent())
7059     return false;
7060 
7061   // Check constant-ness first.
7062   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7063     return true;
7064 
7065   if (Result.getSExtValue() % Num != 0)
7066     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7067            << Num << Arg->getSourceRange();
7068 
7069   return false;
7070 }
7071 
7072 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7073 /// constant expression representing a power of 2.
7074 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7075   llvm::APSInt Result;
7076 
7077   // We can't check the value of a dependent argument.
7078   Expr *Arg = TheCall->getArg(ArgNum);
7079   if (Arg->isTypeDependent() || Arg->isValueDependent())
7080     return false;
7081 
7082   // Check constant-ness first.
7083   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7084     return true;
7085 
7086   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7087   // and only if x is a power of 2.
7088   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7089     return false;
7090 
7091   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7092          << Arg->getSourceRange();
7093 }
7094 
7095 static bool IsShiftedByte(llvm::APSInt Value) {
7096   if (Value.isNegative())
7097     return false;
7098 
7099   // Check if it's a shifted byte, by shifting it down
7100   while (true) {
7101     // If the value fits in the bottom byte, the check passes.
7102     if (Value < 0x100)
7103       return true;
7104 
7105     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7106     // fails.
7107     if ((Value & 0xFF) != 0)
7108       return false;
7109 
7110     // If the bottom 8 bits are all 0, but something above that is nonzero,
7111     // then shifting the value right by 8 bits won't affect whether it's a
7112     // shifted byte or not. So do that, and go round again.
7113     Value >>= 8;
7114   }
7115 }
7116 
7117 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7118 /// a constant expression representing an arbitrary byte value shifted left by
7119 /// a multiple of 8 bits.
7120 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7121                                              unsigned ArgBits) {
7122   llvm::APSInt Result;
7123 
7124   // We can't check the value of a dependent argument.
7125   Expr *Arg = TheCall->getArg(ArgNum);
7126   if (Arg->isTypeDependent() || Arg->isValueDependent())
7127     return false;
7128 
7129   // Check constant-ness first.
7130   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7131     return true;
7132 
7133   // Truncate to the given size.
7134   Result = Result.getLoBits(ArgBits);
7135   Result.setIsUnsigned(true);
7136 
7137   if (IsShiftedByte(Result))
7138     return false;
7139 
7140   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7141          << Arg->getSourceRange();
7142 }
7143 
7144 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7145 /// TheCall is a constant expression representing either a shifted byte value,
7146 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7147 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7148 /// Arm MVE intrinsics.
7149 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7150                                                    int ArgNum,
7151                                                    unsigned ArgBits) {
7152   llvm::APSInt Result;
7153 
7154   // We can't check the value of a dependent argument.
7155   Expr *Arg = TheCall->getArg(ArgNum);
7156   if (Arg->isTypeDependent() || Arg->isValueDependent())
7157     return false;
7158 
7159   // Check constant-ness first.
7160   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7161     return true;
7162 
7163   // Truncate to the given size.
7164   Result = Result.getLoBits(ArgBits);
7165   Result.setIsUnsigned(true);
7166 
7167   // Check to see if it's in either of the required forms.
7168   if (IsShiftedByte(Result) ||
7169       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7170     return false;
7171 
7172   return Diag(TheCall->getBeginLoc(),
7173               diag::err_argument_not_shifted_byte_or_xxff)
7174          << Arg->getSourceRange();
7175 }
7176 
7177 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7178 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7179   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7180     if (checkArgCount(*this, TheCall, 2))
7181       return true;
7182     Expr *Arg0 = TheCall->getArg(0);
7183     Expr *Arg1 = TheCall->getArg(1);
7184 
7185     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7186     if (FirstArg.isInvalid())
7187       return true;
7188     QualType FirstArgType = FirstArg.get()->getType();
7189     if (!FirstArgType->isAnyPointerType())
7190       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7191                << "first" << FirstArgType << Arg0->getSourceRange();
7192     TheCall->setArg(0, FirstArg.get());
7193 
7194     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7195     if (SecArg.isInvalid())
7196       return true;
7197     QualType SecArgType = SecArg.get()->getType();
7198     if (!SecArgType->isIntegerType())
7199       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7200                << "second" << SecArgType << Arg1->getSourceRange();
7201 
7202     // Derive the return type from the pointer argument.
7203     TheCall->setType(FirstArgType);
7204     return false;
7205   }
7206 
7207   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7208     if (checkArgCount(*this, TheCall, 2))
7209       return true;
7210 
7211     Expr *Arg0 = TheCall->getArg(0);
7212     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7213     if (FirstArg.isInvalid())
7214       return true;
7215     QualType FirstArgType = FirstArg.get()->getType();
7216     if (!FirstArgType->isAnyPointerType())
7217       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7218                << "first" << FirstArgType << Arg0->getSourceRange();
7219     TheCall->setArg(0, FirstArg.get());
7220 
7221     // Derive the return type from the pointer argument.
7222     TheCall->setType(FirstArgType);
7223 
7224     // Second arg must be an constant in range [0,15]
7225     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7226   }
7227 
7228   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7229     if (checkArgCount(*this, TheCall, 2))
7230       return true;
7231     Expr *Arg0 = TheCall->getArg(0);
7232     Expr *Arg1 = TheCall->getArg(1);
7233 
7234     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7235     if (FirstArg.isInvalid())
7236       return true;
7237     QualType FirstArgType = FirstArg.get()->getType();
7238     if (!FirstArgType->isAnyPointerType())
7239       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7240                << "first" << FirstArgType << Arg0->getSourceRange();
7241 
7242     QualType SecArgType = Arg1->getType();
7243     if (!SecArgType->isIntegerType())
7244       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7245                << "second" << SecArgType << Arg1->getSourceRange();
7246     TheCall->setType(Context.IntTy);
7247     return false;
7248   }
7249 
7250   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7251       BuiltinID == AArch64::BI__builtin_arm_stg) {
7252     if (checkArgCount(*this, TheCall, 1))
7253       return true;
7254     Expr *Arg0 = TheCall->getArg(0);
7255     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7256     if (FirstArg.isInvalid())
7257       return true;
7258 
7259     QualType FirstArgType = FirstArg.get()->getType();
7260     if (!FirstArgType->isAnyPointerType())
7261       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7262                << "first" << FirstArgType << Arg0->getSourceRange();
7263     TheCall->setArg(0, FirstArg.get());
7264 
7265     // Derive the return type from the pointer argument.
7266     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7267       TheCall->setType(FirstArgType);
7268     return false;
7269   }
7270 
7271   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7272     Expr *ArgA = TheCall->getArg(0);
7273     Expr *ArgB = TheCall->getArg(1);
7274 
7275     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7276     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7277 
7278     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7279       return true;
7280 
7281     QualType ArgTypeA = ArgExprA.get()->getType();
7282     QualType ArgTypeB = ArgExprB.get()->getType();
7283 
7284     auto isNull = [&] (Expr *E) -> bool {
7285       return E->isNullPointerConstant(
7286                         Context, Expr::NPC_ValueDependentIsNotNull); };
7287 
7288     // argument should be either a pointer or null
7289     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7290       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7291         << "first" << ArgTypeA << ArgA->getSourceRange();
7292 
7293     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7294       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7295         << "second" << ArgTypeB << ArgB->getSourceRange();
7296 
7297     // Ensure Pointee types are compatible
7298     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7299         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7300       QualType pointeeA = ArgTypeA->getPointeeType();
7301       QualType pointeeB = ArgTypeB->getPointeeType();
7302       if (!Context.typesAreCompatible(
7303              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7304              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7305         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7306           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7307           << ArgB->getSourceRange();
7308       }
7309     }
7310 
7311     // at least one argument should be pointer type
7312     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7313       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7314         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7315 
7316     if (isNull(ArgA)) // adopt type of the other pointer
7317       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7318 
7319     if (isNull(ArgB))
7320       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7321 
7322     TheCall->setArg(0, ArgExprA.get());
7323     TheCall->setArg(1, ArgExprB.get());
7324     TheCall->setType(Context.LongLongTy);
7325     return false;
7326   }
7327   assert(false && "Unhandled ARM MTE intrinsic");
7328   return true;
7329 }
7330 
7331 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7332 /// TheCall is an ARM/AArch64 special register string literal.
7333 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7334                                     int ArgNum, unsigned ExpectedFieldNum,
7335                                     bool AllowName) {
7336   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7337                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7338                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7339                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7340                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7341                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7342   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7343                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7344                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7345                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7346                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7347                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7348   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7349 
7350   // We can't check the value of a dependent argument.
7351   Expr *Arg = TheCall->getArg(ArgNum);
7352   if (Arg->isTypeDependent() || Arg->isValueDependent())
7353     return false;
7354 
7355   // Check if the argument is a string literal.
7356   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7357     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7358            << Arg->getSourceRange();
7359 
7360   // Check the type of special register given.
7361   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7362   SmallVector<StringRef, 6> Fields;
7363   Reg.split(Fields, ":");
7364 
7365   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7366     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7367            << Arg->getSourceRange();
7368 
7369   // If the string is the name of a register then we cannot check that it is
7370   // valid here but if the string is of one the forms described in ACLE then we
7371   // can check that the supplied fields are integers and within the valid
7372   // ranges.
7373   if (Fields.size() > 1) {
7374     bool FiveFields = Fields.size() == 5;
7375 
7376     bool ValidString = true;
7377     if (IsARMBuiltin) {
7378       ValidString &= Fields[0].startswith_insensitive("cp") ||
7379                      Fields[0].startswith_insensitive("p");
7380       if (ValidString)
7381         Fields[0] = Fields[0].drop_front(
7382             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7383 
7384       ValidString &= Fields[2].startswith_insensitive("c");
7385       if (ValidString)
7386         Fields[2] = Fields[2].drop_front(1);
7387 
7388       if (FiveFields) {
7389         ValidString &= Fields[3].startswith_insensitive("c");
7390         if (ValidString)
7391           Fields[3] = Fields[3].drop_front(1);
7392       }
7393     }
7394 
7395     SmallVector<int, 5> Ranges;
7396     if (FiveFields)
7397       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7398     else
7399       Ranges.append({15, 7, 15});
7400 
7401     for (unsigned i=0; i<Fields.size(); ++i) {
7402       int IntField;
7403       ValidString &= !Fields[i].getAsInteger(10, IntField);
7404       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7405     }
7406 
7407     if (!ValidString)
7408       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7409              << Arg->getSourceRange();
7410   } else if (IsAArch64Builtin && Fields.size() == 1) {
7411     // If the register name is one of those that appear in the condition below
7412     // and the special register builtin being used is one of the write builtins,
7413     // then we require that the argument provided for writing to the register
7414     // is an integer constant expression. This is because it will be lowered to
7415     // an MSR (immediate) instruction, so we need to know the immediate at
7416     // compile time.
7417     if (TheCall->getNumArgs() != 2)
7418       return false;
7419 
7420     std::string RegLower = Reg.lower();
7421     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7422         RegLower != "pan" && RegLower != "uao")
7423       return false;
7424 
7425     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7426   }
7427 
7428   return false;
7429 }
7430 
7431 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7432 /// Emit an error and return true on failure; return false on success.
7433 /// TypeStr is a string containing the type descriptor of the value returned by
7434 /// the builtin and the descriptors of the expected type of the arguments.
7435 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7436 
7437   assert((TypeStr[0] != '\0') &&
7438          "Invalid types in PPC MMA builtin declaration");
7439 
7440   unsigned Mask = 0;
7441   unsigned ArgNum = 0;
7442 
7443   // The first type in TypeStr is the type of the value returned by the
7444   // builtin. So we first read that type and change the type of TheCall.
7445   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7446   TheCall->setType(type);
7447 
7448   while (*TypeStr != '\0') {
7449     Mask = 0;
7450     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7451     if (ArgNum >= TheCall->getNumArgs()) {
7452       ArgNum++;
7453       break;
7454     }
7455 
7456     Expr *Arg = TheCall->getArg(ArgNum);
7457     QualType ArgType = Arg->getType();
7458 
7459     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7460         (!ExpectedType->isVoidPointerType() &&
7461            ArgType.getCanonicalType() != ExpectedType))
7462       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7463              << ArgType << ExpectedType << 1 << 0 << 0;
7464 
7465     // If the value of the Mask is not 0, we have a constraint in the size of
7466     // the integer argument so here we ensure the argument is a constant that
7467     // is in the valid range.
7468     if (Mask != 0 &&
7469         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7470       return true;
7471 
7472     ArgNum++;
7473   }
7474 
7475   // In case we exited early from the previous loop, there are other types to
7476   // read from TypeStr. So we need to read them all to ensure we have the right
7477   // number of arguments in TheCall and if it is not the case, to display a
7478   // better error message.
7479   while (*TypeStr != '\0') {
7480     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7481     ArgNum++;
7482   }
7483   if (checkArgCount(*this, TheCall, ArgNum))
7484     return true;
7485 
7486   return false;
7487 }
7488 
7489 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7490 /// This checks that the target supports __builtin_longjmp and
7491 /// that val is a constant 1.
7492 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7493   if (!Context.getTargetInfo().hasSjLjLowering())
7494     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7495            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7496 
7497   Expr *Arg = TheCall->getArg(1);
7498   llvm::APSInt Result;
7499 
7500   // TODO: This is less than ideal. Overload this to take a value.
7501   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7502     return true;
7503 
7504   if (Result != 1)
7505     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7506            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7507 
7508   return false;
7509 }
7510 
7511 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7512 /// This checks that the target supports __builtin_setjmp.
7513 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7514   if (!Context.getTargetInfo().hasSjLjLowering())
7515     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7516            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7517   return false;
7518 }
7519 
7520 namespace {
7521 
7522 class UncoveredArgHandler {
7523   enum { Unknown = -1, AllCovered = -2 };
7524 
7525   signed FirstUncoveredArg = Unknown;
7526   SmallVector<const Expr *, 4> DiagnosticExprs;
7527 
7528 public:
7529   UncoveredArgHandler() = default;
7530 
7531   bool hasUncoveredArg() const {
7532     return (FirstUncoveredArg >= 0);
7533   }
7534 
7535   unsigned getUncoveredArg() const {
7536     assert(hasUncoveredArg() && "no uncovered argument");
7537     return FirstUncoveredArg;
7538   }
7539 
7540   void setAllCovered() {
7541     // A string has been found with all arguments covered, so clear out
7542     // the diagnostics.
7543     DiagnosticExprs.clear();
7544     FirstUncoveredArg = AllCovered;
7545   }
7546 
7547   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7548     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7549 
7550     // Don't update if a previous string covers all arguments.
7551     if (FirstUncoveredArg == AllCovered)
7552       return;
7553 
7554     // UncoveredArgHandler tracks the highest uncovered argument index
7555     // and with it all the strings that match this index.
7556     if (NewFirstUncoveredArg == FirstUncoveredArg)
7557       DiagnosticExprs.push_back(StrExpr);
7558     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7559       DiagnosticExprs.clear();
7560       DiagnosticExprs.push_back(StrExpr);
7561       FirstUncoveredArg = NewFirstUncoveredArg;
7562     }
7563   }
7564 
7565   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7566 };
7567 
7568 enum StringLiteralCheckType {
7569   SLCT_NotALiteral,
7570   SLCT_UncheckedLiteral,
7571   SLCT_CheckedLiteral
7572 };
7573 
7574 } // namespace
7575 
7576 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7577                                      BinaryOperatorKind BinOpKind,
7578                                      bool AddendIsRight) {
7579   unsigned BitWidth = Offset.getBitWidth();
7580   unsigned AddendBitWidth = Addend.getBitWidth();
7581   // There might be negative interim results.
7582   if (Addend.isUnsigned()) {
7583     Addend = Addend.zext(++AddendBitWidth);
7584     Addend.setIsSigned(true);
7585   }
7586   // Adjust the bit width of the APSInts.
7587   if (AddendBitWidth > BitWidth) {
7588     Offset = Offset.sext(AddendBitWidth);
7589     BitWidth = AddendBitWidth;
7590   } else if (BitWidth > AddendBitWidth) {
7591     Addend = Addend.sext(BitWidth);
7592   }
7593 
7594   bool Ov = false;
7595   llvm::APSInt ResOffset = Offset;
7596   if (BinOpKind == BO_Add)
7597     ResOffset = Offset.sadd_ov(Addend, Ov);
7598   else {
7599     assert(AddendIsRight && BinOpKind == BO_Sub &&
7600            "operator must be add or sub with addend on the right");
7601     ResOffset = Offset.ssub_ov(Addend, Ov);
7602   }
7603 
7604   // We add an offset to a pointer here so we should support an offset as big as
7605   // possible.
7606   if (Ov) {
7607     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7608            "index (intermediate) result too big");
7609     Offset = Offset.sext(2 * BitWidth);
7610     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7611     return;
7612   }
7613 
7614   Offset = ResOffset;
7615 }
7616 
7617 namespace {
7618 
7619 // This is a wrapper class around StringLiteral to support offsetted string
7620 // literals as format strings. It takes the offset into account when returning
7621 // the string and its length or the source locations to display notes correctly.
7622 class FormatStringLiteral {
7623   const StringLiteral *FExpr;
7624   int64_t Offset;
7625 
7626  public:
7627   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7628       : FExpr(fexpr), Offset(Offset) {}
7629 
7630   StringRef getString() const {
7631     return FExpr->getString().drop_front(Offset);
7632   }
7633 
7634   unsigned getByteLength() const {
7635     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7636   }
7637 
7638   unsigned getLength() const { return FExpr->getLength() - Offset; }
7639   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7640 
7641   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7642 
7643   QualType getType() const { return FExpr->getType(); }
7644 
7645   bool isAscii() const { return FExpr->isAscii(); }
7646   bool isWide() const { return FExpr->isWide(); }
7647   bool isUTF8() const { return FExpr->isUTF8(); }
7648   bool isUTF16() const { return FExpr->isUTF16(); }
7649   bool isUTF32() const { return FExpr->isUTF32(); }
7650   bool isPascal() const { return FExpr->isPascal(); }
7651 
7652   SourceLocation getLocationOfByte(
7653       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7654       const TargetInfo &Target, unsigned *StartToken = nullptr,
7655       unsigned *StartTokenByteOffset = nullptr) const {
7656     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7657                                     StartToken, StartTokenByteOffset);
7658   }
7659 
7660   SourceLocation getBeginLoc() const LLVM_READONLY {
7661     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7662   }
7663 
7664   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7665 };
7666 
7667 }  // namespace
7668 
7669 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7670                               const Expr *OrigFormatExpr,
7671                               ArrayRef<const Expr *> Args,
7672                               bool HasVAListArg, unsigned format_idx,
7673                               unsigned firstDataArg,
7674                               Sema::FormatStringType Type,
7675                               bool inFunctionCall,
7676                               Sema::VariadicCallType CallType,
7677                               llvm::SmallBitVector &CheckedVarArgs,
7678                               UncoveredArgHandler &UncoveredArg,
7679                               bool IgnoreStringsWithoutSpecifiers);
7680 
7681 // Determine if an expression is a string literal or constant string.
7682 // If this function returns false on the arguments to a function expecting a
7683 // format string, we will usually need to emit a warning.
7684 // True string literals are then checked by CheckFormatString.
7685 static StringLiteralCheckType
7686 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7687                       bool HasVAListArg, unsigned format_idx,
7688                       unsigned firstDataArg, Sema::FormatStringType Type,
7689                       Sema::VariadicCallType CallType, bool InFunctionCall,
7690                       llvm::SmallBitVector &CheckedVarArgs,
7691                       UncoveredArgHandler &UncoveredArg,
7692                       llvm::APSInt Offset,
7693                       bool IgnoreStringsWithoutSpecifiers = false) {
7694   if (S.isConstantEvaluated())
7695     return SLCT_NotALiteral;
7696  tryAgain:
7697   assert(Offset.isSigned() && "invalid offset");
7698 
7699   if (E->isTypeDependent() || E->isValueDependent())
7700     return SLCT_NotALiteral;
7701 
7702   E = E->IgnoreParenCasts();
7703 
7704   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7705     // Technically -Wformat-nonliteral does not warn about this case.
7706     // The behavior of printf and friends in this case is implementation
7707     // dependent.  Ideally if the format string cannot be null then
7708     // it should have a 'nonnull' attribute in the function prototype.
7709     return SLCT_UncheckedLiteral;
7710 
7711   switch (E->getStmtClass()) {
7712   case Stmt::BinaryConditionalOperatorClass:
7713   case Stmt::ConditionalOperatorClass: {
7714     // The expression is a literal if both sub-expressions were, and it was
7715     // completely checked only if both sub-expressions were checked.
7716     const AbstractConditionalOperator *C =
7717         cast<AbstractConditionalOperator>(E);
7718 
7719     // Determine whether it is necessary to check both sub-expressions, for
7720     // example, because the condition expression is a constant that can be
7721     // evaluated at compile time.
7722     bool CheckLeft = true, CheckRight = true;
7723 
7724     bool Cond;
7725     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7726                                                  S.isConstantEvaluated())) {
7727       if (Cond)
7728         CheckRight = false;
7729       else
7730         CheckLeft = false;
7731     }
7732 
7733     // We need to maintain the offsets for the right and the left hand side
7734     // separately to check if every possible indexed expression is a valid
7735     // string literal. They might have different offsets for different string
7736     // literals in the end.
7737     StringLiteralCheckType Left;
7738     if (!CheckLeft)
7739       Left = SLCT_UncheckedLiteral;
7740     else {
7741       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7742                                    HasVAListArg, format_idx, firstDataArg,
7743                                    Type, CallType, InFunctionCall,
7744                                    CheckedVarArgs, UncoveredArg, Offset,
7745                                    IgnoreStringsWithoutSpecifiers);
7746       if (Left == SLCT_NotALiteral || !CheckRight) {
7747         return Left;
7748       }
7749     }
7750 
7751     StringLiteralCheckType Right = checkFormatStringExpr(
7752         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7753         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7754         IgnoreStringsWithoutSpecifiers);
7755 
7756     return (CheckLeft && Left < Right) ? Left : Right;
7757   }
7758 
7759   case Stmt::ImplicitCastExprClass:
7760     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7761     goto tryAgain;
7762 
7763   case Stmt::OpaqueValueExprClass:
7764     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7765       E = src;
7766       goto tryAgain;
7767     }
7768     return SLCT_NotALiteral;
7769 
7770   case Stmt::PredefinedExprClass:
7771     // While __func__, etc., are technically not string literals, they
7772     // cannot contain format specifiers and thus are not a security
7773     // liability.
7774     return SLCT_UncheckedLiteral;
7775 
7776   case Stmt::DeclRefExprClass: {
7777     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7778 
7779     // As an exception, do not flag errors for variables binding to
7780     // const string literals.
7781     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7782       bool isConstant = false;
7783       QualType T = DR->getType();
7784 
7785       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7786         isConstant = AT->getElementType().isConstant(S.Context);
7787       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7788         isConstant = T.isConstant(S.Context) &&
7789                      PT->getPointeeType().isConstant(S.Context);
7790       } else if (T->isObjCObjectPointerType()) {
7791         // In ObjC, there is usually no "const ObjectPointer" type,
7792         // so don't check if the pointee type is constant.
7793         isConstant = T.isConstant(S.Context);
7794       }
7795 
7796       if (isConstant) {
7797         if (const Expr *Init = VD->getAnyInitializer()) {
7798           // Look through initializers like const char c[] = { "foo" }
7799           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7800             if (InitList->isStringLiteralInit())
7801               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7802           }
7803           return checkFormatStringExpr(S, Init, Args,
7804                                        HasVAListArg, format_idx,
7805                                        firstDataArg, Type, CallType,
7806                                        /*InFunctionCall*/ false, CheckedVarArgs,
7807                                        UncoveredArg, Offset);
7808         }
7809       }
7810 
7811       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7812       // special check to see if the format string is a function parameter
7813       // of the function calling the printf function.  If the function
7814       // has an attribute indicating it is a printf-like function, then we
7815       // should suppress warnings concerning non-literals being used in a call
7816       // to a vprintf function.  For example:
7817       //
7818       // void
7819       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7820       //      va_list ap;
7821       //      va_start(ap, fmt);
7822       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7823       //      ...
7824       // }
7825       if (HasVAListArg) {
7826         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7827           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7828             int PVIndex = PV->getFunctionScopeIndex() + 1;
7829             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7830               // adjust for implicit parameter
7831               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7832                 if (MD->isInstance())
7833                   ++PVIndex;
7834               // We also check if the formats are compatible.
7835               // We can't pass a 'scanf' string to a 'printf' function.
7836               if (PVIndex == PVFormat->getFormatIdx() &&
7837                   Type == S.GetFormatStringType(PVFormat))
7838                 return SLCT_UncheckedLiteral;
7839             }
7840           }
7841         }
7842       }
7843     }
7844 
7845     return SLCT_NotALiteral;
7846   }
7847 
7848   case Stmt::CallExprClass:
7849   case Stmt::CXXMemberCallExprClass: {
7850     const CallExpr *CE = cast<CallExpr>(E);
7851     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7852       bool IsFirst = true;
7853       StringLiteralCheckType CommonResult;
7854       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7855         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7856         StringLiteralCheckType Result = checkFormatStringExpr(
7857             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7858             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7859             IgnoreStringsWithoutSpecifiers);
7860         if (IsFirst) {
7861           CommonResult = Result;
7862           IsFirst = false;
7863         }
7864       }
7865       if (!IsFirst)
7866         return CommonResult;
7867 
7868       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7869         unsigned BuiltinID = FD->getBuiltinID();
7870         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7871             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7872           const Expr *Arg = CE->getArg(0);
7873           return checkFormatStringExpr(S, Arg, Args,
7874                                        HasVAListArg, format_idx,
7875                                        firstDataArg, Type, CallType,
7876                                        InFunctionCall, CheckedVarArgs,
7877                                        UncoveredArg, Offset,
7878                                        IgnoreStringsWithoutSpecifiers);
7879         }
7880       }
7881     }
7882 
7883     return SLCT_NotALiteral;
7884   }
7885   case Stmt::ObjCMessageExprClass: {
7886     const auto *ME = cast<ObjCMessageExpr>(E);
7887     if (const auto *MD = ME->getMethodDecl()) {
7888       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7889         // As a special case heuristic, if we're using the method -[NSBundle
7890         // localizedStringForKey:value:table:], ignore any key strings that lack
7891         // format specifiers. The idea is that if the key doesn't have any
7892         // format specifiers then its probably just a key to map to the
7893         // localized strings. If it does have format specifiers though, then its
7894         // likely that the text of the key is the format string in the
7895         // programmer's language, and should be checked.
7896         const ObjCInterfaceDecl *IFace;
7897         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7898             IFace->getIdentifier()->isStr("NSBundle") &&
7899             MD->getSelector().isKeywordSelector(
7900                 {"localizedStringForKey", "value", "table"})) {
7901           IgnoreStringsWithoutSpecifiers = true;
7902         }
7903 
7904         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7905         return checkFormatStringExpr(
7906             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7907             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7908             IgnoreStringsWithoutSpecifiers);
7909       }
7910     }
7911 
7912     return SLCT_NotALiteral;
7913   }
7914   case Stmt::ObjCStringLiteralClass:
7915   case Stmt::StringLiteralClass: {
7916     const StringLiteral *StrE = nullptr;
7917 
7918     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7919       StrE = ObjCFExpr->getString();
7920     else
7921       StrE = cast<StringLiteral>(E);
7922 
7923     if (StrE) {
7924       if (Offset.isNegative() || Offset > StrE->getLength()) {
7925         // TODO: It would be better to have an explicit warning for out of
7926         // bounds literals.
7927         return SLCT_NotALiteral;
7928       }
7929       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7930       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7931                         firstDataArg, Type, InFunctionCall, CallType,
7932                         CheckedVarArgs, UncoveredArg,
7933                         IgnoreStringsWithoutSpecifiers);
7934       return SLCT_CheckedLiteral;
7935     }
7936 
7937     return SLCT_NotALiteral;
7938   }
7939   case Stmt::BinaryOperatorClass: {
7940     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7941 
7942     // A string literal + an int offset is still a string literal.
7943     if (BinOp->isAdditiveOp()) {
7944       Expr::EvalResult LResult, RResult;
7945 
7946       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7947           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7948       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7949           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7950 
7951       if (LIsInt != RIsInt) {
7952         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7953 
7954         if (LIsInt) {
7955           if (BinOpKind == BO_Add) {
7956             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7957             E = BinOp->getRHS();
7958             goto tryAgain;
7959           }
7960         } else {
7961           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7962           E = BinOp->getLHS();
7963           goto tryAgain;
7964         }
7965       }
7966     }
7967 
7968     return SLCT_NotALiteral;
7969   }
7970   case Stmt::UnaryOperatorClass: {
7971     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7972     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7973     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7974       Expr::EvalResult IndexResult;
7975       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7976                                        Expr::SE_NoSideEffects,
7977                                        S.isConstantEvaluated())) {
7978         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7979                    /*RHS is int*/ true);
7980         E = ASE->getBase();
7981         goto tryAgain;
7982       }
7983     }
7984 
7985     return SLCT_NotALiteral;
7986   }
7987 
7988   default:
7989     return SLCT_NotALiteral;
7990   }
7991 }
7992 
7993 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7994   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7995       .Case("scanf", FST_Scanf)
7996       .Cases("printf", "printf0", FST_Printf)
7997       .Cases("NSString", "CFString", FST_NSString)
7998       .Case("strftime", FST_Strftime)
7999       .Case("strfmon", FST_Strfmon)
8000       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8001       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8002       .Case("os_trace", FST_OSLog)
8003       .Case("os_log", FST_OSLog)
8004       .Default(FST_Unknown);
8005 }
8006 
8007 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8008 /// functions) for correct use of format strings.
8009 /// Returns true if a format string has been fully checked.
8010 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8011                                 ArrayRef<const Expr *> Args,
8012                                 bool IsCXXMember,
8013                                 VariadicCallType CallType,
8014                                 SourceLocation Loc, SourceRange Range,
8015                                 llvm::SmallBitVector &CheckedVarArgs) {
8016   FormatStringInfo FSI;
8017   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8018     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8019                                 FSI.FirstDataArg, GetFormatStringType(Format),
8020                                 CallType, Loc, Range, CheckedVarArgs);
8021   return false;
8022 }
8023 
8024 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8025                                 bool HasVAListArg, unsigned format_idx,
8026                                 unsigned firstDataArg, FormatStringType Type,
8027                                 VariadicCallType CallType,
8028                                 SourceLocation Loc, SourceRange Range,
8029                                 llvm::SmallBitVector &CheckedVarArgs) {
8030   // CHECK: printf/scanf-like function is called with no format string.
8031   if (format_idx >= Args.size()) {
8032     Diag(Loc, diag::warn_missing_format_string) << Range;
8033     return false;
8034   }
8035 
8036   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8037 
8038   // CHECK: format string is not a string literal.
8039   //
8040   // Dynamically generated format strings are difficult to
8041   // automatically vet at compile time.  Requiring that format strings
8042   // are string literals: (1) permits the checking of format strings by
8043   // the compiler and thereby (2) can practically remove the source of
8044   // many format string exploits.
8045 
8046   // Format string can be either ObjC string (e.g. @"%d") or
8047   // C string (e.g. "%d")
8048   // ObjC string uses the same format specifiers as C string, so we can use
8049   // the same format string checking logic for both ObjC and C strings.
8050   UncoveredArgHandler UncoveredArg;
8051   StringLiteralCheckType CT =
8052       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8053                             format_idx, firstDataArg, Type, CallType,
8054                             /*IsFunctionCall*/ true, CheckedVarArgs,
8055                             UncoveredArg,
8056                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8057 
8058   // Generate a diagnostic where an uncovered argument is detected.
8059   if (UncoveredArg.hasUncoveredArg()) {
8060     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8061     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8062     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8063   }
8064 
8065   if (CT != SLCT_NotALiteral)
8066     // Literal format string found, check done!
8067     return CT == SLCT_CheckedLiteral;
8068 
8069   // Strftime is particular as it always uses a single 'time' argument,
8070   // so it is safe to pass a non-literal string.
8071   if (Type == FST_Strftime)
8072     return false;
8073 
8074   // Do not emit diag when the string param is a macro expansion and the
8075   // format is either NSString or CFString. This is a hack to prevent
8076   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8077   // which are usually used in place of NS and CF string literals.
8078   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8079   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8080     return false;
8081 
8082   // If there are no arguments specified, warn with -Wformat-security, otherwise
8083   // warn only with -Wformat-nonliteral.
8084   if (Args.size() == firstDataArg) {
8085     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8086       << OrigFormatExpr->getSourceRange();
8087     switch (Type) {
8088     default:
8089       break;
8090     case FST_Kprintf:
8091     case FST_FreeBSDKPrintf:
8092     case FST_Printf:
8093       Diag(FormatLoc, diag::note_format_security_fixit)
8094         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8095       break;
8096     case FST_NSString:
8097       Diag(FormatLoc, diag::note_format_security_fixit)
8098         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8099       break;
8100     }
8101   } else {
8102     Diag(FormatLoc, diag::warn_format_nonliteral)
8103       << OrigFormatExpr->getSourceRange();
8104   }
8105   return false;
8106 }
8107 
8108 namespace {
8109 
8110 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8111 protected:
8112   Sema &S;
8113   const FormatStringLiteral *FExpr;
8114   const Expr *OrigFormatExpr;
8115   const Sema::FormatStringType FSType;
8116   const unsigned FirstDataArg;
8117   const unsigned NumDataArgs;
8118   const char *Beg; // Start of format string.
8119   const bool HasVAListArg;
8120   ArrayRef<const Expr *> Args;
8121   unsigned FormatIdx;
8122   llvm::SmallBitVector CoveredArgs;
8123   bool usesPositionalArgs = false;
8124   bool atFirstArg = true;
8125   bool inFunctionCall;
8126   Sema::VariadicCallType CallType;
8127   llvm::SmallBitVector &CheckedVarArgs;
8128   UncoveredArgHandler &UncoveredArg;
8129 
8130 public:
8131   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8132                      const Expr *origFormatExpr,
8133                      const Sema::FormatStringType type, unsigned firstDataArg,
8134                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8135                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8136                      bool inFunctionCall, Sema::VariadicCallType callType,
8137                      llvm::SmallBitVector &CheckedVarArgs,
8138                      UncoveredArgHandler &UncoveredArg)
8139       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8140         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8141         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8142         inFunctionCall(inFunctionCall), CallType(callType),
8143         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8144     CoveredArgs.resize(numDataArgs);
8145     CoveredArgs.reset();
8146   }
8147 
8148   void DoneProcessing();
8149 
8150   void HandleIncompleteSpecifier(const char *startSpecifier,
8151                                  unsigned specifierLen) override;
8152 
8153   void HandleInvalidLengthModifier(
8154                            const analyze_format_string::FormatSpecifier &FS,
8155                            const analyze_format_string::ConversionSpecifier &CS,
8156                            const char *startSpecifier, unsigned specifierLen,
8157                            unsigned DiagID);
8158 
8159   void HandleNonStandardLengthModifier(
8160                     const analyze_format_string::FormatSpecifier &FS,
8161                     const char *startSpecifier, unsigned specifierLen);
8162 
8163   void HandleNonStandardConversionSpecifier(
8164                     const analyze_format_string::ConversionSpecifier &CS,
8165                     const char *startSpecifier, unsigned specifierLen);
8166 
8167   void HandlePosition(const char *startPos, unsigned posLen) override;
8168 
8169   void HandleInvalidPosition(const char *startSpecifier,
8170                              unsigned specifierLen,
8171                              analyze_format_string::PositionContext p) override;
8172 
8173   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8174 
8175   void HandleNullChar(const char *nullCharacter) override;
8176 
8177   template <typename Range>
8178   static void
8179   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8180                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8181                        bool IsStringLocation, Range StringRange,
8182                        ArrayRef<FixItHint> Fixit = None);
8183 
8184 protected:
8185   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8186                                         const char *startSpec,
8187                                         unsigned specifierLen,
8188                                         const char *csStart, unsigned csLen);
8189 
8190   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8191                                          const char *startSpec,
8192                                          unsigned specifierLen);
8193 
8194   SourceRange getFormatStringRange();
8195   CharSourceRange getSpecifierRange(const char *startSpecifier,
8196                                     unsigned specifierLen);
8197   SourceLocation getLocationOfByte(const char *x);
8198 
8199   const Expr *getDataArg(unsigned i) const;
8200 
8201   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8202                     const analyze_format_string::ConversionSpecifier &CS,
8203                     const char *startSpecifier, unsigned specifierLen,
8204                     unsigned argIndex);
8205 
8206   template <typename Range>
8207   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8208                             bool IsStringLocation, Range StringRange,
8209                             ArrayRef<FixItHint> Fixit = None);
8210 };
8211 
8212 } // namespace
8213 
8214 SourceRange CheckFormatHandler::getFormatStringRange() {
8215   return OrigFormatExpr->getSourceRange();
8216 }
8217 
8218 CharSourceRange CheckFormatHandler::
8219 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8220   SourceLocation Start = getLocationOfByte(startSpecifier);
8221   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8222 
8223   // Advance the end SourceLocation by one due to half-open ranges.
8224   End = End.getLocWithOffset(1);
8225 
8226   return CharSourceRange::getCharRange(Start, End);
8227 }
8228 
8229 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8230   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8231                                   S.getLangOpts(), S.Context.getTargetInfo());
8232 }
8233 
8234 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8235                                                    unsigned specifierLen){
8236   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8237                        getLocationOfByte(startSpecifier),
8238                        /*IsStringLocation*/true,
8239                        getSpecifierRange(startSpecifier, specifierLen));
8240 }
8241 
8242 void CheckFormatHandler::HandleInvalidLengthModifier(
8243     const analyze_format_string::FormatSpecifier &FS,
8244     const analyze_format_string::ConversionSpecifier &CS,
8245     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8246   using namespace analyze_format_string;
8247 
8248   const LengthModifier &LM = FS.getLengthModifier();
8249   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8250 
8251   // See if we know how to fix this length modifier.
8252   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8253   if (FixedLM) {
8254     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8255                          getLocationOfByte(LM.getStart()),
8256                          /*IsStringLocation*/true,
8257                          getSpecifierRange(startSpecifier, specifierLen));
8258 
8259     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8260       << FixedLM->toString()
8261       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8262 
8263   } else {
8264     FixItHint Hint;
8265     if (DiagID == diag::warn_format_nonsensical_length)
8266       Hint = FixItHint::CreateRemoval(LMRange);
8267 
8268     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8269                          getLocationOfByte(LM.getStart()),
8270                          /*IsStringLocation*/true,
8271                          getSpecifierRange(startSpecifier, specifierLen),
8272                          Hint);
8273   }
8274 }
8275 
8276 void CheckFormatHandler::HandleNonStandardLengthModifier(
8277     const analyze_format_string::FormatSpecifier &FS,
8278     const char *startSpecifier, unsigned specifierLen) {
8279   using namespace analyze_format_string;
8280 
8281   const LengthModifier &LM = FS.getLengthModifier();
8282   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8283 
8284   // See if we know how to fix this length modifier.
8285   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8286   if (FixedLM) {
8287     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8288                            << LM.toString() << 0,
8289                          getLocationOfByte(LM.getStart()),
8290                          /*IsStringLocation*/true,
8291                          getSpecifierRange(startSpecifier, specifierLen));
8292 
8293     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8294       << FixedLM->toString()
8295       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8296 
8297   } else {
8298     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8299                            << LM.toString() << 0,
8300                          getLocationOfByte(LM.getStart()),
8301                          /*IsStringLocation*/true,
8302                          getSpecifierRange(startSpecifier, specifierLen));
8303   }
8304 }
8305 
8306 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8307     const analyze_format_string::ConversionSpecifier &CS,
8308     const char *startSpecifier, unsigned specifierLen) {
8309   using namespace analyze_format_string;
8310 
8311   // See if we know how to fix this conversion specifier.
8312   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8313   if (FixedCS) {
8314     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8315                           << CS.toString() << /*conversion specifier*/1,
8316                          getLocationOfByte(CS.getStart()),
8317                          /*IsStringLocation*/true,
8318                          getSpecifierRange(startSpecifier, specifierLen));
8319 
8320     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8321     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8322       << FixedCS->toString()
8323       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8324   } else {
8325     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8326                           << CS.toString() << /*conversion specifier*/1,
8327                          getLocationOfByte(CS.getStart()),
8328                          /*IsStringLocation*/true,
8329                          getSpecifierRange(startSpecifier, specifierLen));
8330   }
8331 }
8332 
8333 void CheckFormatHandler::HandlePosition(const char *startPos,
8334                                         unsigned posLen) {
8335   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8336                                getLocationOfByte(startPos),
8337                                /*IsStringLocation*/true,
8338                                getSpecifierRange(startPos, posLen));
8339 }
8340 
8341 void
8342 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8343                                      analyze_format_string::PositionContext p) {
8344   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8345                          << (unsigned) p,
8346                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8347                        getSpecifierRange(startPos, posLen));
8348 }
8349 
8350 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8351                                             unsigned posLen) {
8352   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8353                                getLocationOfByte(startPos),
8354                                /*IsStringLocation*/true,
8355                                getSpecifierRange(startPos, posLen));
8356 }
8357 
8358 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8359   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8360     // The presence of a null character is likely an error.
8361     EmitFormatDiagnostic(
8362       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8363       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8364       getFormatStringRange());
8365   }
8366 }
8367 
8368 // Note that this may return NULL if there was an error parsing or building
8369 // one of the argument expressions.
8370 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8371   return Args[FirstDataArg + i];
8372 }
8373 
8374 void CheckFormatHandler::DoneProcessing() {
8375   // Does the number of data arguments exceed the number of
8376   // format conversions in the format string?
8377   if (!HasVAListArg) {
8378       // Find any arguments that weren't covered.
8379     CoveredArgs.flip();
8380     signed notCoveredArg = CoveredArgs.find_first();
8381     if (notCoveredArg >= 0) {
8382       assert((unsigned)notCoveredArg < NumDataArgs);
8383       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8384     } else {
8385       UncoveredArg.setAllCovered();
8386     }
8387   }
8388 }
8389 
8390 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8391                                    const Expr *ArgExpr) {
8392   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8393          "Invalid state");
8394 
8395   if (!ArgExpr)
8396     return;
8397 
8398   SourceLocation Loc = ArgExpr->getBeginLoc();
8399 
8400   if (S.getSourceManager().isInSystemMacro(Loc))
8401     return;
8402 
8403   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8404   for (auto E : DiagnosticExprs)
8405     PDiag << E->getSourceRange();
8406 
8407   CheckFormatHandler::EmitFormatDiagnostic(
8408                                   S, IsFunctionCall, DiagnosticExprs[0],
8409                                   PDiag, Loc, /*IsStringLocation*/false,
8410                                   DiagnosticExprs[0]->getSourceRange());
8411 }
8412 
8413 bool
8414 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8415                                                      SourceLocation Loc,
8416                                                      const char *startSpec,
8417                                                      unsigned specifierLen,
8418                                                      const char *csStart,
8419                                                      unsigned csLen) {
8420   bool keepGoing = true;
8421   if (argIndex < NumDataArgs) {
8422     // Consider the argument coverered, even though the specifier doesn't
8423     // make sense.
8424     CoveredArgs.set(argIndex);
8425   }
8426   else {
8427     // If argIndex exceeds the number of data arguments we
8428     // don't issue a warning because that is just a cascade of warnings (and
8429     // they may have intended '%%' anyway). We don't want to continue processing
8430     // the format string after this point, however, as we will like just get
8431     // gibberish when trying to match arguments.
8432     keepGoing = false;
8433   }
8434 
8435   StringRef Specifier(csStart, csLen);
8436 
8437   // If the specifier in non-printable, it could be the first byte of a UTF-8
8438   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8439   // hex value.
8440   std::string CodePointStr;
8441   if (!llvm::sys::locale::isPrint(*csStart)) {
8442     llvm::UTF32 CodePoint;
8443     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8444     const llvm::UTF8 *E =
8445         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8446     llvm::ConversionResult Result =
8447         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8448 
8449     if (Result != llvm::conversionOK) {
8450       unsigned char FirstChar = *csStart;
8451       CodePoint = (llvm::UTF32)FirstChar;
8452     }
8453 
8454     llvm::raw_string_ostream OS(CodePointStr);
8455     if (CodePoint < 256)
8456       OS << "\\x" << llvm::format("%02x", CodePoint);
8457     else if (CodePoint <= 0xFFFF)
8458       OS << "\\u" << llvm::format("%04x", CodePoint);
8459     else
8460       OS << "\\U" << llvm::format("%08x", CodePoint);
8461     OS.flush();
8462     Specifier = CodePointStr;
8463   }
8464 
8465   EmitFormatDiagnostic(
8466       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8467       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8468 
8469   return keepGoing;
8470 }
8471 
8472 void
8473 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8474                                                       const char *startSpec,
8475                                                       unsigned specifierLen) {
8476   EmitFormatDiagnostic(
8477     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8478     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8479 }
8480 
8481 bool
8482 CheckFormatHandler::CheckNumArgs(
8483   const analyze_format_string::FormatSpecifier &FS,
8484   const analyze_format_string::ConversionSpecifier &CS,
8485   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8486 
8487   if (argIndex >= NumDataArgs) {
8488     PartialDiagnostic PDiag = FS.usesPositionalArg()
8489       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8490            << (argIndex+1) << NumDataArgs)
8491       : S.PDiag(diag::warn_printf_insufficient_data_args);
8492     EmitFormatDiagnostic(
8493       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8494       getSpecifierRange(startSpecifier, specifierLen));
8495 
8496     // Since more arguments than conversion tokens are given, by extension
8497     // all arguments are covered, so mark this as so.
8498     UncoveredArg.setAllCovered();
8499     return false;
8500   }
8501   return true;
8502 }
8503 
8504 template<typename Range>
8505 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8506                                               SourceLocation Loc,
8507                                               bool IsStringLocation,
8508                                               Range StringRange,
8509                                               ArrayRef<FixItHint> FixIt) {
8510   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8511                        Loc, IsStringLocation, StringRange, FixIt);
8512 }
8513 
8514 /// If the format string is not within the function call, emit a note
8515 /// so that the function call and string are in diagnostic messages.
8516 ///
8517 /// \param InFunctionCall if true, the format string is within the function
8518 /// call and only one diagnostic message will be produced.  Otherwise, an
8519 /// extra note will be emitted pointing to location of the format string.
8520 ///
8521 /// \param ArgumentExpr the expression that is passed as the format string
8522 /// argument in the function call.  Used for getting locations when two
8523 /// diagnostics are emitted.
8524 ///
8525 /// \param PDiag the callee should already have provided any strings for the
8526 /// diagnostic message.  This function only adds locations and fixits
8527 /// to diagnostics.
8528 ///
8529 /// \param Loc primary location for diagnostic.  If two diagnostics are
8530 /// required, one will be at Loc and a new SourceLocation will be created for
8531 /// the other one.
8532 ///
8533 /// \param IsStringLocation if true, Loc points to the format string should be
8534 /// used for the note.  Otherwise, Loc points to the argument list and will
8535 /// be used with PDiag.
8536 ///
8537 /// \param StringRange some or all of the string to highlight.  This is
8538 /// templated so it can accept either a CharSourceRange or a SourceRange.
8539 ///
8540 /// \param FixIt optional fix it hint for the format string.
8541 template <typename Range>
8542 void CheckFormatHandler::EmitFormatDiagnostic(
8543     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8544     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8545     Range StringRange, ArrayRef<FixItHint> FixIt) {
8546   if (InFunctionCall) {
8547     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8548     D << StringRange;
8549     D << FixIt;
8550   } else {
8551     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8552       << ArgumentExpr->getSourceRange();
8553 
8554     const Sema::SemaDiagnosticBuilder &Note =
8555       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8556              diag::note_format_string_defined);
8557 
8558     Note << StringRange;
8559     Note << FixIt;
8560   }
8561 }
8562 
8563 //===--- CHECK: Printf format string checking ------------------------------===//
8564 
8565 namespace {
8566 
8567 class CheckPrintfHandler : public CheckFormatHandler {
8568 public:
8569   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8570                      const Expr *origFormatExpr,
8571                      const Sema::FormatStringType type, unsigned firstDataArg,
8572                      unsigned numDataArgs, bool isObjC, const char *beg,
8573                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8574                      unsigned formatIdx, bool inFunctionCall,
8575                      Sema::VariadicCallType CallType,
8576                      llvm::SmallBitVector &CheckedVarArgs,
8577                      UncoveredArgHandler &UncoveredArg)
8578       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8579                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8580                            inFunctionCall, CallType, CheckedVarArgs,
8581                            UncoveredArg) {}
8582 
8583   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8584 
8585   /// Returns true if '%@' specifiers are allowed in the format string.
8586   bool allowsObjCArg() const {
8587     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8588            FSType == Sema::FST_OSTrace;
8589   }
8590 
8591   bool HandleInvalidPrintfConversionSpecifier(
8592                                       const analyze_printf::PrintfSpecifier &FS,
8593                                       const char *startSpecifier,
8594                                       unsigned specifierLen) override;
8595 
8596   void handleInvalidMaskType(StringRef MaskType) override;
8597 
8598   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8599                              const char *startSpecifier,
8600                              unsigned specifierLen) override;
8601   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8602                        const char *StartSpecifier,
8603                        unsigned SpecifierLen,
8604                        const Expr *E);
8605 
8606   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8607                     const char *startSpecifier, unsigned specifierLen);
8608   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8609                            const analyze_printf::OptionalAmount &Amt,
8610                            unsigned type,
8611                            const char *startSpecifier, unsigned specifierLen);
8612   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8613                   const analyze_printf::OptionalFlag &flag,
8614                   const char *startSpecifier, unsigned specifierLen);
8615   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8616                          const analyze_printf::OptionalFlag &ignoredFlag,
8617                          const analyze_printf::OptionalFlag &flag,
8618                          const char *startSpecifier, unsigned specifierLen);
8619   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8620                            const Expr *E);
8621 
8622   void HandleEmptyObjCModifierFlag(const char *startFlag,
8623                                    unsigned flagLen) override;
8624 
8625   void HandleInvalidObjCModifierFlag(const char *startFlag,
8626                                             unsigned flagLen) override;
8627 
8628   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8629                                            const char *flagsEnd,
8630                                            const char *conversionPosition)
8631                                              override;
8632 };
8633 
8634 } // namespace
8635 
8636 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8637                                       const analyze_printf::PrintfSpecifier &FS,
8638                                       const char *startSpecifier,
8639                                       unsigned specifierLen) {
8640   const analyze_printf::PrintfConversionSpecifier &CS =
8641     FS.getConversionSpecifier();
8642 
8643   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8644                                           getLocationOfByte(CS.getStart()),
8645                                           startSpecifier, specifierLen,
8646                                           CS.getStart(), CS.getLength());
8647 }
8648 
8649 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8650   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8651 }
8652 
8653 bool CheckPrintfHandler::HandleAmount(
8654                                const analyze_format_string::OptionalAmount &Amt,
8655                                unsigned k, const char *startSpecifier,
8656                                unsigned specifierLen) {
8657   if (Amt.hasDataArgument()) {
8658     if (!HasVAListArg) {
8659       unsigned argIndex = Amt.getArgIndex();
8660       if (argIndex >= NumDataArgs) {
8661         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8662                                << k,
8663                              getLocationOfByte(Amt.getStart()),
8664                              /*IsStringLocation*/true,
8665                              getSpecifierRange(startSpecifier, specifierLen));
8666         // Don't do any more checking.  We will just emit
8667         // spurious errors.
8668         return false;
8669       }
8670 
8671       // Type check the data argument.  It should be an 'int'.
8672       // Although not in conformance with C99, we also allow the argument to be
8673       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8674       // doesn't emit a warning for that case.
8675       CoveredArgs.set(argIndex);
8676       const Expr *Arg = getDataArg(argIndex);
8677       if (!Arg)
8678         return false;
8679 
8680       QualType T = Arg->getType();
8681 
8682       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8683       assert(AT.isValid());
8684 
8685       if (!AT.matchesType(S.Context, T)) {
8686         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8687                                << k << AT.getRepresentativeTypeName(S.Context)
8688                                << T << Arg->getSourceRange(),
8689                              getLocationOfByte(Amt.getStart()),
8690                              /*IsStringLocation*/true,
8691                              getSpecifierRange(startSpecifier, specifierLen));
8692         // Don't do any more checking.  We will just emit
8693         // spurious errors.
8694         return false;
8695       }
8696     }
8697   }
8698   return true;
8699 }
8700 
8701 void CheckPrintfHandler::HandleInvalidAmount(
8702                                       const analyze_printf::PrintfSpecifier &FS,
8703                                       const analyze_printf::OptionalAmount &Amt,
8704                                       unsigned type,
8705                                       const char *startSpecifier,
8706                                       unsigned specifierLen) {
8707   const analyze_printf::PrintfConversionSpecifier &CS =
8708     FS.getConversionSpecifier();
8709 
8710   FixItHint fixit =
8711     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8712       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8713                                  Amt.getConstantLength()))
8714       : FixItHint();
8715 
8716   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8717                          << type << CS.toString(),
8718                        getLocationOfByte(Amt.getStart()),
8719                        /*IsStringLocation*/true,
8720                        getSpecifierRange(startSpecifier, specifierLen),
8721                        fixit);
8722 }
8723 
8724 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8725                                     const analyze_printf::OptionalFlag &flag,
8726                                     const char *startSpecifier,
8727                                     unsigned specifierLen) {
8728   // Warn about pointless flag with a fixit removal.
8729   const analyze_printf::PrintfConversionSpecifier &CS =
8730     FS.getConversionSpecifier();
8731   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8732                          << flag.toString() << CS.toString(),
8733                        getLocationOfByte(flag.getPosition()),
8734                        /*IsStringLocation*/true,
8735                        getSpecifierRange(startSpecifier, specifierLen),
8736                        FixItHint::CreateRemoval(
8737                          getSpecifierRange(flag.getPosition(), 1)));
8738 }
8739 
8740 void CheckPrintfHandler::HandleIgnoredFlag(
8741                                 const analyze_printf::PrintfSpecifier &FS,
8742                                 const analyze_printf::OptionalFlag &ignoredFlag,
8743                                 const analyze_printf::OptionalFlag &flag,
8744                                 const char *startSpecifier,
8745                                 unsigned specifierLen) {
8746   // Warn about ignored flag with a fixit removal.
8747   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8748                          << ignoredFlag.toString() << flag.toString(),
8749                        getLocationOfByte(ignoredFlag.getPosition()),
8750                        /*IsStringLocation*/true,
8751                        getSpecifierRange(startSpecifier, specifierLen),
8752                        FixItHint::CreateRemoval(
8753                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8754 }
8755 
8756 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8757                                                      unsigned flagLen) {
8758   // Warn about an empty flag.
8759   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8760                        getLocationOfByte(startFlag),
8761                        /*IsStringLocation*/true,
8762                        getSpecifierRange(startFlag, flagLen));
8763 }
8764 
8765 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8766                                                        unsigned flagLen) {
8767   // Warn about an invalid flag.
8768   auto Range = getSpecifierRange(startFlag, flagLen);
8769   StringRef flag(startFlag, flagLen);
8770   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8771                       getLocationOfByte(startFlag),
8772                       /*IsStringLocation*/true,
8773                       Range, FixItHint::CreateRemoval(Range));
8774 }
8775 
8776 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8777     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8778     // Warn about using '[...]' without a '@' conversion.
8779     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8780     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8781     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8782                          getLocationOfByte(conversionPosition),
8783                          /*IsStringLocation*/true,
8784                          Range, FixItHint::CreateRemoval(Range));
8785 }
8786 
8787 // Determines if the specified is a C++ class or struct containing
8788 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8789 // "c_str()").
8790 template<typename MemberKind>
8791 static llvm::SmallPtrSet<MemberKind*, 1>
8792 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8793   const RecordType *RT = Ty->getAs<RecordType>();
8794   llvm::SmallPtrSet<MemberKind*, 1> Results;
8795 
8796   if (!RT)
8797     return Results;
8798   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8799   if (!RD || !RD->getDefinition())
8800     return Results;
8801 
8802   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8803                  Sema::LookupMemberName);
8804   R.suppressDiagnostics();
8805 
8806   // We just need to include all members of the right kind turned up by the
8807   // filter, at this point.
8808   if (S.LookupQualifiedName(R, RT->getDecl()))
8809     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8810       NamedDecl *decl = (*I)->getUnderlyingDecl();
8811       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8812         Results.insert(FK);
8813     }
8814   return Results;
8815 }
8816 
8817 /// Check if we could call '.c_str()' on an object.
8818 ///
8819 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8820 /// allow the call, or if it would be ambiguous).
8821 bool Sema::hasCStrMethod(const Expr *E) {
8822   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8823 
8824   MethodSet Results =
8825       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8826   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8827        MI != ME; ++MI)
8828     if ((*MI)->getMinRequiredArguments() == 0)
8829       return true;
8830   return false;
8831 }
8832 
8833 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8834 // better diagnostic if so. AT is assumed to be valid.
8835 // Returns true when a c_str() conversion method is found.
8836 bool CheckPrintfHandler::checkForCStrMembers(
8837     const analyze_printf::ArgType &AT, const Expr *E) {
8838   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8839 
8840   MethodSet Results =
8841       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8842 
8843   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8844        MI != ME; ++MI) {
8845     const CXXMethodDecl *Method = *MI;
8846     if (Method->getMinRequiredArguments() == 0 &&
8847         AT.matchesType(S.Context, Method->getReturnType())) {
8848       // FIXME: Suggest parens if the expression needs them.
8849       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8850       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8851           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8852       return true;
8853     }
8854   }
8855 
8856   return false;
8857 }
8858 
8859 bool
8860 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8861                                             &FS,
8862                                           const char *startSpecifier,
8863                                           unsigned specifierLen) {
8864   using namespace analyze_format_string;
8865   using namespace analyze_printf;
8866 
8867   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8868 
8869   if (FS.consumesDataArgument()) {
8870     if (atFirstArg) {
8871         atFirstArg = false;
8872         usesPositionalArgs = FS.usesPositionalArg();
8873     }
8874     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8875       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8876                                         startSpecifier, specifierLen);
8877       return false;
8878     }
8879   }
8880 
8881   // First check if the field width, precision, and conversion specifier
8882   // have matching data arguments.
8883   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8884                     startSpecifier, specifierLen)) {
8885     return false;
8886   }
8887 
8888   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8889                     startSpecifier, specifierLen)) {
8890     return false;
8891   }
8892 
8893   if (!CS.consumesDataArgument()) {
8894     // FIXME: Technically specifying a precision or field width here
8895     // makes no sense.  Worth issuing a warning at some point.
8896     return true;
8897   }
8898 
8899   // Consume the argument.
8900   unsigned argIndex = FS.getArgIndex();
8901   if (argIndex < NumDataArgs) {
8902     // The check to see if the argIndex is valid will come later.
8903     // We set the bit here because we may exit early from this
8904     // function if we encounter some other error.
8905     CoveredArgs.set(argIndex);
8906   }
8907 
8908   // FreeBSD kernel extensions.
8909   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8910       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8911     // We need at least two arguments.
8912     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8913       return false;
8914 
8915     // Claim the second argument.
8916     CoveredArgs.set(argIndex + 1);
8917 
8918     // Type check the first argument (int for %b, pointer for %D)
8919     const Expr *Ex = getDataArg(argIndex);
8920     const analyze_printf::ArgType &AT =
8921       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8922         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8923     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8924       EmitFormatDiagnostic(
8925           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8926               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8927               << false << Ex->getSourceRange(),
8928           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8929           getSpecifierRange(startSpecifier, specifierLen));
8930 
8931     // Type check the second argument (char * for both %b and %D)
8932     Ex = getDataArg(argIndex + 1);
8933     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8934     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8935       EmitFormatDiagnostic(
8936           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8937               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8938               << false << Ex->getSourceRange(),
8939           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8940           getSpecifierRange(startSpecifier, specifierLen));
8941 
8942      return true;
8943   }
8944 
8945   // Check for using an Objective-C specific conversion specifier
8946   // in a non-ObjC literal.
8947   if (!allowsObjCArg() && CS.isObjCArg()) {
8948     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8949                                                   specifierLen);
8950   }
8951 
8952   // %P can only be used with os_log.
8953   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8954     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8955                                                   specifierLen);
8956   }
8957 
8958   // %n is not allowed with os_log.
8959   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8960     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8961                          getLocationOfByte(CS.getStart()),
8962                          /*IsStringLocation*/ false,
8963                          getSpecifierRange(startSpecifier, specifierLen));
8964 
8965     return true;
8966   }
8967 
8968   // Only scalars are allowed for os_trace.
8969   if (FSType == Sema::FST_OSTrace &&
8970       (CS.getKind() == ConversionSpecifier::PArg ||
8971        CS.getKind() == ConversionSpecifier::sArg ||
8972        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8973     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8974                                                   specifierLen);
8975   }
8976 
8977   // Check for use of public/private annotation outside of os_log().
8978   if (FSType != Sema::FST_OSLog) {
8979     if (FS.isPublic().isSet()) {
8980       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8981                                << "public",
8982                            getLocationOfByte(FS.isPublic().getPosition()),
8983                            /*IsStringLocation*/ false,
8984                            getSpecifierRange(startSpecifier, specifierLen));
8985     }
8986     if (FS.isPrivate().isSet()) {
8987       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8988                                << "private",
8989                            getLocationOfByte(FS.isPrivate().getPosition()),
8990                            /*IsStringLocation*/ false,
8991                            getSpecifierRange(startSpecifier, specifierLen));
8992     }
8993   }
8994 
8995   // Check for invalid use of field width
8996   if (!FS.hasValidFieldWidth()) {
8997     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8998         startSpecifier, specifierLen);
8999   }
9000 
9001   // Check for invalid use of precision
9002   if (!FS.hasValidPrecision()) {
9003     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9004         startSpecifier, specifierLen);
9005   }
9006 
9007   // Precision is mandatory for %P specifier.
9008   if (CS.getKind() == ConversionSpecifier::PArg &&
9009       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9010     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9011                          getLocationOfByte(startSpecifier),
9012                          /*IsStringLocation*/ false,
9013                          getSpecifierRange(startSpecifier, specifierLen));
9014   }
9015 
9016   // Check each flag does not conflict with any other component.
9017   if (!FS.hasValidThousandsGroupingPrefix())
9018     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9019   if (!FS.hasValidLeadingZeros())
9020     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9021   if (!FS.hasValidPlusPrefix())
9022     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9023   if (!FS.hasValidSpacePrefix())
9024     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9025   if (!FS.hasValidAlternativeForm())
9026     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9027   if (!FS.hasValidLeftJustified())
9028     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9029 
9030   // Check that flags are not ignored by another flag
9031   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9032     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9033         startSpecifier, specifierLen);
9034   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9035     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9036             startSpecifier, specifierLen);
9037 
9038   // Check the length modifier is valid with the given conversion specifier.
9039   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9040                                  S.getLangOpts()))
9041     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9042                                 diag::warn_format_nonsensical_length);
9043   else if (!FS.hasStandardLengthModifier())
9044     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9045   else if (!FS.hasStandardLengthConversionCombination())
9046     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9047                                 diag::warn_format_non_standard_conversion_spec);
9048 
9049   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9050     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9051 
9052   // The remaining checks depend on the data arguments.
9053   if (HasVAListArg)
9054     return true;
9055 
9056   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9057     return false;
9058 
9059   const Expr *Arg = getDataArg(argIndex);
9060   if (!Arg)
9061     return true;
9062 
9063   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9064 }
9065 
9066 static bool requiresParensToAddCast(const Expr *E) {
9067   // FIXME: We should have a general way to reason about operator
9068   // precedence and whether parens are actually needed here.
9069   // Take care of a few common cases where they aren't.
9070   const Expr *Inside = E->IgnoreImpCasts();
9071   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9072     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9073 
9074   switch (Inside->getStmtClass()) {
9075   case Stmt::ArraySubscriptExprClass:
9076   case Stmt::CallExprClass:
9077   case Stmt::CharacterLiteralClass:
9078   case Stmt::CXXBoolLiteralExprClass:
9079   case Stmt::DeclRefExprClass:
9080   case Stmt::FloatingLiteralClass:
9081   case Stmt::IntegerLiteralClass:
9082   case Stmt::MemberExprClass:
9083   case Stmt::ObjCArrayLiteralClass:
9084   case Stmt::ObjCBoolLiteralExprClass:
9085   case Stmt::ObjCBoxedExprClass:
9086   case Stmt::ObjCDictionaryLiteralClass:
9087   case Stmt::ObjCEncodeExprClass:
9088   case Stmt::ObjCIvarRefExprClass:
9089   case Stmt::ObjCMessageExprClass:
9090   case Stmt::ObjCPropertyRefExprClass:
9091   case Stmt::ObjCStringLiteralClass:
9092   case Stmt::ObjCSubscriptRefExprClass:
9093   case Stmt::ParenExprClass:
9094   case Stmt::StringLiteralClass:
9095   case Stmt::UnaryOperatorClass:
9096     return false;
9097   default:
9098     return true;
9099   }
9100 }
9101 
9102 static std::pair<QualType, StringRef>
9103 shouldNotPrintDirectly(const ASTContext &Context,
9104                        QualType IntendedTy,
9105                        const Expr *E) {
9106   // Use a 'while' to peel off layers of typedefs.
9107   QualType TyTy = IntendedTy;
9108   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9109     StringRef Name = UserTy->getDecl()->getName();
9110     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9111       .Case("CFIndex", Context.getNSIntegerType())
9112       .Case("NSInteger", Context.getNSIntegerType())
9113       .Case("NSUInteger", Context.getNSUIntegerType())
9114       .Case("SInt32", Context.IntTy)
9115       .Case("UInt32", Context.UnsignedIntTy)
9116       .Default(QualType());
9117 
9118     if (!CastTy.isNull())
9119       return std::make_pair(CastTy, Name);
9120 
9121     TyTy = UserTy->desugar();
9122   }
9123 
9124   // Strip parens if necessary.
9125   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9126     return shouldNotPrintDirectly(Context,
9127                                   PE->getSubExpr()->getType(),
9128                                   PE->getSubExpr());
9129 
9130   // If this is a conditional expression, then its result type is constructed
9131   // via usual arithmetic conversions and thus there might be no necessary
9132   // typedef sugar there.  Recurse to operands to check for NSInteger &
9133   // Co. usage condition.
9134   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9135     QualType TrueTy, FalseTy;
9136     StringRef TrueName, FalseName;
9137 
9138     std::tie(TrueTy, TrueName) =
9139       shouldNotPrintDirectly(Context,
9140                              CO->getTrueExpr()->getType(),
9141                              CO->getTrueExpr());
9142     std::tie(FalseTy, FalseName) =
9143       shouldNotPrintDirectly(Context,
9144                              CO->getFalseExpr()->getType(),
9145                              CO->getFalseExpr());
9146 
9147     if (TrueTy == FalseTy)
9148       return std::make_pair(TrueTy, TrueName);
9149     else if (TrueTy.isNull())
9150       return std::make_pair(FalseTy, FalseName);
9151     else if (FalseTy.isNull())
9152       return std::make_pair(TrueTy, TrueName);
9153   }
9154 
9155   return std::make_pair(QualType(), StringRef());
9156 }
9157 
9158 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9159 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9160 /// type do not count.
9161 static bool
9162 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9163   QualType From = ICE->getSubExpr()->getType();
9164   QualType To = ICE->getType();
9165   // It's an integer promotion if the destination type is the promoted
9166   // source type.
9167   if (ICE->getCastKind() == CK_IntegralCast &&
9168       From->isPromotableIntegerType() &&
9169       S.Context.getPromotedIntegerType(From) == To)
9170     return true;
9171   // Look through vector types, since we do default argument promotion for
9172   // those in OpenCL.
9173   if (const auto *VecTy = From->getAs<ExtVectorType>())
9174     From = VecTy->getElementType();
9175   if (const auto *VecTy = To->getAs<ExtVectorType>())
9176     To = VecTy->getElementType();
9177   // It's a floating promotion if the source type is a lower rank.
9178   return ICE->getCastKind() == CK_FloatingCast &&
9179          S.Context.getFloatingTypeOrder(From, To) < 0;
9180 }
9181 
9182 bool
9183 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9184                                     const char *StartSpecifier,
9185                                     unsigned SpecifierLen,
9186                                     const Expr *E) {
9187   using namespace analyze_format_string;
9188   using namespace analyze_printf;
9189 
9190   // Now type check the data expression that matches the
9191   // format specifier.
9192   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9193   if (!AT.isValid())
9194     return true;
9195 
9196   QualType ExprTy = E->getType();
9197   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9198     ExprTy = TET->getUnderlyingExpr()->getType();
9199   }
9200 
9201   // Diagnose attempts to print a boolean value as a character. Unlike other
9202   // -Wformat diagnostics, this is fine from a type perspective, but it still
9203   // doesn't make sense.
9204   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9205       E->isKnownToHaveBooleanValue()) {
9206     const CharSourceRange &CSR =
9207         getSpecifierRange(StartSpecifier, SpecifierLen);
9208     SmallString<4> FSString;
9209     llvm::raw_svector_ostream os(FSString);
9210     FS.toString(os);
9211     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9212                              << FSString,
9213                          E->getExprLoc(), false, CSR);
9214     return true;
9215   }
9216 
9217   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9218   if (Match == analyze_printf::ArgType::Match)
9219     return true;
9220 
9221   // Look through argument promotions for our error message's reported type.
9222   // This includes the integral and floating promotions, but excludes array
9223   // and function pointer decay (seeing that an argument intended to be a
9224   // string has type 'char [6]' is probably more confusing than 'char *') and
9225   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9226   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9227     if (isArithmeticArgumentPromotion(S, ICE)) {
9228       E = ICE->getSubExpr();
9229       ExprTy = E->getType();
9230 
9231       // Check if we didn't match because of an implicit cast from a 'char'
9232       // or 'short' to an 'int'.  This is done because printf is a varargs
9233       // function.
9234       if (ICE->getType() == S.Context.IntTy ||
9235           ICE->getType() == S.Context.UnsignedIntTy) {
9236         // All further checking is done on the subexpression
9237         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9238             AT.matchesType(S.Context, ExprTy);
9239         if (ImplicitMatch == analyze_printf::ArgType::Match)
9240           return true;
9241         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9242             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9243           Match = ImplicitMatch;
9244       }
9245     }
9246   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9247     // Special case for 'a', which has type 'int' in C.
9248     // Note, however, that we do /not/ want to treat multibyte constants like
9249     // 'MooV' as characters! This form is deprecated but still exists. In
9250     // addition, don't treat expressions as of type 'char' if one byte length
9251     // modifier is provided.
9252     if (ExprTy == S.Context.IntTy &&
9253         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9254       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9255         ExprTy = S.Context.CharTy;
9256   }
9257 
9258   // Look through enums to their underlying type.
9259   bool IsEnum = false;
9260   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9261     ExprTy = EnumTy->getDecl()->getIntegerType();
9262     IsEnum = true;
9263   }
9264 
9265   // %C in an Objective-C context prints a unichar, not a wchar_t.
9266   // If the argument is an integer of some kind, believe the %C and suggest
9267   // a cast instead of changing the conversion specifier.
9268   QualType IntendedTy = ExprTy;
9269   if (isObjCContext() &&
9270       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9271     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9272         !ExprTy->isCharType()) {
9273       // 'unichar' is defined as a typedef of unsigned short, but we should
9274       // prefer using the typedef if it is visible.
9275       IntendedTy = S.Context.UnsignedShortTy;
9276 
9277       // While we are here, check if the value is an IntegerLiteral that happens
9278       // to be within the valid range.
9279       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9280         const llvm::APInt &V = IL->getValue();
9281         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9282           return true;
9283       }
9284 
9285       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9286                           Sema::LookupOrdinaryName);
9287       if (S.LookupName(Result, S.getCurScope())) {
9288         NamedDecl *ND = Result.getFoundDecl();
9289         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9290           if (TD->getUnderlyingType() == IntendedTy)
9291             IntendedTy = S.Context.getTypedefType(TD);
9292       }
9293     }
9294   }
9295 
9296   // Special-case some of Darwin's platform-independence types by suggesting
9297   // casts to primitive types that are known to be large enough.
9298   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9299   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9300     QualType CastTy;
9301     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9302     if (!CastTy.isNull()) {
9303       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9304       // (long in ASTContext). Only complain to pedants.
9305       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9306           (AT.isSizeT() || AT.isPtrdiffT()) &&
9307           AT.matchesType(S.Context, CastTy))
9308         Match = ArgType::NoMatchPedantic;
9309       IntendedTy = CastTy;
9310       ShouldNotPrintDirectly = true;
9311     }
9312   }
9313 
9314   // We may be able to offer a FixItHint if it is a supported type.
9315   PrintfSpecifier fixedFS = FS;
9316   bool Success =
9317       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9318 
9319   if (Success) {
9320     // Get the fix string from the fixed format specifier
9321     SmallString<16> buf;
9322     llvm::raw_svector_ostream os(buf);
9323     fixedFS.toString(os);
9324 
9325     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9326 
9327     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9328       unsigned Diag;
9329       switch (Match) {
9330       case ArgType::Match: llvm_unreachable("expected non-matching");
9331       case ArgType::NoMatchPedantic:
9332         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9333         break;
9334       case ArgType::NoMatchTypeConfusion:
9335         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9336         break;
9337       case ArgType::NoMatch:
9338         Diag = diag::warn_format_conversion_argument_type_mismatch;
9339         break;
9340       }
9341 
9342       // In this case, the specifier is wrong and should be changed to match
9343       // the argument.
9344       EmitFormatDiagnostic(S.PDiag(Diag)
9345                                << AT.getRepresentativeTypeName(S.Context)
9346                                << IntendedTy << IsEnum << E->getSourceRange(),
9347                            E->getBeginLoc(),
9348                            /*IsStringLocation*/ false, SpecRange,
9349                            FixItHint::CreateReplacement(SpecRange, os.str()));
9350     } else {
9351       // The canonical type for formatting this value is different from the
9352       // actual type of the expression. (This occurs, for example, with Darwin's
9353       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9354       // should be printed as 'long' for 64-bit compatibility.)
9355       // Rather than emitting a normal format/argument mismatch, we want to
9356       // add a cast to the recommended type (and correct the format string
9357       // if necessary).
9358       SmallString<16> CastBuf;
9359       llvm::raw_svector_ostream CastFix(CastBuf);
9360       CastFix << "(";
9361       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9362       CastFix << ")";
9363 
9364       SmallVector<FixItHint,4> Hints;
9365       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9366         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9367 
9368       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9369         // If there's already a cast present, just replace it.
9370         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9371         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9372 
9373       } else if (!requiresParensToAddCast(E)) {
9374         // If the expression has high enough precedence,
9375         // just write the C-style cast.
9376         Hints.push_back(
9377             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9378       } else {
9379         // Otherwise, add parens around the expression as well as the cast.
9380         CastFix << "(";
9381         Hints.push_back(
9382             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9383 
9384         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9385         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9386       }
9387 
9388       if (ShouldNotPrintDirectly) {
9389         // The expression has a type that should not be printed directly.
9390         // We extract the name from the typedef because we don't want to show
9391         // the underlying type in the diagnostic.
9392         StringRef Name;
9393         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9394           Name = TypedefTy->getDecl()->getName();
9395         else
9396           Name = CastTyName;
9397         unsigned Diag = Match == ArgType::NoMatchPedantic
9398                             ? diag::warn_format_argument_needs_cast_pedantic
9399                             : diag::warn_format_argument_needs_cast;
9400         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9401                                            << E->getSourceRange(),
9402                              E->getBeginLoc(), /*IsStringLocation=*/false,
9403                              SpecRange, Hints);
9404       } else {
9405         // In this case, the expression could be printed using a different
9406         // specifier, but we've decided that the specifier is probably correct
9407         // and we should cast instead. Just use the normal warning message.
9408         EmitFormatDiagnostic(
9409             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9410                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9411                 << E->getSourceRange(),
9412             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9413       }
9414     }
9415   } else {
9416     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9417                                                    SpecifierLen);
9418     // Since the warning for passing non-POD types to variadic functions
9419     // was deferred until now, we emit a warning for non-POD
9420     // arguments here.
9421     switch (S.isValidVarArgType(ExprTy)) {
9422     case Sema::VAK_Valid:
9423     case Sema::VAK_ValidInCXX11: {
9424       unsigned Diag;
9425       switch (Match) {
9426       case ArgType::Match: llvm_unreachable("expected non-matching");
9427       case ArgType::NoMatchPedantic:
9428         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9429         break;
9430       case ArgType::NoMatchTypeConfusion:
9431         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9432         break;
9433       case ArgType::NoMatch:
9434         Diag = diag::warn_format_conversion_argument_type_mismatch;
9435         break;
9436       }
9437 
9438       EmitFormatDiagnostic(
9439           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9440                         << IsEnum << CSR << E->getSourceRange(),
9441           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9442       break;
9443     }
9444     case Sema::VAK_Undefined:
9445     case Sema::VAK_MSVCUndefined:
9446       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9447                                << S.getLangOpts().CPlusPlus11 << ExprTy
9448                                << CallType
9449                                << AT.getRepresentativeTypeName(S.Context) << CSR
9450                                << E->getSourceRange(),
9451                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9452       checkForCStrMembers(AT, E);
9453       break;
9454 
9455     case Sema::VAK_Invalid:
9456       if (ExprTy->isObjCObjectType())
9457         EmitFormatDiagnostic(
9458             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9459                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9460                 << AT.getRepresentativeTypeName(S.Context) << CSR
9461                 << E->getSourceRange(),
9462             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9463       else
9464         // FIXME: If this is an initializer list, suggest removing the braces
9465         // or inserting a cast to the target type.
9466         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9467             << isa<InitListExpr>(E) << ExprTy << CallType
9468             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9469       break;
9470     }
9471 
9472     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9473            "format string specifier index out of range");
9474     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9475   }
9476 
9477   return true;
9478 }
9479 
9480 //===--- CHECK: Scanf format string checking ------------------------------===//
9481 
9482 namespace {
9483 
9484 class CheckScanfHandler : public CheckFormatHandler {
9485 public:
9486   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9487                     const Expr *origFormatExpr, Sema::FormatStringType type,
9488                     unsigned firstDataArg, unsigned numDataArgs,
9489                     const char *beg, bool hasVAListArg,
9490                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9491                     bool inFunctionCall, Sema::VariadicCallType CallType,
9492                     llvm::SmallBitVector &CheckedVarArgs,
9493                     UncoveredArgHandler &UncoveredArg)
9494       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9495                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9496                            inFunctionCall, CallType, CheckedVarArgs,
9497                            UncoveredArg) {}
9498 
9499   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9500                             const char *startSpecifier,
9501                             unsigned specifierLen) override;
9502 
9503   bool HandleInvalidScanfConversionSpecifier(
9504           const analyze_scanf::ScanfSpecifier &FS,
9505           const char *startSpecifier,
9506           unsigned specifierLen) override;
9507 
9508   void HandleIncompleteScanList(const char *start, const char *end) override;
9509 };
9510 
9511 } // namespace
9512 
9513 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9514                                                  const char *end) {
9515   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9516                        getLocationOfByte(end), /*IsStringLocation*/true,
9517                        getSpecifierRange(start, end - start));
9518 }
9519 
9520 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9521                                         const analyze_scanf::ScanfSpecifier &FS,
9522                                         const char *startSpecifier,
9523                                         unsigned specifierLen) {
9524   const analyze_scanf::ScanfConversionSpecifier &CS =
9525     FS.getConversionSpecifier();
9526 
9527   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9528                                           getLocationOfByte(CS.getStart()),
9529                                           startSpecifier, specifierLen,
9530                                           CS.getStart(), CS.getLength());
9531 }
9532 
9533 bool CheckScanfHandler::HandleScanfSpecifier(
9534                                        const analyze_scanf::ScanfSpecifier &FS,
9535                                        const char *startSpecifier,
9536                                        unsigned specifierLen) {
9537   using namespace analyze_scanf;
9538   using namespace analyze_format_string;
9539 
9540   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9541 
9542   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9543   // be used to decide if we are using positional arguments consistently.
9544   if (FS.consumesDataArgument()) {
9545     if (atFirstArg) {
9546       atFirstArg = false;
9547       usesPositionalArgs = FS.usesPositionalArg();
9548     }
9549     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9550       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9551                                         startSpecifier, specifierLen);
9552       return false;
9553     }
9554   }
9555 
9556   // Check if the field with is non-zero.
9557   const OptionalAmount &Amt = FS.getFieldWidth();
9558   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9559     if (Amt.getConstantAmount() == 0) {
9560       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9561                                                    Amt.getConstantLength());
9562       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9563                            getLocationOfByte(Amt.getStart()),
9564                            /*IsStringLocation*/true, R,
9565                            FixItHint::CreateRemoval(R));
9566     }
9567   }
9568 
9569   if (!FS.consumesDataArgument()) {
9570     // FIXME: Technically specifying a precision or field width here
9571     // makes no sense.  Worth issuing a warning at some point.
9572     return true;
9573   }
9574 
9575   // Consume the argument.
9576   unsigned argIndex = FS.getArgIndex();
9577   if (argIndex < NumDataArgs) {
9578       // The check to see if the argIndex is valid will come later.
9579       // We set the bit here because we may exit early from this
9580       // function if we encounter some other error.
9581     CoveredArgs.set(argIndex);
9582   }
9583 
9584   // Check the length modifier is valid with the given conversion specifier.
9585   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9586                                  S.getLangOpts()))
9587     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9588                                 diag::warn_format_nonsensical_length);
9589   else if (!FS.hasStandardLengthModifier())
9590     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9591   else if (!FS.hasStandardLengthConversionCombination())
9592     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9593                                 diag::warn_format_non_standard_conversion_spec);
9594 
9595   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9596     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9597 
9598   // The remaining checks depend on the data arguments.
9599   if (HasVAListArg)
9600     return true;
9601 
9602   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9603     return false;
9604 
9605   // Check that the argument type matches the format specifier.
9606   const Expr *Ex = getDataArg(argIndex);
9607   if (!Ex)
9608     return true;
9609 
9610   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9611 
9612   if (!AT.isValid()) {
9613     return true;
9614   }
9615 
9616   analyze_format_string::ArgType::MatchKind Match =
9617       AT.matchesType(S.Context, Ex->getType());
9618   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9619   if (Match == analyze_format_string::ArgType::Match)
9620     return true;
9621 
9622   ScanfSpecifier fixedFS = FS;
9623   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9624                                  S.getLangOpts(), S.Context);
9625 
9626   unsigned Diag =
9627       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9628                : diag::warn_format_conversion_argument_type_mismatch;
9629 
9630   if (Success) {
9631     // Get the fix string from the fixed format specifier.
9632     SmallString<128> buf;
9633     llvm::raw_svector_ostream os(buf);
9634     fixedFS.toString(os);
9635 
9636     EmitFormatDiagnostic(
9637         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9638                       << Ex->getType() << false << Ex->getSourceRange(),
9639         Ex->getBeginLoc(),
9640         /*IsStringLocation*/ false,
9641         getSpecifierRange(startSpecifier, specifierLen),
9642         FixItHint::CreateReplacement(
9643             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9644   } else {
9645     EmitFormatDiagnostic(S.PDiag(Diag)
9646                              << AT.getRepresentativeTypeName(S.Context)
9647                              << Ex->getType() << false << Ex->getSourceRange(),
9648                          Ex->getBeginLoc(),
9649                          /*IsStringLocation*/ false,
9650                          getSpecifierRange(startSpecifier, specifierLen));
9651   }
9652 
9653   return true;
9654 }
9655 
9656 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9657                               const Expr *OrigFormatExpr,
9658                               ArrayRef<const Expr *> Args,
9659                               bool HasVAListArg, unsigned format_idx,
9660                               unsigned firstDataArg,
9661                               Sema::FormatStringType Type,
9662                               bool inFunctionCall,
9663                               Sema::VariadicCallType CallType,
9664                               llvm::SmallBitVector &CheckedVarArgs,
9665                               UncoveredArgHandler &UncoveredArg,
9666                               bool IgnoreStringsWithoutSpecifiers) {
9667   // CHECK: is the format string a wide literal?
9668   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9669     CheckFormatHandler::EmitFormatDiagnostic(
9670         S, inFunctionCall, Args[format_idx],
9671         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9672         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9673     return;
9674   }
9675 
9676   // Str - The format string.  NOTE: this is NOT null-terminated!
9677   StringRef StrRef = FExpr->getString();
9678   const char *Str = StrRef.data();
9679   // Account for cases where the string literal is truncated in a declaration.
9680   const ConstantArrayType *T =
9681     S.Context.getAsConstantArrayType(FExpr->getType());
9682   assert(T && "String literal not of constant array type!");
9683   size_t TypeSize = T->getSize().getZExtValue();
9684   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9685   const unsigned numDataArgs = Args.size() - firstDataArg;
9686 
9687   if (IgnoreStringsWithoutSpecifiers &&
9688       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9689           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9690     return;
9691 
9692   // Emit a warning if the string literal is truncated and does not contain an
9693   // embedded null character.
9694   if (TypeSize <= StrRef.size() &&
9695       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9696     CheckFormatHandler::EmitFormatDiagnostic(
9697         S, inFunctionCall, Args[format_idx],
9698         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9699         FExpr->getBeginLoc(),
9700         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9701     return;
9702   }
9703 
9704   // CHECK: empty format string?
9705   if (StrLen == 0 && numDataArgs > 0) {
9706     CheckFormatHandler::EmitFormatDiagnostic(
9707         S, inFunctionCall, Args[format_idx],
9708         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9709         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9710     return;
9711   }
9712 
9713   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9714       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9715       Type == Sema::FST_OSTrace) {
9716     CheckPrintfHandler H(
9717         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9718         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9719         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9720         CheckedVarArgs, UncoveredArg);
9721 
9722     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9723                                                   S.getLangOpts(),
9724                                                   S.Context.getTargetInfo(),
9725                                             Type == Sema::FST_FreeBSDKPrintf))
9726       H.DoneProcessing();
9727   } else if (Type == Sema::FST_Scanf) {
9728     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9729                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9730                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9731 
9732     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9733                                                  S.getLangOpts(),
9734                                                  S.Context.getTargetInfo()))
9735       H.DoneProcessing();
9736   } // TODO: handle other formats
9737 }
9738 
9739 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9740   // Str - The format string.  NOTE: this is NOT null-terminated!
9741   StringRef StrRef = FExpr->getString();
9742   const char *Str = StrRef.data();
9743   // Account for cases where the string literal is truncated in a declaration.
9744   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9745   assert(T && "String literal not of constant array type!");
9746   size_t TypeSize = T->getSize().getZExtValue();
9747   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9748   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9749                                                          getLangOpts(),
9750                                                          Context.getTargetInfo());
9751 }
9752 
9753 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9754 
9755 // Returns the related absolute value function that is larger, of 0 if one
9756 // does not exist.
9757 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9758   switch (AbsFunction) {
9759   default:
9760     return 0;
9761 
9762   case Builtin::BI__builtin_abs:
9763     return Builtin::BI__builtin_labs;
9764   case Builtin::BI__builtin_labs:
9765     return Builtin::BI__builtin_llabs;
9766   case Builtin::BI__builtin_llabs:
9767     return 0;
9768 
9769   case Builtin::BI__builtin_fabsf:
9770     return Builtin::BI__builtin_fabs;
9771   case Builtin::BI__builtin_fabs:
9772     return Builtin::BI__builtin_fabsl;
9773   case Builtin::BI__builtin_fabsl:
9774     return 0;
9775 
9776   case Builtin::BI__builtin_cabsf:
9777     return Builtin::BI__builtin_cabs;
9778   case Builtin::BI__builtin_cabs:
9779     return Builtin::BI__builtin_cabsl;
9780   case Builtin::BI__builtin_cabsl:
9781     return 0;
9782 
9783   case Builtin::BIabs:
9784     return Builtin::BIlabs;
9785   case Builtin::BIlabs:
9786     return Builtin::BIllabs;
9787   case Builtin::BIllabs:
9788     return 0;
9789 
9790   case Builtin::BIfabsf:
9791     return Builtin::BIfabs;
9792   case Builtin::BIfabs:
9793     return Builtin::BIfabsl;
9794   case Builtin::BIfabsl:
9795     return 0;
9796 
9797   case Builtin::BIcabsf:
9798    return Builtin::BIcabs;
9799   case Builtin::BIcabs:
9800     return Builtin::BIcabsl;
9801   case Builtin::BIcabsl:
9802     return 0;
9803   }
9804 }
9805 
9806 // Returns the argument type of the absolute value function.
9807 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9808                                              unsigned AbsType) {
9809   if (AbsType == 0)
9810     return QualType();
9811 
9812   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9813   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9814   if (Error != ASTContext::GE_None)
9815     return QualType();
9816 
9817   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9818   if (!FT)
9819     return QualType();
9820 
9821   if (FT->getNumParams() != 1)
9822     return QualType();
9823 
9824   return FT->getParamType(0);
9825 }
9826 
9827 // Returns the best absolute value function, or zero, based on type and
9828 // current absolute value function.
9829 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9830                                    unsigned AbsFunctionKind) {
9831   unsigned BestKind = 0;
9832   uint64_t ArgSize = Context.getTypeSize(ArgType);
9833   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9834        Kind = getLargerAbsoluteValueFunction(Kind)) {
9835     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9836     if (Context.getTypeSize(ParamType) >= ArgSize) {
9837       if (BestKind == 0)
9838         BestKind = Kind;
9839       else if (Context.hasSameType(ParamType, ArgType)) {
9840         BestKind = Kind;
9841         break;
9842       }
9843     }
9844   }
9845   return BestKind;
9846 }
9847 
9848 enum AbsoluteValueKind {
9849   AVK_Integer,
9850   AVK_Floating,
9851   AVK_Complex
9852 };
9853 
9854 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9855   if (T->isIntegralOrEnumerationType())
9856     return AVK_Integer;
9857   if (T->isRealFloatingType())
9858     return AVK_Floating;
9859   if (T->isAnyComplexType())
9860     return AVK_Complex;
9861 
9862   llvm_unreachable("Type not integer, floating, or complex");
9863 }
9864 
9865 // Changes the absolute value function to a different type.  Preserves whether
9866 // the function is a builtin.
9867 static unsigned changeAbsFunction(unsigned AbsKind,
9868                                   AbsoluteValueKind ValueKind) {
9869   switch (ValueKind) {
9870   case AVK_Integer:
9871     switch (AbsKind) {
9872     default:
9873       return 0;
9874     case Builtin::BI__builtin_fabsf:
9875     case Builtin::BI__builtin_fabs:
9876     case Builtin::BI__builtin_fabsl:
9877     case Builtin::BI__builtin_cabsf:
9878     case Builtin::BI__builtin_cabs:
9879     case Builtin::BI__builtin_cabsl:
9880       return Builtin::BI__builtin_abs;
9881     case Builtin::BIfabsf:
9882     case Builtin::BIfabs:
9883     case Builtin::BIfabsl:
9884     case Builtin::BIcabsf:
9885     case Builtin::BIcabs:
9886     case Builtin::BIcabsl:
9887       return Builtin::BIabs;
9888     }
9889   case AVK_Floating:
9890     switch (AbsKind) {
9891     default:
9892       return 0;
9893     case Builtin::BI__builtin_abs:
9894     case Builtin::BI__builtin_labs:
9895     case Builtin::BI__builtin_llabs:
9896     case Builtin::BI__builtin_cabsf:
9897     case Builtin::BI__builtin_cabs:
9898     case Builtin::BI__builtin_cabsl:
9899       return Builtin::BI__builtin_fabsf;
9900     case Builtin::BIabs:
9901     case Builtin::BIlabs:
9902     case Builtin::BIllabs:
9903     case Builtin::BIcabsf:
9904     case Builtin::BIcabs:
9905     case Builtin::BIcabsl:
9906       return Builtin::BIfabsf;
9907     }
9908   case AVK_Complex:
9909     switch (AbsKind) {
9910     default:
9911       return 0;
9912     case Builtin::BI__builtin_abs:
9913     case Builtin::BI__builtin_labs:
9914     case Builtin::BI__builtin_llabs:
9915     case Builtin::BI__builtin_fabsf:
9916     case Builtin::BI__builtin_fabs:
9917     case Builtin::BI__builtin_fabsl:
9918       return Builtin::BI__builtin_cabsf;
9919     case Builtin::BIabs:
9920     case Builtin::BIlabs:
9921     case Builtin::BIllabs:
9922     case Builtin::BIfabsf:
9923     case Builtin::BIfabs:
9924     case Builtin::BIfabsl:
9925       return Builtin::BIcabsf;
9926     }
9927   }
9928   llvm_unreachable("Unable to convert function");
9929 }
9930 
9931 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9932   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9933   if (!FnInfo)
9934     return 0;
9935 
9936   switch (FDecl->getBuiltinID()) {
9937   default:
9938     return 0;
9939   case Builtin::BI__builtin_abs:
9940   case Builtin::BI__builtin_fabs:
9941   case Builtin::BI__builtin_fabsf:
9942   case Builtin::BI__builtin_fabsl:
9943   case Builtin::BI__builtin_labs:
9944   case Builtin::BI__builtin_llabs:
9945   case Builtin::BI__builtin_cabs:
9946   case Builtin::BI__builtin_cabsf:
9947   case Builtin::BI__builtin_cabsl:
9948   case Builtin::BIabs:
9949   case Builtin::BIlabs:
9950   case Builtin::BIllabs:
9951   case Builtin::BIfabs:
9952   case Builtin::BIfabsf:
9953   case Builtin::BIfabsl:
9954   case Builtin::BIcabs:
9955   case Builtin::BIcabsf:
9956   case Builtin::BIcabsl:
9957     return FDecl->getBuiltinID();
9958   }
9959   llvm_unreachable("Unknown Builtin type");
9960 }
9961 
9962 // If the replacement is valid, emit a note with replacement function.
9963 // Additionally, suggest including the proper header if not already included.
9964 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9965                             unsigned AbsKind, QualType ArgType) {
9966   bool EmitHeaderHint = true;
9967   const char *HeaderName = nullptr;
9968   const char *FunctionName = nullptr;
9969   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9970     FunctionName = "std::abs";
9971     if (ArgType->isIntegralOrEnumerationType()) {
9972       HeaderName = "cstdlib";
9973     } else if (ArgType->isRealFloatingType()) {
9974       HeaderName = "cmath";
9975     } else {
9976       llvm_unreachable("Invalid Type");
9977     }
9978 
9979     // Lookup all std::abs
9980     if (NamespaceDecl *Std = S.getStdNamespace()) {
9981       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9982       R.suppressDiagnostics();
9983       S.LookupQualifiedName(R, Std);
9984 
9985       for (const auto *I : R) {
9986         const FunctionDecl *FDecl = nullptr;
9987         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9988           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9989         } else {
9990           FDecl = dyn_cast<FunctionDecl>(I);
9991         }
9992         if (!FDecl)
9993           continue;
9994 
9995         // Found std::abs(), check that they are the right ones.
9996         if (FDecl->getNumParams() != 1)
9997           continue;
9998 
9999         // Check that the parameter type can handle the argument.
10000         QualType ParamType = FDecl->getParamDecl(0)->getType();
10001         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10002             S.Context.getTypeSize(ArgType) <=
10003                 S.Context.getTypeSize(ParamType)) {
10004           // Found a function, don't need the header hint.
10005           EmitHeaderHint = false;
10006           break;
10007         }
10008       }
10009     }
10010   } else {
10011     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10012     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10013 
10014     if (HeaderName) {
10015       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10016       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10017       R.suppressDiagnostics();
10018       S.LookupName(R, S.getCurScope());
10019 
10020       if (R.isSingleResult()) {
10021         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10022         if (FD && FD->getBuiltinID() == AbsKind) {
10023           EmitHeaderHint = false;
10024         } else {
10025           return;
10026         }
10027       } else if (!R.empty()) {
10028         return;
10029       }
10030     }
10031   }
10032 
10033   S.Diag(Loc, diag::note_replace_abs_function)
10034       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10035 
10036   if (!HeaderName)
10037     return;
10038 
10039   if (!EmitHeaderHint)
10040     return;
10041 
10042   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10043                                                     << FunctionName;
10044 }
10045 
10046 template <std::size_t StrLen>
10047 static bool IsStdFunction(const FunctionDecl *FDecl,
10048                           const char (&Str)[StrLen]) {
10049   if (!FDecl)
10050     return false;
10051   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10052     return false;
10053   if (!FDecl->isInStdNamespace())
10054     return false;
10055 
10056   return true;
10057 }
10058 
10059 // Warn when using the wrong abs() function.
10060 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10061                                       const FunctionDecl *FDecl) {
10062   if (Call->getNumArgs() != 1)
10063     return;
10064 
10065   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10066   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10067   if (AbsKind == 0 && !IsStdAbs)
10068     return;
10069 
10070   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10071   QualType ParamType = Call->getArg(0)->getType();
10072 
10073   // Unsigned types cannot be negative.  Suggest removing the absolute value
10074   // function call.
10075   if (ArgType->isUnsignedIntegerType()) {
10076     const char *FunctionName =
10077         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10078     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10079     Diag(Call->getExprLoc(), diag::note_remove_abs)
10080         << FunctionName
10081         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10082     return;
10083   }
10084 
10085   // Taking the absolute value of a pointer is very suspicious, they probably
10086   // wanted to index into an array, dereference a pointer, call a function, etc.
10087   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10088     unsigned DiagType = 0;
10089     if (ArgType->isFunctionType())
10090       DiagType = 1;
10091     else if (ArgType->isArrayType())
10092       DiagType = 2;
10093 
10094     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10095     return;
10096   }
10097 
10098   // std::abs has overloads which prevent most of the absolute value problems
10099   // from occurring.
10100   if (IsStdAbs)
10101     return;
10102 
10103   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10104   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10105 
10106   // The argument and parameter are the same kind.  Check if they are the right
10107   // size.
10108   if (ArgValueKind == ParamValueKind) {
10109     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10110       return;
10111 
10112     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10113     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10114         << FDecl << ArgType << ParamType;
10115 
10116     if (NewAbsKind == 0)
10117       return;
10118 
10119     emitReplacement(*this, Call->getExprLoc(),
10120                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10121     return;
10122   }
10123 
10124   // ArgValueKind != ParamValueKind
10125   // The wrong type of absolute value function was used.  Attempt to find the
10126   // proper one.
10127   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10128   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10129   if (NewAbsKind == 0)
10130     return;
10131 
10132   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10133       << FDecl << ParamValueKind << ArgValueKind;
10134 
10135   emitReplacement(*this, Call->getExprLoc(),
10136                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10137 }
10138 
10139 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10140 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10141                                 const FunctionDecl *FDecl) {
10142   if (!Call || !FDecl) return;
10143 
10144   // Ignore template specializations and macros.
10145   if (inTemplateInstantiation()) return;
10146   if (Call->getExprLoc().isMacroID()) return;
10147 
10148   // Only care about the one template argument, two function parameter std::max
10149   if (Call->getNumArgs() != 2) return;
10150   if (!IsStdFunction(FDecl, "max")) return;
10151   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10152   if (!ArgList) return;
10153   if (ArgList->size() != 1) return;
10154 
10155   // Check that template type argument is unsigned integer.
10156   const auto& TA = ArgList->get(0);
10157   if (TA.getKind() != TemplateArgument::Type) return;
10158   QualType ArgType = TA.getAsType();
10159   if (!ArgType->isUnsignedIntegerType()) return;
10160 
10161   // See if either argument is a literal zero.
10162   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10163     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10164     if (!MTE) return false;
10165     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10166     if (!Num) return false;
10167     if (Num->getValue() != 0) return false;
10168     return true;
10169   };
10170 
10171   const Expr *FirstArg = Call->getArg(0);
10172   const Expr *SecondArg = Call->getArg(1);
10173   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10174   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10175 
10176   // Only warn when exactly one argument is zero.
10177   if (IsFirstArgZero == IsSecondArgZero) return;
10178 
10179   SourceRange FirstRange = FirstArg->getSourceRange();
10180   SourceRange SecondRange = SecondArg->getSourceRange();
10181 
10182   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10183 
10184   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10185       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10186 
10187   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10188   SourceRange RemovalRange;
10189   if (IsFirstArgZero) {
10190     RemovalRange = SourceRange(FirstRange.getBegin(),
10191                                SecondRange.getBegin().getLocWithOffset(-1));
10192   } else {
10193     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10194                                SecondRange.getEnd());
10195   }
10196 
10197   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10198         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10199         << FixItHint::CreateRemoval(RemovalRange);
10200 }
10201 
10202 //===--- CHECK: Standard memory functions ---------------------------------===//
10203 
10204 /// Takes the expression passed to the size_t parameter of functions
10205 /// such as memcmp, strncat, etc and warns if it's a comparison.
10206 ///
10207 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10208 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10209                                            IdentifierInfo *FnName,
10210                                            SourceLocation FnLoc,
10211                                            SourceLocation RParenLoc) {
10212   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10213   if (!Size)
10214     return false;
10215 
10216   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10217   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10218     return false;
10219 
10220   SourceRange SizeRange = Size->getSourceRange();
10221   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10222       << SizeRange << FnName;
10223   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10224       << FnName
10225       << FixItHint::CreateInsertion(
10226              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10227       << FixItHint::CreateRemoval(RParenLoc);
10228   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10229       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10230       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10231                                     ")");
10232 
10233   return true;
10234 }
10235 
10236 /// Determine whether the given type is or contains a dynamic class type
10237 /// (e.g., whether it has a vtable).
10238 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10239                                                      bool &IsContained) {
10240   // Look through array types while ignoring qualifiers.
10241   const Type *Ty = T->getBaseElementTypeUnsafe();
10242   IsContained = false;
10243 
10244   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10245   RD = RD ? RD->getDefinition() : nullptr;
10246   if (!RD || RD->isInvalidDecl())
10247     return nullptr;
10248 
10249   if (RD->isDynamicClass())
10250     return RD;
10251 
10252   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10253   // It's impossible for a class to transitively contain itself by value, so
10254   // infinite recursion is impossible.
10255   for (auto *FD : RD->fields()) {
10256     bool SubContained;
10257     if (const CXXRecordDecl *ContainedRD =
10258             getContainedDynamicClass(FD->getType(), SubContained)) {
10259       IsContained = true;
10260       return ContainedRD;
10261     }
10262   }
10263 
10264   return nullptr;
10265 }
10266 
10267 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10268   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10269     if (Unary->getKind() == UETT_SizeOf)
10270       return Unary;
10271   return nullptr;
10272 }
10273 
10274 /// If E is a sizeof expression, returns its argument expression,
10275 /// otherwise returns NULL.
10276 static const Expr *getSizeOfExprArg(const Expr *E) {
10277   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10278     if (!SizeOf->isArgumentType())
10279       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10280   return nullptr;
10281 }
10282 
10283 /// If E is a sizeof expression, returns its argument type.
10284 static QualType getSizeOfArgType(const Expr *E) {
10285   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10286     return SizeOf->getTypeOfArgument();
10287   return QualType();
10288 }
10289 
10290 namespace {
10291 
10292 struct SearchNonTrivialToInitializeField
10293     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10294   using Super =
10295       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10296 
10297   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10298 
10299   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10300                      SourceLocation SL) {
10301     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10302       asDerived().visitArray(PDIK, AT, SL);
10303       return;
10304     }
10305 
10306     Super::visitWithKind(PDIK, FT, SL);
10307   }
10308 
10309   void visitARCStrong(QualType FT, SourceLocation SL) {
10310     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10311   }
10312   void visitARCWeak(QualType FT, SourceLocation SL) {
10313     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10314   }
10315   void visitStruct(QualType FT, SourceLocation SL) {
10316     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10317       visit(FD->getType(), FD->getLocation());
10318   }
10319   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10320                   const ArrayType *AT, SourceLocation SL) {
10321     visit(getContext().getBaseElementType(AT), SL);
10322   }
10323   void visitTrivial(QualType FT, SourceLocation SL) {}
10324 
10325   static void diag(QualType RT, const Expr *E, Sema &S) {
10326     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10327   }
10328 
10329   ASTContext &getContext() { return S.getASTContext(); }
10330 
10331   const Expr *E;
10332   Sema &S;
10333 };
10334 
10335 struct SearchNonTrivialToCopyField
10336     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10337   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10338 
10339   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10340 
10341   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10342                      SourceLocation SL) {
10343     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10344       asDerived().visitArray(PCK, AT, SL);
10345       return;
10346     }
10347 
10348     Super::visitWithKind(PCK, FT, SL);
10349   }
10350 
10351   void visitARCStrong(QualType FT, SourceLocation SL) {
10352     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10353   }
10354   void visitARCWeak(QualType FT, SourceLocation SL) {
10355     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10356   }
10357   void visitStruct(QualType FT, SourceLocation SL) {
10358     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10359       visit(FD->getType(), FD->getLocation());
10360   }
10361   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10362                   SourceLocation SL) {
10363     visit(getContext().getBaseElementType(AT), SL);
10364   }
10365   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10366                 SourceLocation SL) {}
10367   void visitTrivial(QualType FT, SourceLocation SL) {}
10368   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10369 
10370   static void diag(QualType RT, const Expr *E, Sema &S) {
10371     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10372   }
10373 
10374   ASTContext &getContext() { return S.getASTContext(); }
10375 
10376   const Expr *E;
10377   Sema &S;
10378 };
10379 
10380 }
10381 
10382 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10383 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10384   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10385 
10386   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10387     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10388       return false;
10389 
10390     return doesExprLikelyComputeSize(BO->getLHS()) ||
10391            doesExprLikelyComputeSize(BO->getRHS());
10392   }
10393 
10394   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10395 }
10396 
10397 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10398 ///
10399 /// \code
10400 ///   #define MACRO 0
10401 ///   foo(MACRO);
10402 ///   foo(0);
10403 /// \endcode
10404 ///
10405 /// This should return true for the first call to foo, but not for the second
10406 /// (regardless of whether foo is a macro or function).
10407 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10408                                         SourceLocation CallLoc,
10409                                         SourceLocation ArgLoc) {
10410   if (!CallLoc.isMacroID())
10411     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10412 
10413   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10414          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10415 }
10416 
10417 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10418 /// last two arguments transposed.
10419 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10420   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10421     return;
10422 
10423   const Expr *SizeArg =
10424     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10425 
10426   auto isLiteralZero = [](const Expr *E) {
10427     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10428   };
10429 
10430   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10431   SourceLocation CallLoc = Call->getRParenLoc();
10432   SourceManager &SM = S.getSourceManager();
10433   if (isLiteralZero(SizeArg) &&
10434       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10435 
10436     SourceLocation DiagLoc = SizeArg->getExprLoc();
10437 
10438     // Some platforms #define bzero to __builtin_memset. See if this is the
10439     // case, and if so, emit a better diagnostic.
10440     if (BId == Builtin::BIbzero ||
10441         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10442                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10443       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10444       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10445     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10446       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10447       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10448     }
10449     return;
10450   }
10451 
10452   // If the second argument to a memset is a sizeof expression and the third
10453   // isn't, this is also likely an error. This should catch
10454   // 'memset(buf, sizeof(buf), 0xff)'.
10455   if (BId == Builtin::BImemset &&
10456       doesExprLikelyComputeSize(Call->getArg(1)) &&
10457       !doesExprLikelyComputeSize(Call->getArg(2))) {
10458     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10459     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10460     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10461     return;
10462   }
10463 }
10464 
10465 /// Check for dangerous or invalid arguments to memset().
10466 ///
10467 /// This issues warnings on known problematic, dangerous or unspecified
10468 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10469 /// function calls.
10470 ///
10471 /// \param Call The call expression to diagnose.
10472 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10473                                    unsigned BId,
10474                                    IdentifierInfo *FnName) {
10475   assert(BId != 0);
10476 
10477   // It is possible to have a non-standard definition of memset.  Validate
10478   // we have enough arguments, and if not, abort further checking.
10479   unsigned ExpectedNumArgs =
10480       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10481   if (Call->getNumArgs() < ExpectedNumArgs)
10482     return;
10483 
10484   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10485                       BId == Builtin::BIstrndup ? 1 : 2);
10486   unsigned LenArg =
10487       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10488   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10489 
10490   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10491                                      Call->getBeginLoc(), Call->getRParenLoc()))
10492     return;
10493 
10494   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10495   CheckMemaccessSize(*this, BId, Call);
10496 
10497   // We have special checking when the length is a sizeof expression.
10498   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10499   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10500   llvm::FoldingSetNodeID SizeOfArgID;
10501 
10502   // Although widely used, 'bzero' is not a standard function. Be more strict
10503   // with the argument types before allowing diagnostics and only allow the
10504   // form bzero(ptr, sizeof(...)).
10505   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10506   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10507     return;
10508 
10509   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10510     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10511     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10512 
10513     QualType DestTy = Dest->getType();
10514     QualType PointeeTy;
10515     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10516       PointeeTy = DestPtrTy->getPointeeType();
10517 
10518       // Never warn about void type pointers. This can be used to suppress
10519       // false positives.
10520       if (PointeeTy->isVoidType())
10521         continue;
10522 
10523       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10524       // actually comparing the expressions for equality. Because computing the
10525       // expression IDs can be expensive, we only do this if the diagnostic is
10526       // enabled.
10527       if (SizeOfArg &&
10528           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10529                            SizeOfArg->getExprLoc())) {
10530         // We only compute IDs for expressions if the warning is enabled, and
10531         // cache the sizeof arg's ID.
10532         if (SizeOfArgID == llvm::FoldingSetNodeID())
10533           SizeOfArg->Profile(SizeOfArgID, Context, true);
10534         llvm::FoldingSetNodeID DestID;
10535         Dest->Profile(DestID, Context, true);
10536         if (DestID == SizeOfArgID) {
10537           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10538           //       over sizeof(src) as well.
10539           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10540           StringRef ReadableName = FnName->getName();
10541 
10542           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10543             if (UnaryOp->getOpcode() == UO_AddrOf)
10544               ActionIdx = 1; // If its an address-of operator, just remove it.
10545           if (!PointeeTy->isIncompleteType() &&
10546               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10547             ActionIdx = 2; // If the pointee's size is sizeof(char),
10548                            // suggest an explicit length.
10549 
10550           // If the function is defined as a builtin macro, do not show macro
10551           // expansion.
10552           SourceLocation SL = SizeOfArg->getExprLoc();
10553           SourceRange DSR = Dest->getSourceRange();
10554           SourceRange SSR = SizeOfArg->getSourceRange();
10555           SourceManager &SM = getSourceManager();
10556 
10557           if (SM.isMacroArgExpansion(SL)) {
10558             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10559             SL = SM.getSpellingLoc(SL);
10560             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10561                              SM.getSpellingLoc(DSR.getEnd()));
10562             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10563                              SM.getSpellingLoc(SSR.getEnd()));
10564           }
10565 
10566           DiagRuntimeBehavior(SL, SizeOfArg,
10567                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10568                                 << ReadableName
10569                                 << PointeeTy
10570                                 << DestTy
10571                                 << DSR
10572                                 << SSR);
10573           DiagRuntimeBehavior(SL, SizeOfArg,
10574                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10575                                 << ActionIdx
10576                                 << SSR);
10577 
10578           break;
10579         }
10580       }
10581 
10582       // Also check for cases where the sizeof argument is the exact same
10583       // type as the memory argument, and where it points to a user-defined
10584       // record type.
10585       if (SizeOfArgTy != QualType()) {
10586         if (PointeeTy->isRecordType() &&
10587             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10588           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10589                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10590                                 << FnName << SizeOfArgTy << ArgIdx
10591                                 << PointeeTy << Dest->getSourceRange()
10592                                 << LenExpr->getSourceRange());
10593           break;
10594         }
10595       }
10596     } else if (DestTy->isArrayType()) {
10597       PointeeTy = DestTy;
10598     }
10599 
10600     if (PointeeTy == QualType())
10601       continue;
10602 
10603     // Always complain about dynamic classes.
10604     bool IsContained;
10605     if (const CXXRecordDecl *ContainedRD =
10606             getContainedDynamicClass(PointeeTy, IsContained)) {
10607 
10608       unsigned OperationType = 0;
10609       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10610       // "overwritten" if we're warning about the destination for any call
10611       // but memcmp; otherwise a verb appropriate to the call.
10612       if (ArgIdx != 0 || IsCmp) {
10613         if (BId == Builtin::BImemcpy)
10614           OperationType = 1;
10615         else if(BId == Builtin::BImemmove)
10616           OperationType = 2;
10617         else if (IsCmp)
10618           OperationType = 3;
10619       }
10620 
10621       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10622                           PDiag(diag::warn_dyn_class_memaccess)
10623                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10624                               << IsContained << ContainedRD << OperationType
10625                               << Call->getCallee()->getSourceRange());
10626     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10627              BId != Builtin::BImemset)
10628       DiagRuntimeBehavior(
10629         Dest->getExprLoc(), Dest,
10630         PDiag(diag::warn_arc_object_memaccess)
10631           << ArgIdx << FnName << PointeeTy
10632           << Call->getCallee()->getSourceRange());
10633     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10634       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10635           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10636         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10637                             PDiag(diag::warn_cstruct_memaccess)
10638                                 << ArgIdx << FnName << PointeeTy << 0);
10639         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10640       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10641                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10642         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10643                             PDiag(diag::warn_cstruct_memaccess)
10644                                 << ArgIdx << FnName << PointeeTy << 1);
10645         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10646       } else {
10647         continue;
10648       }
10649     } else
10650       continue;
10651 
10652     DiagRuntimeBehavior(
10653       Dest->getExprLoc(), Dest,
10654       PDiag(diag::note_bad_memaccess_silence)
10655         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10656     break;
10657   }
10658 }
10659 
10660 // A little helper routine: ignore addition and subtraction of integer literals.
10661 // This intentionally does not ignore all integer constant expressions because
10662 // we don't want to remove sizeof().
10663 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10664   Ex = Ex->IgnoreParenCasts();
10665 
10666   while (true) {
10667     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10668     if (!BO || !BO->isAdditiveOp())
10669       break;
10670 
10671     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10672     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10673 
10674     if (isa<IntegerLiteral>(RHS))
10675       Ex = LHS;
10676     else if (isa<IntegerLiteral>(LHS))
10677       Ex = RHS;
10678     else
10679       break;
10680   }
10681 
10682   return Ex;
10683 }
10684 
10685 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10686                                                       ASTContext &Context) {
10687   // Only handle constant-sized or VLAs, but not flexible members.
10688   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10689     // Only issue the FIXIT for arrays of size > 1.
10690     if (CAT->getSize().getSExtValue() <= 1)
10691       return false;
10692   } else if (!Ty->isVariableArrayType()) {
10693     return false;
10694   }
10695   return true;
10696 }
10697 
10698 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10699 // be the size of the source, instead of the destination.
10700 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10701                                     IdentifierInfo *FnName) {
10702 
10703   // Don't crash if the user has the wrong number of arguments
10704   unsigned NumArgs = Call->getNumArgs();
10705   if ((NumArgs != 3) && (NumArgs != 4))
10706     return;
10707 
10708   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10709   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10710   const Expr *CompareWithSrc = nullptr;
10711 
10712   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10713                                      Call->getBeginLoc(), Call->getRParenLoc()))
10714     return;
10715 
10716   // Look for 'strlcpy(dst, x, sizeof(x))'
10717   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10718     CompareWithSrc = Ex;
10719   else {
10720     // Look for 'strlcpy(dst, x, strlen(x))'
10721     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10722       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10723           SizeCall->getNumArgs() == 1)
10724         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10725     }
10726   }
10727 
10728   if (!CompareWithSrc)
10729     return;
10730 
10731   // Determine if the argument to sizeof/strlen is equal to the source
10732   // argument.  In principle there's all kinds of things you could do
10733   // here, for instance creating an == expression and evaluating it with
10734   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10735   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10736   if (!SrcArgDRE)
10737     return;
10738 
10739   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10740   if (!CompareWithSrcDRE ||
10741       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10742     return;
10743 
10744   const Expr *OriginalSizeArg = Call->getArg(2);
10745   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10746       << OriginalSizeArg->getSourceRange() << FnName;
10747 
10748   // Output a FIXIT hint if the destination is an array (rather than a
10749   // pointer to an array).  This could be enhanced to handle some
10750   // pointers if we know the actual size, like if DstArg is 'array+2'
10751   // we could say 'sizeof(array)-2'.
10752   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10753   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10754     return;
10755 
10756   SmallString<128> sizeString;
10757   llvm::raw_svector_ostream OS(sizeString);
10758   OS << "sizeof(";
10759   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10760   OS << ")";
10761 
10762   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10763       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10764                                       OS.str());
10765 }
10766 
10767 /// Check if two expressions refer to the same declaration.
10768 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10769   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10770     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10771       return D1->getDecl() == D2->getDecl();
10772   return false;
10773 }
10774 
10775 static const Expr *getStrlenExprArg(const Expr *E) {
10776   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10777     const FunctionDecl *FD = CE->getDirectCallee();
10778     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10779       return nullptr;
10780     return CE->getArg(0)->IgnoreParenCasts();
10781   }
10782   return nullptr;
10783 }
10784 
10785 // Warn on anti-patterns as the 'size' argument to strncat.
10786 // The correct size argument should look like following:
10787 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10788 void Sema::CheckStrncatArguments(const CallExpr *CE,
10789                                  IdentifierInfo *FnName) {
10790   // Don't crash if the user has the wrong number of arguments.
10791   if (CE->getNumArgs() < 3)
10792     return;
10793   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10794   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10795   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10796 
10797   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10798                                      CE->getRParenLoc()))
10799     return;
10800 
10801   // Identify common expressions, which are wrongly used as the size argument
10802   // to strncat and may lead to buffer overflows.
10803   unsigned PatternType = 0;
10804   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10805     // - sizeof(dst)
10806     if (referToTheSameDecl(SizeOfArg, DstArg))
10807       PatternType = 1;
10808     // - sizeof(src)
10809     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10810       PatternType = 2;
10811   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10812     if (BE->getOpcode() == BO_Sub) {
10813       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10814       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10815       // - sizeof(dst) - strlen(dst)
10816       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10817           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10818         PatternType = 1;
10819       // - sizeof(src) - (anything)
10820       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10821         PatternType = 2;
10822     }
10823   }
10824 
10825   if (PatternType == 0)
10826     return;
10827 
10828   // Generate the diagnostic.
10829   SourceLocation SL = LenArg->getBeginLoc();
10830   SourceRange SR = LenArg->getSourceRange();
10831   SourceManager &SM = getSourceManager();
10832 
10833   // If the function is defined as a builtin macro, do not show macro expansion.
10834   if (SM.isMacroArgExpansion(SL)) {
10835     SL = SM.getSpellingLoc(SL);
10836     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10837                      SM.getSpellingLoc(SR.getEnd()));
10838   }
10839 
10840   // Check if the destination is an array (rather than a pointer to an array).
10841   QualType DstTy = DstArg->getType();
10842   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10843                                                                     Context);
10844   if (!isKnownSizeArray) {
10845     if (PatternType == 1)
10846       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10847     else
10848       Diag(SL, diag::warn_strncat_src_size) << SR;
10849     return;
10850   }
10851 
10852   if (PatternType == 1)
10853     Diag(SL, diag::warn_strncat_large_size) << SR;
10854   else
10855     Diag(SL, diag::warn_strncat_src_size) << SR;
10856 
10857   SmallString<128> sizeString;
10858   llvm::raw_svector_ostream OS(sizeString);
10859   OS << "sizeof(";
10860   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10861   OS << ") - ";
10862   OS << "strlen(";
10863   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10864   OS << ") - 1";
10865 
10866   Diag(SL, diag::note_strncat_wrong_size)
10867     << FixItHint::CreateReplacement(SR, OS.str());
10868 }
10869 
10870 namespace {
10871 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10872                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10873   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10874     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10875         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10876     return;
10877   }
10878 }
10879 
10880 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10881                                  const UnaryOperator *UnaryExpr) {
10882   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10883     const Decl *D = Lvalue->getDecl();
10884     if (isa<DeclaratorDecl>(D))
10885       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10886         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10887   }
10888 
10889   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10890     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10891                                       Lvalue->getMemberDecl());
10892 }
10893 
10894 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10895                             const UnaryOperator *UnaryExpr) {
10896   const auto *Lambda = dyn_cast<LambdaExpr>(
10897       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10898   if (!Lambda)
10899     return;
10900 
10901   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10902       << CalleeName << 2 /*object: lambda expression*/;
10903 }
10904 
10905 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10906                                   const DeclRefExpr *Lvalue) {
10907   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10908   if (Var == nullptr)
10909     return;
10910 
10911   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10912       << CalleeName << 0 /*object: */ << Var;
10913 }
10914 
10915 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10916                             const CastExpr *Cast) {
10917   SmallString<128> SizeString;
10918   llvm::raw_svector_ostream OS(SizeString);
10919 
10920   clang::CastKind Kind = Cast->getCastKind();
10921   if (Kind == clang::CK_BitCast &&
10922       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10923     return;
10924   if (Kind == clang::CK_IntegralToPointer &&
10925       !isa<IntegerLiteral>(
10926           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10927     return;
10928 
10929   switch (Cast->getCastKind()) {
10930   case clang::CK_BitCast:
10931   case clang::CK_IntegralToPointer:
10932   case clang::CK_FunctionToPointerDecay:
10933     OS << '\'';
10934     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10935     OS << '\'';
10936     break;
10937   default:
10938     return;
10939   }
10940 
10941   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10942       << CalleeName << 0 /*object: */ << OS.str();
10943 }
10944 } // namespace
10945 
10946 /// Alerts the user that they are attempting to free a non-malloc'd object.
10947 void Sema::CheckFreeArguments(const CallExpr *E) {
10948   const std::string CalleeName =
10949       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10950 
10951   { // Prefer something that doesn't involve a cast to make things simpler.
10952     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10953     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10954       switch (UnaryExpr->getOpcode()) {
10955       case UnaryOperator::Opcode::UO_AddrOf:
10956         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10957       case UnaryOperator::Opcode::UO_Plus:
10958         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10959       default:
10960         break;
10961       }
10962 
10963     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10964       if (Lvalue->getType()->isArrayType())
10965         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10966 
10967     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10968       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10969           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10970       return;
10971     }
10972 
10973     if (isa<BlockExpr>(Arg)) {
10974       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10975           << CalleeName << 1 /*object: block*/;
10976       return;
10977     }
10978   }
10979   // Maybe the cast was important, check after the other cases.
10980   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10981     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10982 }
10983 
10984 void
10985 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10986                          SourceLocation ReturnLoc,
10987                          bool isObjCMethod,
10988                          const AttrVec *Attrs,
10989                          const FunctionDecl *FD) {
10990   // Check if the return value is null but should not be.
10991   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10992        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10993       CheckNonNullExpr(*this, RetValExp))
10994     Diag(ReturnLoc, diag::warn_null_ret)
10995       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10996 
10997   // C++11 [basic.stc.dynamic.allocation]p4:
10998   //   If an allocation function declared with a non-throwing
10999   //   exception-specification fails to allocate storage, it shall return
11000   //   a null pointer. Any other allocation function that fails to allocate
11001   //   storage shall indicate failure only by throwing an exception [...]
11002   if (FD) {
11003     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11004     if (Op == OO_New || Op == OO_Array_New) {
11005       const FunctionProtoType *Proto
11006         = FD->getType()->castAs<FunctionProtoType>();
11007       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11008           CheckNonNullExpr(*this, RetValExp))
11009         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11010           << FD << getLangOpts().CPlusPlus11;
11011     }
11012   }
11013 
11014   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11015   // here prevent the user from using a PPC MMA type as trailing return type.
11016   if (Context.getTargetInfo().getTriple().isPPC64())
11017     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11018 }
11019 
11020 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11021 
11022 /// Check for comparisons of floating point operands using != and ==.
11023 /// Issue a warning if these are no self-comparisons, as they are not likely
11024 /// to do what the programmer intended.
11025 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11026   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11027   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11028 
11029   // Special case: check for x == x (which is OK).
11030   // Do not emit warnings for such cases.
11031   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11032     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11033       if (DRL->getDecl() == DRR->getDecl())
11034         return;
11035 
11036   // Special case: check for comparisons against literals that can be exactly
11037   //  represented by APFloat.  In such cases, do not emit a warning.  This
11038   //  is a heuristic: often comparison against such literals are used to
11039   //  detect if a value in a variable has not changed.  This clearly can
11040   //  lead to false negatives.
11041   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11042     if (FLL->isExact())
11043       return;
11044   } else
11045     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11046       if (FLR->isExact())
11047         return;
11048 
11049   // Check for comparisons with builtin types.
11050   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11051     if (CL->getBuiltinCallee())
11052       return;
11053 
11054   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11055     if (CR->getBuiltinCallee())
11056       return;
11057 
11058   // Emit the diagnostic.
11059   Diag(Loc, diag::warn_floatingpoint_eq)
11060     << LHS->getSourceRange() << RHS->getSourceRange();
11061 }
11062 
11063 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11064 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11065 
11066 namespace {
11067 
11068 /// Structure recording the 'active' range of an integer-valued
11069 /// expression.
11070 struct IntRange {
11071   /// The number of bits active in the int. Note that this includes exactly one
11072   /// sign bit if !NonNegative.
11073   unsigned Width;
11074 
11075   /// True if the int is known not to have negative values. If so, all leading
11076   /// bits before Width are known zero, otherwise they are known to be the
11077   /// same as the MSB within Width.
11078   bool NonNegative;
11079 
11080   IntRange(unsigned Width, bool NonNegative)
11081       : Width(Width), NonNegative(NonNegative) {}
11082 
11083   /// Number of bits excluding the sign bit.
11084   unsigned valueBits() const {
11085     return NonNegative ? Width : Width - 1;
11086   }
11087 
11088   /// Returns the range of the bool type.
11089   static IntRange forBoolType() {
11090     return IntRange(1, true);
11091   }
11092 
11093   /// Returns the range of an opaque value of the given integral type.
11094   static IntRange forValueOfType(ASTContext &C, QualType T) {
11095     return forValueOfCanonicalType(C,
11096                           T->getCanonicalTypeInternal().getTypePtr());
11097   }
11098 
11099   /// Returns the range of an opaque value of a canonical integral type.
11100   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11101     assert(T->isCanonicalUnqualified());
11102 
11103     if (const VectorType *VT = dyn_cast<VectorType>(T))
11104       T = VT->getElementType().getTypePtr();
11105     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11106       T = CT->getElementType().getTypePtr();
11107     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11108       T = AT->getValueType().getTypePtr();
11109 
11110     if (!C.getLangOpts().CPlusPlus) {
11111       // For enum types in C code, use the underlying datatype.
11112       if (const EnumType *ET = dyn_cast<EnumType>(T))
11113         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11114     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11115       // For enum types in C++, use the known bit width of the enumerators.
11116       EnumDecl *Enum = ET->getDecl();
11117       // In C++11, enums can have a fixed underlying type. Use this type to
11118       // compute the range.
11119       if (Enum->isFixed()) {
11120         return IntRange(C.getIntWidth(QualType(T, 0)),
11121                         !ET->isSignedIntegerOrEnumerationType());
11122       }
11123 
11124       unsigned NumPositive = Enum->getNumPositiveBits();
11125       unsigned NumNegative = Enum->getNumNegativeBits();
11126 
11127       if (NumNegative == 0)
11128         return IntRange(NumPositive, true/*NonNegative*/);
11129       else
11130         return IntRange(std::max(NumPositive + 1, NumNegative),
11131                         false/*NonNegative*/);
11132     }
11133 
11134     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11135       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11136 
11137     const BuiltinType *BT = cast<BuiltinType>(T);
11138     assert(BT->isInteger());
11139 
11140     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11141   }
11142 
11143   /// Returns the "target" range of a canonical integral type, i.e.
11144   /// the range of values expressible in the type.
11145   ///
11146   /// This matches forValueOfCanonicalType except that enums have the
11147   /// full range of their type, not the range of their enumerators.
11148   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11149     assert(T->isCanonicalUnqualified());
11150 
11151     if (const VectorType *VT = dyn_cast<VectorType>(T))
11152       T = VT->getElementType().getTypePtr();
11153     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11154       T = CT->getElementType().getTypePtr();
11155     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11156       T = AT->getValueType().getTypePtr();
11157     if (const EnumType *ET = dyn_cast<EnumType>(T))
11158       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11159 
11160     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11161       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11162 
11163     const BuiltinType *BT = cast<BuiltinType>(T);
11164     assert(BT->isInteger());
11165 
11166     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11167   }
11168 
11169   /// Returns the supremum of two ranges: i.e. their conservative merge.
11170   static IntRange join(IntRange L, IntRange R) {
11171     bool Unsigned = L.NonNegative && R.NonNegative;
11172     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11173                     L.NonNegative && R.NonNegative);
11174   }
11175 
11176   /// Return the range of a bitwise-AND of the two ranges.
11177   static IntRange bit_and(IntRange L, IntRange R) {
11178     unsigned Bits = std::max(L.Width, R.Width);
11179     bool NonNegative = false;
11180     if (L.NonNegative) {
11181       Bits = std::min(Bits, L.Width);
11182       NonNegative = true;
11183     }
11184     if (R.NonNegative) {
11185       Bits = std::min(Bits, R.Width);
11186       NonNegative = true;
11187     }
11188     return IntRange(Bits, NonNegative);
11189   }
11190 
11191   /// Return the range of a sum of the two ranges.
11192   static IntRange sum(IntRange L, IntRange R) {
11193     bool Unsigned = L.NonNegative && R.NonNegative;
11194     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11195                     Unsigned);
11196   }
11197 
11198   /// Return the range of a difference of the two ranges.
11199   static IntRange difference(IntRange L, IntRange R) {
11200     // We need a 1-bit-wider range if:
11201     //   1) LHS can be negative: least value can be reduced.
11202     //   2) RHS can be negative: greatest value can be increased.
11203     bool CanWiden = !L.NonNegative || !R.NonNegative;
11204     bool Unsigned = L.NonNegative && R.Width == 0;
11205     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11206                         !Unsigned,
11207                     Unsigned);
11208   }
11209 
11210   /// Return the range of a product of the two ranges.
11211   static IntRange product(IntRange L, IntRange R) {
11212     // If both LHS and RHS can be negative, we can form
11213     //   -2^L * -2^R = 2^(L + R)
11214     // which requires L + R + 1 value bits to represent.
11215     bool CanWiden = !L.NonNegative && !R.NonNegative;
11216     bool Unsigned = L.NonNegative && R.NonNegative;
11217     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11218                     Unsigned);
11219   }
11220 
11221   /// Return the range of a remainder operation between the two ranges.
11222   static IntRange rem(IntRange L, IntRange R) {
11223     // The result of a remainder can't be larger than the result of
11224     // either side. The sign of the result is the sign of the LHS.
11225     bool Unsigned = L.NonNegative;
11226     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11227                     Unsigned);
11228   }
11229 };
11230 
11231 } // namespace
11232 
11233 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11234                               unsigned MaxWidth) {
11235   if (value.isSigned() && value.isNegative())
11236     return IntRange(value.getMinSignedBits(), false);
11237 
11238   if (value.getBitWidth() > MaxWidth)
11239     value = value.trunc(MaxWidth);
11240 
11241   // isNonNegative() just checks the sign bit without considering
11242   // signedness.
11243   return IntRange(value.getActiveBits(), true);
11244 }
11245 
11246 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11247                               unsigned MaxWidth) {
11248   if (result.isInt())
11249     return GetValueRange(C, result.getInt(), MaxWidth);
11250 
11251   if (result.isVector()) {
11252     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11253     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11254       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11255       R = IntRange::join(R, El);
11256     }
11257     return R;
11258   }
11259 
11260   if (result.isComplexInt()) {
11261     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11262     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11263     return IntRange::join(R, I);
11264   }
11265 
11266   // This can happen with lossless casts to intptr_t of "based" lvalues.
11267   // Assume it might use arbitrary bits.
11268   // FIXME: The only reason we need to pass the type in here is to get
11269   // the sign right on this one case.  It would be nice if APValue
11270   // preserved this.
11271   assert(result.isLValue() || result.isAddrLabelDiff());
11272   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11273 }
11274 
11275 static QualType GetExprType(const Expr *E) {
11276   QualType Ty = E->getType();
11277   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11278     Ty = AtomicRHS->getValueType();
11279   return Ty;
11280 }
11281 
11282 /// Pseudo-evaluate the given integer expression, estimating the
11283 /// range of values it might take.
11284 ///
11285 /// \param MaxWidth The width to which the value will be truncated.
11286 /// \param Approximate If \c true, return a likely range for the result: in
11287 ///        particular, assume that arithmetic on narrower types doesn't leave
11288 ///        those types. If \c false, return a range including all possible
11289 ///        result values.
11290 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11291                              bool InConstantContext, bool Approximate) {
11292   E = E->IgnoreParens();
11293 
11294   // Try a full evaluation first.
11295   Expr::EvalResult result;
11296   if (E->EvaluateAsRValue(result, C, InConstantContext))
11297     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11298 
11299   // I think we only want to look through implicit casts here; if the
11300   // user has an explicit widening cast, we should treat the value as
11301   // being of the new, wider type.
11302   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11303     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11304       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11305                           Approximate);
11306 
11307     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11308 
11309     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11310                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11311 
11312     // Assume that non-integer casts can span the full range of the type.
11313     if (!isIntegerCast)
11314       return OutputTypeRange;
11315 
11316     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11317                                      std::min(MaxWidth, OutputTypeRange.Width),
11318                                      InConstantContext, Approximate);
11319 
11320     // Bail out if the subexpr's range is as wide as the cast type.
11321     if (SubRange.Width >= OutputTypeRange.Width)
11322       return OutputTypeRange;
11323 
11324     // Otherwise, we take the smaller width, and we're non-negative if
11325     // either the output type or the subexpr is.
11326     return IntRange(SubRange.Width,
11327                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11328   }
11329 
11330   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11331     // If we can fold the condition, just take that operand.
11332     bool CondResult;
11333     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11334       return GetExprRange(C,
11335                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11336                           MaxWidth, InConstantContext, Approximate);
11337 
11338     // Otherwise, conservatively merge.
11339     // GetExprRange requires an integer expression, but a throw expression
11340     // results in a void type.
11341     Expr *E = CO->getTrueExpr();
11342     IntRange L = E->getType()->isVoidType()
11343                      ? IntRange{0, true}
11344                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11345     E = CO->getFalseExpr();
11346     IntRange R = E->getType()->isVoidType()
11347                      ? IntRange{0, true}
11348                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11349     return IntRange::join(L, R);
11350   }
11351 
11352   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11353     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11354 
11355     switch (BO->getOpcode()) {
11356     case BO_Cmp:
11357       llvm_unreachable("builtin <=> should have class type");
11358 
11359     // Boolean-valued operations are single-bit and positive.
11360     case BO_LAnd:
11361     case BO_LOr:
11362     case BO_LT:
11363     case BO_GT:
11364     case BO_LE:
11365     case BO_GE:
11366     case BO_EQ:
11367     case BO_NE:
11368       return IntRange::forBoolType();
11369 
11370     // The type of the assignments is the type of the LHS, so the RHS
11371     // is not necessarily the same type.
11372     case BO_MulAssign:
11373     case BO_DivAssign:
11374     case BO_RemAssign:
11375     case BO_AddAssign:
11376     case BO_SubAssign:
11377     case BO_XorAssign:
11378     case BO_OrAssign:
11379       // TODO: bitfields?
11380       return IntRange::forValueOfType(C, GetExprType(E));
11381 
11382     // Simple assignments just pass through the RHS, which will have
11383     // been coerced to the LHS type.
11384     case BO_Assign:
11385       // TODO: bitfields?
11386       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11387                           Approximate);
11388 
11389     // Operations with opaque sources are black-listed.
11390     case BO_PtrMemD:
11391     case BO_PtrMemI:
11392       return IntRange::forValueOfType(C, GetExprType(E));
11393 
11394     // Bitwise-and uses the *infinum* of the two source ranges.
11395     case BO_And:
11396     case BO_AndAssign:
11397       Combine = IntRange::bit_and;
11398       break;
11399 
11400     // Left shift gets black-listed based on a judgement call.
11401     case BO_Shl:
11402       // ...except that we want to treat '1 << (blah)' as logically
11403       // positive.  It's an important idiom.
11404       if (IntegerLiteral *I
11405             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11406         if (I->getValue() == 1) {
11407           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11408           return IntRange(R.Width, /*NonNegative*/ true);
11409         }
11410       }
11411       LLVM_FALLTHROUGH;
11412 
11413     case BO_ShlAssign:
11414       return IntRange::forValueOfType(C, GetExprType(E));
11415 
11416     // Right shift by a constant can narrow its left argument.
11417     case BO_Shr:
11418     case BO_ShrAssign: {
11419       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11420                                 Approximate);
11421 
11422       // If the shift amount is a positive constant, drop the width by
11423       // that much.
11424       if (Optional<llvm::APSInt> shift =
11425               BO->getRHS()->getIntegerConstantExpr(C)) {
11426         if (shift->isNonNegative()) {
11427           unsigned zext = shift->getZExtValue();
11428           if (zext >= L.Width)
11429             L.Width = (L.NonNegative ? 0 : 1);
11430           else
11431             L.Width -= zext;
11432         }
11433       }
11434 
11435       return L;
11436     }
11437 
11438     // Comma acts as its right operand.
11439     case BO_Comma:
11440       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11441                           Approximate);
11442 
11443     case BO_Add:
11444       if (!Approximate)
11445         Combine = IntRange::sum;
11446       break;
11447 
11448     case BO_Sub:
11449       if (BO->getLHS()->getType()->isPointerType())
11450         return IntRange::forValueOfType(C, GetExprType(E));
11451       if (!Approximate)
11452         Combine = IntRange::difference;
11453       break;
11454 
11455     case BO_Mul:
11456       if (!Approximate)
11457         Combine = IntRange::product;
11458       break;
11459 
11460     // The width of a division result is mostly determined by the size
11461     // of the LHS.
11462     case BO_Div: {
11463       // Don't 'pre-truncate' the operands.
11464       unsigned opWidth = C.getIntWidth(GetExprType(E));
11465       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11466                                 Approximate);
11467 
11468       // If the divisor is constant, use that.
11469       if (Optional<llvm::APSInt> divisor =
11470               BO->getRHS()->getIntegerConstantExpr(C)) {
11471         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11472         if (log2 >= L.Width)
11473           L.Width = (L.NonNegative ? 0 : 1);
11474         else
11475           L.Width = std::min(L.Width - log2, MaxWidth);
11476         return L;
11477       }
11478 
11479       // Otherwise, just use the LHS's width.
11480       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11481       // could be -1.
11482       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11483                                 Approximate);
11484       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11485     }
11486 
11487     case BO_Rem:
11488       Combine = IntRange::rem;
11489       break;
11490 
11491     // The default behavior is okay for these.
11492     case BO_Xor:
11493     case BO_Or:
11494       break;
11495     }
11496 
11497     // Combine the two ranges, but limit the result to the type in which we
11498     // performed the computation.
11499     QualType T = GetExprType(E);
11500     unsigned opWidth = C.getIntWidth(T);
11501     IntRange L =
11502         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11503     IntRange R =
11504         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11505     IntRange C = Combine(L, R);
11506     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11507     C.Width = std::min(C.Width, MaxWidth);
11508     return C;
11509   }
11510 
11511   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11512     switch (UO->getOpcode()) {
11513     // Boolean-valued operations are white-listed.
11514     case UO_LNot:
11515       return IntRange::forBoolType();
11516 
11517     // Operations with opaque sources are black-listed.
11518     case UO_Deref:
11519     case UO_AddrOf: // should be impossible
11520       return IntRange::forValueOfType(C, GetExprType(E));
11521 
11522     default:
11523       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11524                           Approximate);
11525     }
11526   }
11527 
11528   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11529     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11530                         Approximate);
11531 
11532   if (const auto *BitField = E->getSourceBitField())
11533     return IntRange(BitField->getBitWidthValue(C),
11534                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11535 
11536   return IntRange::forValueOfType(C, GetExprType(E));
11537 }
11538 
11539 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11540                              bool InConstantContext, bool Approximate) {
11541   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11542                       Approximate);
11543 }
11544 
11545 /// Checks whether the given value, which currently has the given
11546 /// source semantics, has the same value when coerced through the
11547 /// target semantics.
11548 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11549                                  const llvm::fltSemantics &Src,
11550                                  const llvm::fltSemantics &Tgt) {
11551   llvm::APFloat truncated = value;
11552 
11553   bool ignored;
11554   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11555   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11556 
11557   return truncated.bitwiseIsEqual(value);
11558 }
11559 
11560 /// Checks whether the given value, which currently has the given
11561 /// source semantics, has the same value when coerced through the
11562 /// target semantics.
11563 ///
11564 /// The value might be a vector of floats (or a complex number).
11565 static bool IsSameFloatAfterCast(const APValue &value,
11566                                  const llvm::fltSemantics &Src,
11567                                  const llvm::fltSemantics &Tgt) {
11568   if (value.isFloat())
11569     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11570 
11571   if (value.isVector()) {
11572     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11573       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11574         return false;
11575     return true;
11576   }
11577 
11578   assert(value.isComplexFloat());
11579   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11580           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11581 }
11582 
11583 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11584                                        bool IsListInit = false);
11585 
11586 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11587   // Suppress cases where we are comparing against an enum constant.
11588   if (const DeclRefExpr *DR =
11589       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11590     if (isa<EnumConstantDecl>(DR->getDecl()))
11591       return true;
11592 
11593   // Suppress cases where the value is expanded from a macro, unless that macro
11594   // is how a language represents a boolean literal. This is the case in both C
11595   // and Objective-C.
11596   SourceLocation BeginLoc = E->getBeginLoc();
11597   if (BeginLoc.isMacroID()) {
11598     StringRef MacroName = Lexer::getImmediateMacroName(
11599         BeginLoc, S.getSourceManager(), S.getLangOpts());
11600     return MacroName != "YES" && MacroName != "NO" &&
11601            MacroName != "true" && MacroName != "false";
11602   }
11603 
11604   return false;
11605 }
11606 
11607 static bool isKnownToHaveUnsignedValue(Expr *E) {
11608   return E->getType()->isIntegerType() &&
11609          (!E->getType()->isSignedIntegerType() ||
11610           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11611 }
11612 
11613 namespace {
11614 /// The promoted range of values of a type. In general this has the
11615 /// following structure:
11616 ///
11617 ///     |-----------| . . . |-----------|
11618 ///     ^           ^       ^           ^
11619 ///    Min       HoleMin  HoleMax      Max
11620 ///
11621 /// ... where there is only a hole if a signed type is promoted to unsigned
11622 /// (in which case Min and Max are the smallest and largest representable
11623 /// values).
11624 struct PromotedRange {
11625   // Min, or HoleMax if there is a hole.
11626   llvm::APSInt PromotedMin;
11627   // Max, or HoleMin if there is a hole.
11628   llvm::APSInt PromotedMax;
11629 
11630   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11631     if (R.Width == 0)
11632       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11633     else if (R.Width >= BitWidth && !Unsigned) {
11634       // Promotion made the type *narrower*. This happens when promoting
11635       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11636       // Treat all values of 'signed int' as being in range for now.
11637       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11638       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11639     } else {
11640       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11641                         .extOrTrunc(BitWidth);
11642       PromotedMin.setIsUnsigned(Unsigned);
11643 
11644       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11645                         .extOrTrunc(BitWidth);
11646       PromotedMax.setIsUnsigned(Unsigned);
11647     }
11648   }
11649 
11650   // Determine whether this range is contiguous (has no hole).
11651   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11652 
11653   // Where a constant value is within the range.
11654   enum ComparisonResult {
11655     LT = 0x1,
11656     LE = 0x2,
11657     GT = 0x4,
11658     GE = 0x8,
11659     EQ = 0x10,
11660     NE = 0x20,
11661     InRangeFlag = 0x40,
11662 
11663     Less = LE | LT | NE,
11664     Min = LE | InRangeFlag,
11665     InRange = InRangeFlag,
11666     Max = GE | InRangeFlag,
11667     Greater = GE | GT | NE,
11668 
11669     OnlyValue = LE | GE | EQ | InRangeFlag,
11670     InHole = NE
11671   };
11672 
11673   ComparisonResult compare(const llvm::APSInt &Value) const {
11674     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11675            Value.isUnsigned() == PromotedMin.isUnsigned());
11676     if (!isContiguous()) {
11677       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11678       if (Value.isMinValue()) return Min;
11679       if (Value.isMaxValue()) return Max;
11680       if (Value >= PromotedMin) return InRange;
11681       if (Value <= PromotedMax) return InRange;
11682       return InHole;
11683     }
11684 
11685     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11686     case -1: return Less;
11687     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11688     case 1:
11689       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11690       case -1: return InRange;
11691       case 0: return Max;
11692       case 1: return Greater;
11693       }
11694     }
11695 
11696     llvm_unreachable("impossible compare result");
11697   }
11698 
11699   static llvm::Optional<StringRef>
11700   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11701     if (Op == BO_Cmp) {
11702       ComparisonResult LTFlag = LT, GTFlag = GT;
11703       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11704 
11705       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11706       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11707       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11708       return llvm::None;
11709     }
11710 
11711     ComparisonResult TrueFlag, FalseFlag;
11712     if (Op == BO_EQ) {
11713       TrueFlag = EQ;
11714       FalseFlag = NE;
11715     } else if (Op == BO_NE) {
11716       TrueFlag = NE;
11717       FalseFlag = EQ;
11718     } else {
11719       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11720         TrueFlag = LT;
11721         FalseFlag = GE;
11722       } else {
11723         TrueFlag = GT;
11724         FalseFlag = LE;
11725       }
11726       if (Op == BO_GE || Op == BO_LE)
11727         std::swap(TrueFlag, FalseFlag);
11728     }
11729     if (R & TrueFlag)
11730       return StringRef("true");
11731     if (R & FalseFlag)
11732       return StringRef("false");
11733     return llvm::None;
11734   }
11735 };
11736 }
11737 
11738 static bool HasEnumType(Expr *E) {
11739   // Strip off implicit integral promotions.
11740   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11741     if (ICE->getCastKind() != CK_IntegralCast &&
11742         ICE->getCastKind() != CK_NoOp)
11743       break;
11744     E = ICE->getSubExpr();
11745   }
11746 
11747   return E->getType()->isEnumeralType();
11748 }
11749 
11750 static int classifyConstantValue(Expr *Constant) {
11751   // The values of this enumeration are used in the diagnostics
11752   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11753   enum ConstantValueKind {
11754     Miscellaneous = 0,
11755     LiteralTrue,
11756     LiteralFalse
11757   };
11758   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11759     return BL->getValue() ? ConstantValueKind::LiteralTrue
11760                           : ConstantValueKind::LiteralFalse;
11761   return ConstantValueKind::Miscellaneous;
11762 }
11763 
11764 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11765                                         Expr *Constant, Expr *Other,
11766                                         const llvm::APSInt &Value,
11767                                         bool RhsConstant) {
11768   if (S.inTemplateInstantiation())
11769     return false;
11770 
11771   Expr *OriginalOther = Other;
11772 
11773   Constant = Constant->IgnoreParenImpCasts();
11774   Other = Other->IgnoreParenImpCasts();
11775 
11776   // Suppress warnings on tautological comparisons between values of the same
11777   // enumeration type. There are only two ways we could warn on this:
11778   //  - If the constant is outside the range of representable values of
11779   //    the enumeration. In such a case, we should warn about the cast
11780   //    to enumeration type, not about the comparison.
11781   //  - If the constant is the maximum / minimum in-range value. For an
11782   //    enumeratin type, such comparisons can be meaningful and useful.
11783   if (Constant->getType()->isEnumeralType() &&
11784       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11785     return false;
11786 
11787   IntRange OtherValueRange = GetExprRange(
11788       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11789 
11790   QualType OtherT = Other->getType();
11791   if (const auto *AT = OtherT->getAs<AtomicType>())
11792     OtherT = AT->getValueType();
11793   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11794 
11795   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11796   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11797   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11798                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11799                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11800 
11801   // Whether we're treating Other as being a bool because of the form of
11802   // expression despite it having another type (typically 'int' in C).
11803   bool OtherIsBooleanDespiteType =
11804       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11805   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11806     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11807 
11808   // Check if all values in the range of possible values of this expression
11809   // lead to the same comparison outcome.
11810   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11811                                         Value.isUnsigned());
11812   auto Cmp = OtherPromotedValueRange.compare(Value);
11813   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11814   if (!Result)
11815     return false;
11816 
11817   // Also consider the range determined by the type alone. This allows us to
11818   // classify the warning under the proper diagnostic group.
11819   bool TautologicalTypeCompare = false;
11820   {
11821     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11822                                          Value.isUnsigned());
11823     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11824     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11825                                                        RhsConstant)) {
11826       TautologicalTypeCompare = true;
11827       Cmp = TypeCmp;
11828       Result = TypeResult;
11829     }
11830   }
11831 
11832   // Don't warn if the non-constant operand actually always evaluates to the
11833   // same value.
11834   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11835     return false;
11836 
11837   // Suppress the diagnostic for an in-range comparison if the constant comes
11838   // from a macro or enumerator. We don't want to diagnose
11839   //
11840   //   some_long_value <= INT_MAX
11841   //
11842   // when sizeof(int) == sizeof(long).
11843   bool InRange = Cmp & PromotedRange::InRangeFlag;
11844   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11845     return false;
11846 
11847   // A comparison of an unsigned bit-field against 0 is really a type problem,
11848   // even though at the type level the bit-field might promote to 'signed int'.
11849   if (Other->refersToBitField() && InRange && Value == 0 &&
11850       Other->getType()->isUnsignedIntegerOrEnumerationType())
11851     TautologicalTypeCompare = true;
11852 
11853   // If this is a comparison to an enum constant, include that
11854   // constant in the diagnostic.
11855   const EnumConstantDecl *ED = nullptr;
11856   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11857     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11858 
11859   // Should be enough for uint128 (39 decimal digits)
11860   SmallString<64> PrettySourceValue;
11861   llvm::raw_svector_ostream OS(PrettySourceValue);
11862   if (ED) {
11863     OS << '\'' << *ED << "' (" << Value << ")";
11864   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11865                Constant->IgnoreParenImpCasts())) {
11866     OS << (BL->getValue() ? "YES" : "NO");
11867   } else {
11868     OS << Value;
11869   }
11870 
11871   if (!TautologicalTypeCompare) {
11872     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11873         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11874         << E->getOpcodeStr() << OS.str() << *Result
11875         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11876     return true;
11877   }
11878 
11879   if (IsObjCSignedCharBool) {
11880     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11881                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11882                               << OS.str() << *Result);
11883     return true;
11884   }
11885 
11886   // FIXME: We use a somewhat different formatting for the in-range cases and
11887   // cases involving boolean values for historical reasons. We should pick a
11888   // consistent way of presenting these diagnostics.
11889   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11890 
11891     S.DiagRuntimeBehavior(
11892         E->getOperatorLoc(), E,
11893         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11894                          : diag::warn_tautological_bool_compare)
11895             << OS.str() << classifyConstantValue(Constant) << OtherT
11896             << OtherIsBooleanDespiteType << *Result
11897             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11898   } else {
11899     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11900     unsigned Diag =
11901         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11902             ? (HasEnumType(OriginalOther)
11903                    ? diag::warn_unsigned_enum_always_true_comparison
11904                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11905                               : diag::warn_unsigned_always_true_comparison)
11906             : diag::warn_tautological_constant_compare;
11907 
11908     S.Diag(E->getOperatorLoc(), Diag)
11909         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11910         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11911   }
11912 
11913   return true;
11914 }
11915 
11916 /// Analyze the operands of the given comparison.  Implements the
11917 /// fallback case from AnalyzeComparison.
11918 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11919   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11920   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11921 }
11922 
11923 /// Implements -Wsign-compare.
11924 ///
11925 /// \param E the binary operator to check for warnings
11926 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11927   // The type the comparison is being performed in.
11928   QualType T = E->getLHS()->getType();
11929 
11930   // Only analyze comparison operators where both sides have been converted to
11931   // the same type.
11932   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11933     return AnalyzeImpConvsInComparison(S, E);
11934 
11935   // Don't analyze value-dependent comparisons directly.
11936   if (E->isValueDependent())
11937     return AnalyzeImpConvsInComparison(S, E);
11938 
11939   Expr *LHS = E->getLHS();
11940   Expr *RHS = E->getRHS();
11941 
11942   if (T->isIntegralType(S.Context)) {
11943     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11944     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11945 
11946     // We don't care about expressions whose result is a constant.
11947     if (RHSValue && LHSValue)
11948       return AnalyzeImpConvsInComparison(S, E);
11949 
11950     // We only care about expressions where just one side is literal
11951     if ((bool)RHSValue ^ (bool)LHSValue) {
11952       // Is the constant on the RHS or LHS?
11953       const bool RhsConstant = (bool)RHSValue;
11954       Expr *Const = RhsConstant ? RHS : LHS;
11955       Expr *Other = RhsConstant ? LHS : RHS;
11956       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11957 
11958       // Check whether an integer constant comparison results in a value
11959       // of 'true' or 'false'.
11960       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11961         return AnalyzeImpConvsInComparison(S, E);
11962     }
11963   }
11964 
11965   if (!T->hasUnsignedIntegerRepresentation()) {
11966     // We don't do anything special if this isn't an unsigned integral
11967     // comparison:  we're only interested in integral comparisons, and
11968     // signed comparisons only happen in cases we don't care to warn about.
11969     return AnalyzeImpConvsInComparison(S, E);
11970   }
11971 
11972   LHS = LHS->IgnoreParenImpCasts();
11973   RHS = RHS->IgnoreParenImpCasts();
11974 
11975   if (!S.getLangOpts().CPlusPlus) {
11976     // Avoid warning about comparison of integers with different signs when
11977     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11978     // the type of `E`.
11979     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11980       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11981     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11982       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11983   }
11984 
11985   // Check to see if one of the (unmodified) operands is of different
11986   // signedness.
11987   Expr *signedOperand, *unsignedOperand;
11988   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11989     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11990            "unsigned comparison between two signed integer expressions?");
11991     signedOperand = LHS;
11992     unsignedOperand = RHS;
11993   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11994     signedOperand = RHS;
11995     unsignedOperand = LHS;
11996   } else {
11997     return AnalyzeImpConvsInComparison(S, E);
11998   }
11999 
12000   // Otherwise, calculate the effective range of the signed operand.
12001   IntRange signedRange = GetExprRange(
12002       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12003 
12004   // Go ahead and analyze implicit conversions in the operands.  Note
12005   // that we skip the implicit conversions on both sides.
12006   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12007   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12008 
12009   // If the signed range is non-negative, -Wsign-compare won't fire.
12010   if (signedRange.NonNegative)
12011     return;
12012 
12013   // For (in)equality comparisons, if the unsigned operand is a
12014   // constant which cannot collide with a overflowed signed operand,
12015   // then reinterpreting the signed operand as unsigned will not
12016   // change the result of the comparison.
12017   if (E->isEqualityOp()) {
12018     unsigned comparisonWidth = S.Context.getIntWidth(T);
12019     IntRange unsignedRange =
12020         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12021                      /*Approximate*/ true);
12022 
12023     // We should never be unable to prove that the unsigned operand is
12024     // non-negative.
12025     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12026 
12027     if (unsignedRange.Width < comparisonWidth)
12028       return;
12029   }
12030 
12031   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12032                         S.PDiag(diag::warn_mixed_sign_comparison)
12033                             << LHS->getType() << RHS->getType()
12034                             << LHS->getSourceRange() << RHS->getSourceRange());
12035 }
12036 
12037 /// Analyzes an attempt to assign the given value to a bitfield.
12038 ///
12039 /// Returns true if there was something fishy about the attempt.
12040 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12041                                       SourceLocation InitLoc) {
12042   assert(Bitfield->isBitField());
12043   if (Bitfield->isInvalidDecl())
12044     return false;
12045 
12046   // White-list bool bitfields.
12047   QualType BitfieldType = Bitfield->getType();
12048   if (BitfieldType->isBooleanType())
12049      return false;
12050 
12051   if (BitfieldType->isEnumeralType()) {
12052     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12053     // If the underlying enum type was not explicitly specified as an unsigned
12054     // type and the enum contain only positive values, MSVC++ will cause an
12055     // inconsistency by storing this as a signed type.
12056     if (S.getLangOpts().CPlusPlus11 &&
12057         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12058         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12059         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12060       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12061           << BitfieldEnumDecl;
12062     }
12063   }
12064 
12065   if (Bitfield->getType()->isBooleanType())
12066     return false;
12067 
12068   // Ignore value- or type-dependent expressions.
12069   if (Bitfield->getBitWidth()->isValueDependent() ||
12070       Bitfield->getBitWidth()->isTypeDependent() ||
12071       Init->isValueDependent() ||
12072       Init->isTypeDependent())
12073     return false;
12074 
12075   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12076   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12077 
12078   Expr::EvalResult Result;
12079   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12080                                    Expr::SE_AllowSideEffects)) {
12081     // The RHS is not constant.  If the RHS has an enum type, make sure the
12082     // bitfield is wide enough to hold all the values of the enum without
12083     // truncation.
12084     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12085       EnumDecl *ED = EnumTy->getDecl();
12086       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12087 
12088       // Enum types are implicitly signed on Windows, so check if there are any
12089       // negative enumerators to see if the enum was intended to be signed or
12090       // not.
12091       bool SignedEnum = ED->getNumNegativeBits() > 0;
12092 
12093       // Check for surprising sign changes when assigning enum values to a
12094       // bitfield of different signedness.  If the bitfield is signed and we
12095       // have exactly the right number of bits to store this unsigned enum,
12096       // suggest changing the enum to an unsigned type. This typically happens
12097       // on Windows where unfixed enums always use an underlying type of 'int'.
12098       unsigned DiagID = 0;
12099       if (SignedEnum && !SignedBitfield) {
12100         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12101       } else if (SignedBitfield && !SignedEnum &&
12102                  ED->getNumPositiveBits() == FieldWidth) {
12103         DiagID = diag::warn_signed_bitfield_enum_conversion;
12104       }
12105 
12106       if (DiagID) {
12107         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12108         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12109         SourceRange TypeRange =
12110             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12111         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12112             << SignedEnum << TypeRange;
12113       }
12114 
12115       // Compute the required bitwidth. If the enum has negative values, we need
12116       // one more bit than the normal number of positive bits to represent the
12117       // sign bit.
12118       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12119                                                   ED->getNumNegativeBits())
12120                                        : ED->getNumPositiveBits();
12121 
12122       // Check the bitwidth.
12123       if (BitsNeeded > FieldWidth) {
12124         Expr *WidthExpr = Bitfield->getBitWidth();
12125         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12126             << Bitfield << ED;
12127         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12128             << BitsNeeded << ED << WidthExpr->getSourceRange();
12129       }
12130     }
12131 
12132     return false;
12133   }
12134 
12135   llvm::APSInt Value = Result.Val.getInt();
12136 
12137   unsigned OriginalWidth = Value.getBitWidth();
12138 
12139   if (!Value.isSigned() || Value.isNegative())
12140     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12141       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12142         OriginalWidth = Value.getMinSignedBits();
12143 
12144   if (OriginalWidth <= FieldWidth)
12145     return false;
12146 
12147   // Compute the value which the bitfield will contain.
12148   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12149   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12150 
12151   // Check whether the stored value is equal to the original value.
12152   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12153   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12154     return false;
12155 
12156   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12157   // therefore don't strictly fit into a signed bitfield of width 1.
12158   if (FieldWidth == 1 && Value == 1)
12159     return false;
12160 
12161   std::string PrettyValue = toString(Value, 10);
12162   std::string PrettyTrunc = toString(TruncatedValue, 10);
12163 
12164   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12165     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12166     << Init->getSourceRange();
12167 
12168   return true;
12169 }
12170 
12171 /// Analyze the given simple or compound assignment for warning-worthy
12172 /// operations.
12173 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12174   // Just recurse on the LHS.
12175   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12176 
12177   // We want to recurse on the RHS as normal unless we're assigning to
12178   // a bitfield.
12179   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12180     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12181                                   E->getOperatorLoc())) {
12182       // Recurse, ignoring any implicit conversions on the RHS.
12183       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12184                                         E->getOperatorLoc());
12185     }
12186   }
12187 
12188   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12189 
12190   // Diagnose implicitly sequentially-consistent atomic assignment.
12191   if (E->getLHS()->getType()->isAtomicType())
12192     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12193 }
12194 
12195 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12196 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12197                             SourceLocation CContext, unsigned diag,
12198                             bool pruneControlFlow = false) {
12199   if (pruneControlFlow) {
12200     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12201                           S.PDiag(diag)
12202                               << SourceType << T << E->getSourceRange()
12203                               << SourceRange(CContext));
12204     return;
12205   }
12206   S.Diag(E->getExprLoc(), diag)
12207     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12208 }
12209 
12210 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12211 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12212                             SourceLocation CContext,
12213                             unsigned diag, bool pruneControlFlow = false) {
12214   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12215 }
12216 
12217 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12218   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12219       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12220 }
12221 
12222 static void adornObjCBoolConversionDiagWithTernaryFixit(
12223     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12224   Expr *Ignored = SourceExpr->IgnoreImplicit();
12225   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12226     Ignored = OVE->getSourceExpr();
12227   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12228                      isa<BinaryOperator>(Ignored) ||
12229                      isa<CXXOperatorCallExpr>(Ignored);
12230   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12231   if (NeedsParens)
12232     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12233             << FixItHint::CreateInsertion(EndLoc, ")");
12234   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12235 }
12236 
12237 /// Diagnose an implicit cast from a floating point value to an integer value.
12238 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12239                                     SourceLocation CContext) {
12240   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12241   const bool PruneWarnings = S.inTemplateInstantiation();
12242 
12243   Expr *InnerE = E->IgnoreParenImpCasts();
12244   // We also want to warn on, e.g., "int i = -1.234"
12245   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12246     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12247       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12248 
12249   const bool IsLiteral =
12250       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12251 
12252   llvm::APFloat Value(0.0);
12253   bool IsConstant =
12254     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12255   if (!IsConstant) {
12256     if (isObjCSignedCharBool(S, T)) {
12257       return adornObjCBoolConversionDiagWithTernaryFixit(
12258           S, E,
12259           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12260               << E->getType());
12261     }
12262 
12263     return DiagnoseImpCast(S, E, T, CContext,
12264                            diag::warn_impcast_float_integer, PruneWarnings);
12265   }
12266 
12267   bool isExact = false;
12268 
12269   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12270                             T->hasUnsignedIntegerRepresentation());
12271   llvm::APFloat::opStatus Result = Value.convertToInteger(
12272       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12273 
12274   // FIXME: Force the precision of the source value down so we don't print
12275   // digits which are usually useless (we don't really care here if we
12276   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12277   // would automatically print the shortest representation, but it's a bit
12278   // tricky to implement.
12279   SmallString<16> PrettySourceValue;
12280   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12281   precision = (precision * 59 + 195) / 196;
12282   Value.toString(PrettySourceValue, precision);
12283 
12284   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12285     return adornObjCBoolConversionDiagWithTernaryFixit(
12286         S, E,
12287         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12288             << PrettySourceValue);
12289   }
12290 
12291   if (Result == llvm::APFloat::opOK && isExact) {
12292     if (IsLiteral) return;
12293     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12294                            PruneWarnings);
12295   }
12296 
12297   // Conversion of a floating-point value to a non-bool integer where the
12298   // integral part cannot be represented by the integer type is undefined.
12299   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12300     return DiagnoseImpCast(
12301         S, E, T, CContext,
12302         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12303                   : diag::warn_impcast_float_to_integer_out_of_range,
12304         PruneWarnings);
12305 
12306   unsigned DiagID = 0;
12307   if (IsLiteral) {
12308     // Warn on floating point literal to integer.
12309     DiagID = diag::warn_impcast_literal_float_to_integer;
12310   } else if (IntegerValue == 0) {
12311     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12312       return DiagnoseImpCast(S, E, T, CContext,
12313                              diag::warn_impcast_float_integer, PruneWarnings);
12314     }
12315     // Warn on non-zero to zero conversion.
12316     DiagID = diag::warn_impcast_float_to_integer_zero;
12317   } else {
12318     if (IntegerValue.isUnsigned()) {
12319       if (!IntegerValue.isMaxValue()) {
12320         return DiagnoseImpCast(S, E, T, CContext,
12321                                diag::warn_impcast_float_integer, PruneWarnings);
12322       }
12323     } else {  // IntegerValue.isSigned()
12324       if (!IntegerValue.isMaxSignedValue() &&
12325           !IntegerValue.isMinSignedValue()) {
12326         return DiagnoseImpCast(S, E, T, CContext,
12327                                diag::warn_impcast_float_integer, PruneWarnings);
12328       }
12329     }
12330     // Warn on evaluatable floating point expression to integer conversion.
12331     DiagID = diag::warn_impcast_float_to_integer;
12332   }
12333 
12334   SmallString<16> PrettyTargetValue;
12335   if (IsBool)
12336     PrettyTargetValue = Value.isZero() ? "false" : "true";
12337   else
12338     IntegerValue.toString(PrettyTargetValue);
12339 
12340   if (PruneWarnings) {
12341     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12342                           S.PDiag(DiagID)
12343                               << E->getType() << T.getUnqualifiedType()
12344                               << PrettySourceValue << PrettyTargetValue
12345                               << E->getSourceRange() << SourceRange(CContext));
12346   } else {
12347     S.Diag(E->getExprLoc(), DiagID)
12348         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12349         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12350   }
12351 }
12352 
12353 /// Analyze the given compound assignment for the possible losing of
12354 /// floating-point precision.
12355 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12356   assert(isa<CompoundAssignOperator>(E) &&
12357          "Must be compound assignment operation");
12358   // Recurse on the LHS and RHS in here
12359   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12360   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12361 
12362   if (E->getLHS()->getType()->isAtomicType())
12363     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12364 
12365   // Now check the outermost expression
12366   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12367   const auto *RBT = cast<CompoundAssignOperator>(E)
12368                         ->getComputationResultType()
12369                         ->getAs<BuiltinType>();
12370 
12371   // The below checks assume source is floating point.
12372   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12373 
12374   // If source is floating point but target is an integer.
12375   if (ResultBT->isInteger())
12376     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12377                            E->getExprLoc(), diag::warn_impcast_float_integer);
12378 
12379   if (!ResultBT->isFloatingPoint())
12380     return;
12381 
12382   // If both source and target are floating points, warn about losing precision.
12383   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12384       QualType(ResultBT, 0), QualType(RBT, 0));
12385   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12386     // warn about dropping FP rank.
12387     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12388                     diag::warn_impcast_float_result_precision);
12389 }
12390 
12391 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12392                                       IntRange Range) {
12393   if (!Range.Width) return "0";
12394 
12395   llvm::APSInt ValueInRange = Value;
12396   ValueInRange.setIsSigned(!Range.NonNegative);
12397   ValueInRange = ValueInRange.trunc(Range.Width);
12398   return toString(ValueInRange, 10);
12399 }
12400 
12401 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12402   if (!isa<ImplicitCastExpr>(Ex))
12403     return false;
12404 
12405   Expr *InnerE = Ex->IgnoreParenImpCasts();
12406   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12407   const Type *Source =
12408     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12409   if (Target->isDependentType())
12410     return false;
12411 
12412   const BuiltinType *FloatCandidateBT =
12413     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12414   const Type *BoolCandidateType = ToBool ? Target : Source;
12415 
12416   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12417           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12418 }
12419 
12420 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12421                                              SourceLocation CC) {
12422   unsigned NumArgs = TheCall->getNumArgs();
12423   for (unsigned i = 0; i < NumArgs; ++i) {
12424     Expr *CurrA = TheCall->getArg(i);
12425     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12426       continue;
12427 
12428     bool IsSwapped = ((i > 0) &&
12429         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12430     IsSwapped |= ((i < (NumArgs - 1)) &&
12431         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12432     if (IsSwapped) {
12433       // Warn on this floating-point to bool conversion.
12434       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12435                       CurrA->getType(), CC,
12436                       diag::warn_impcast_floating_point_to_bool);
12437     }
12438   }
12439 }
12440 
12441 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12442                                    SourceLocation CC) {
12443   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12444                         E->getExprLoc()))
12445     return;
12446 
12447   // Don't warn on functions which have return type nullptr_t.
12448   if (isa<CallExpr>(E))
12449     return;
12450 
12451   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12452   const Expr::NullPointerConstantKind NullKind =
12453       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12454   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12455     return;
12456 
12457   // Return if target type is a safe conversion.
12458   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12459       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12460     return;
12461 
12462   SourceLocation Loc = E->getSourceRange().getBegin();
12463 
12464   // Venture through the macro stacks to get to the source of macro arguments.
12465   // The new location is a better location than the complete location that was
12466   // passed in.
12467   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12468   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12469 
12470   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12471   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12472     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12473         Loc, S.SourceMgr, S.getLangOpts());
12474     if (MacroName == "NULL")
12475       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12476   }
12477 
12478   // Only warn if the null and context location are in the same macro expansion.
12479   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12480     return;
12481 
12482   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12483       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12484       << FixItHint::CreateReplacement(Loc,
12485                                       S.getFixItZeroLiteralForType(T, Loc));
12486 }
12487 
12488 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12489                                   ObjCArrayLiteral *ArrayLiteral);
12490 
12491 static void
12492 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12493                            ObjCDictionaryLiteral *DictionaryLiteral);
12494 
12495 /// Check a single element within a collection literal against the
12496 /// target element type.
12497 static void checkObjCCollectionLiteralElement(Sema &S,
12498                                               QualType TargetElementType,
12499                                               Expr *Element,
12500                                               unsigned ElementKind) {
12501   // Skip a bitcast to 'id' or qualified 'id'.
12502   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12503     if (ICE->getCastKind() == CK_BitCast &&
12504         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12505       Element = ICE->getSubExpr();
12506   }
12507 
12508   QualType ElementType = Element->getType();
12509   ExprResult ElementResult(Element);
12510   if (ElementType->getAs<ObjCObjectPointerType>() &&
12511       S.CheckSingleAssignmentConstraints(TargetElementType,
12512                                          ElementResult,
12513                                          false, false)
12514         != Sema::Compatible) {
12515     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12516         << ElementType << ElementKind << TargetElementType
12517         << Element->getSourceRange();
12518   }
12519 
12520   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12521     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12522   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12523     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12524 }
12525 
12526 /// Check an Objective-C array literal being converted to the given
12527 /// target type.
12528 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12529                                   ObjCArrayLiteral *ArrayLiteral) {
12530   if (!S.NSArrayDecl)
12531     return;
12532 
12533   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12534   if (!TargetObjCPtr)
12535     return;
12536 
12537   if (TargetObjCPtr->isUnspecialized() ||
12538       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12539         != S.NSArrayDecl->getCanonicalDecl())
12540     return;
12541 
12542   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12543   if (TypeArgs.size() != 1)
12544     return;
12545 
12546   QualType TargetElementType = TypeArgs[0];
12547   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12548     checkObjCCollectionLiteralElement(S, TargetElementType,
12549                                       ArrayLiteral->getElement(I),
12550                                       0);
12551   }
12552 }
12553 
12554 /// Check an Objective-C dictionary literal being converted to the given
12555 /// target type.
12556 static void
12557 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12558                            ObjCDictionaryLiteral *DictionaryLiteral) {
12559   if (!S.NSDictionaryDecl)
12560     return;
12561 
12562   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12563   if (!TargetObjCPtr)
12564     return;
12565 
12566   if (TargetObjCPtr->isUnspecialized() ||
12567       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12568         != S.NSDictionaryDecl->getCanonicalDecl())
12569     return;
12570 
12571   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12572   if (TypeArgs.size() != 2)
12573     return;
12574 
12575   QualType TargetKeyType = TypeArgs[0];
12576   QualType TargetObjectType = TypeArgs[1];
12577   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12578     auto Element = DictionaryLiteral->getKeyValueElement(I);
12579     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12580     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12581   }
12582 }
12583 
12584 // Helper function to filter out cases for constant width constant conversion.
12585 // Don't warn on char array initialization or for non-decimal values.
12586 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12587                                           SourceLocation CC) {
12588   // If initializing from a constant, and the constant starts with '0',
12589   // then it is a binary, octal, or hexadecimal.  Allow these constants
12590   // to fill all the bits, even if there is a sign change.
12591   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12592     const char FirstLiteralCharacter =
12593         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12594     if (FirstLiteralCharacter == '0')
12595       return false;
12596   }
12597 
12598   // If the CC location points to a '{', and the type is char, then assume
12599   // assume it is an array initialization.
12600   if (CC.isValid() && T->isCharType()) {
12601     const char FirstContextCharacter =
12602         S.getSourceManager().getCharacterData(CC)[0];
12603     if (FirstContextCharacter == '{')
12604       return false;
12605   }
12606 
12607   return true;
12608 }
12609 
12610 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12611   const auto *IL = dyn_cast<IntegerLiteral>(E);
12612   if (!IL) {
12613     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12614       if (UO->getOpcode() == UO_Minus)
12615         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12616     }
12617   }
12618 
12619   return IL;
12620 }
12621 
12622 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12623   E = E->IgnoreParenImpCasts();
12624   SourceLocation ExprLoc = E->getExprLoc();
12625 
12626   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12627     BinaryOperator::Opcode Opc = BO->getOpcode();
12628     Expr::EvalResult Result;
12629     // Do not diagnose unsigned shifts.
12630     if (Opc == BO_Shl) {
12631       const auto *LHS = getIntegerLiteral(BO->getLHS());
12632       const auto *RHS = getIntegerLiteral(BO->getRHS());
12633       if (LHS && LHS->getValue() == 0)
12634         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12635       else if (!E->isValueDependent() && LHS && RHS &&
12636                RHS->getValue().isNonNegative() &&
12637                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12638         S.Diag(ExprLoc, diag::warn_left_shift_always)
12639             << (Result.Val.getInt() != 0);
12640       else if (E->getType()->isSignedIntegerType())
12641         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12642     }
12643   }
12644 
12645   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12646     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12647     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12648     if (!LHS || !RHS)
12649       return;
12650     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12651         (RHS->getValue() == 0 || RHS->getValue() == 1))
12652       // Do not diagnose common idioms.
12653       return;
12654     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12655       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12656   }
12657 }
12658 
12659 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12660                                     SourceLocation CC,
12661                                     bool *ICContext = nullptr,
12662                                     bool IsListInit = false) {
12663   if (E->isTypeDependent() || E->isValueDependent()) return;
12664 
12665   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12666   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12667   if (Source == Target) return;
12668   if (Target->isDependentType()) return;
12669 
12670   // If the conversion context location is invalid don't complain. We also
12671   // don't want to emit a warning if the issue occurs from the expansion of
12672   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12673   // delay this check as long as possible. Once we detect we are in that
12674   // scenario, we just return.
12675   if (CC.isInvalid())
12676     return;
12677 
12678   if (Source->isAtomicType())
12679     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12680 
12681   // Diagnose implicit casts to bool.
12682   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12683     if (isa<StringLiteral>(E))
12684       // Warn on string literal to bool.  Checks for string literals in logical
12685       // and expressions, for instance, assert(0 && "error here"), are
12686       // prevented by a check in AnalyzeImplicitConversions().
12687       return DiagnoseImpCast(S, E, T, CC,
12688                              diag::warn_impcast_string_literal_to_bool);
12689     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12690         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12691       // This covers the literal expressions that evaluate to Objective-C
12692       // objects.
12693       return DiagnoseImpCast(S, E, T, CC,
12694                              diag::warn_impcast_objective_c_literal_to_bool);
12695     }
12696     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12697       // Warn on pointer to bool conversion that is always true.
12698       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12699                                      SourceRange(CC));
12700     }
12701   }
12702 
12703   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12704   // is a typedef for signed char (macOS), then that constant value has to be 1
12705   // or 0.
12706   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12707     Expr::EvalResult Result;
12708     if (E->EvaluateAsInt(Result, S.getASTContext(),
12709                          Expr::SE_AllowSideEffects)) {
12710       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12711         adornObjCBoolConversionDiagWithTernaryFixit(
12712             S, E,
12713             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12714                 << toString(Result.Val.getInt(), 10));
12715       }
12716       return;
12717     }
12718   }
12719 
12720   // Check implicit casts from Objective-C collection literals to specialized
12721   // collection types, e.g., NSArray<NSString *> *.
12722   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12723     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12724   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12725     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12726 
12727   // Strip vector types.
12728   if (isa<VectorType>(Source)) {
12729     if (Target->isVLSTBuiltinType() &&
12730         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12731                                          QualType(Source, 0)) ||
12732          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12733                                             QualType(Source, 0))))
12734       return;
12735 
12736     if (!isa<VectorType>(Target)) {
12737       if (S.SourceMgr.isInSystemMacro(CC))
12738         return;
12739       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12740     }
12741 
12742     // If the vector cast is cast between two vectors of the same size, it is
12743     // a bitcast, not a conversion.
12744     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12745       return;
12746 
12747     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12748     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12749   }
12750   if (auto VecTy = dyn_cast<VectorType>(Target))
12751     Target = VecTy->getElementType().getTypePtr();
12752 
12753   // Strip complex types.
12754   if (isa<ComplexType>(Source)) {
12755     if (!isa<ComplexType>(Target)) {
12756       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12757         return;
12758 
12759       return DiagnoseImpCast(S, E, T, CC,
12760                              S.getLangOpts().CPlusPlus
12761                                  ? diag::err_impcast_complex_scalar
12762                                  : diag::warn_impcast_complex_scalar);
12763     }
12764 
12765     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12766     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12767   }
12768 
12769   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12770   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12771 
12772   // If the source is floating point...
12773   if (SourceBT && SourceBT->isFloatingPoint()) {
12774     // ...and the target is floating point...
12775     if (TargetBT && TargetBT->isFloatingPoint()) {
12776       // ...then warn if we're dropping FP rank.
12777 
12778       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12779           QualType(SourceBT, 0), QualType(TargetBT, 0));
12780       if (Order > 0) {
12781         // Don't warn about float constants that are precisely
12782         // representable in the target type.
12783         Expr::EvalResult result;
12784         if (E->EvaluateAsRValue(result, S.Context)) {
12785           // Value might be a float, a float vector, or a float complex.
12786           if (IsSameFloatAfterCast(result.Val,
12787                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12788                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12789             return;
12790         }
12791 
12792         if (S.SourceMgr.isInSystemMacro(CC))
12793           return;
12794 
12795         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12796       }
12797       // ... or possibly if we're increasing rank, too
12798       else if (Order < 0) {
12799         if (S.SourceMgr.isInSystemMacro(CC))
12800           return;
12801 
12802         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12803       }
12804       return;
12805     }
12806 
12807     // If the target is integral, always warn.
12808     if (TargetBT && TargetBT->isInteger()) {
12809       if (S.SourceMgr.isInSystemMacro(CC))
12810         return;
12811 
12812       DiagnoseFloatingImpCast(S, E, T, CC);
12813     }
12814 
12815     // Detect the case where a call result is converted from floating-point to
12816     // to bool, and the final argument to the call is converted from bool, to
12817     // discover this typo:
12818     //
12819     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12820     //
12821     // FIXME: This is an incredibly special case; is there some more general
12822     // way to detect this class of misplaced-parentheses bug?
12823     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12824       // Check last argument of function call to see if it is an
12825       // implicit cast from a type matching the type the result
12826       // is being cast to.
12827       CallExpr *CEx = cast<CallExpr>(E);
12828       if (unsigned NumArgs = CEx->getNumArgs()) {
12829         Expr *LastA = CEx->getArg(NumArgs - 1);
12830         Expr *InnerE = LastA->IgnoreParenImpCasts();
12831         if (isa<ImplicitCastExpr>(LastA) &&
12832             InnerE->getType()->isBooleanType()) {
12833           // Warn on this floating-point to bool conversion
12834           DiagnoseImpCast(S, E, T, CC,
12835                           diag::warn_impcast_floating_point_to_bool);
12836         }
12837       }
12838     }
12839     return;
12840   }
12841 
12842   // Valid casts involving fixed point types should be accounted for here.
12843   if (Source->isFixedPointType()) {
12844     if (Target->isUnsaturatedFixedPointType()) {
12845       Expr::EvalResult Result;
12846       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12847                                   S.isConstantEvaluated())) {
12848         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12849         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12850         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12851         if (Value > MaxVal || Value < MinVal) {
12852           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12853                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12854                                     << Value.toString() << T
12855                                     << E->getSourceRange()
12856                                     << clang::SourceRange(CC));
12857           return;
12858         }
12859       }
12860     } else if (Target->isIntegerType()) {
12861       Expr::EvalResult Result;
12862       if (!S.isConstantEvaluated() &&
12863           E->EvaluateAsFixedPoint(Result, S.Context,
12864                                   Expr::SE_AllowSideEffects)) {
12865         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12866 
12867         bool Overflowed;
12868         llvm::APSInt IntResult = FXResult.convertToInt(
12869             S.Context.getIntWidth(T),
12870             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12871 
12872         if (Overflowed) {
12873           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12874                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12875                                     << FXResult.toString() << T
12876                                     << E->getSourceRange()
12877                                     << clang::SourceRange(CC));
12878           return;
12879         }
12880       }
12881     }
12882   } else if (Target->isUnsaturatedFixedPointType()) {
12883     if (Source->isIntegerType()) {
12884       Expr::EvalResult Result;
12885       if (!S.isConstantEvaluated() &&
12886           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12887         llvm::APSInt Value = Result.Val.getInt();
12888 
12889         bool Overflowed;
12890         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12891             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12892 
12893         if (Overflowed) {
12894           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12895                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12896                                     << toString(Value, /*Radix=*/10) << T
12897                                     << E->getSourceRange()
12898                                     << clang::SourceRange(CC));
12899           return;
12900         }
12901       }
12902     }
12903   }
12904 
12905   // If we are casting an integer type to a floating point type without
12906   // initialization-list syntax, we might lose accuracy if the floating
12907   // point type has a narrower significand than the integer type.
12908   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12909       TargetBT->isFloatingType() && !IsListInit) {
12910     // Determine the number of precision bits in the source integer type.
12911     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12912                                         /*Approximate*/ true);
12913     unsigned int SourcePrecision = SourceRange.Width;
12914 
12915     // Determine the number of precision bits in the
12916     // target floating point type.
12917     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12918         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12919 
12920     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12921         SourcePrecision > TargetPrecision) {
12922 
12923       if (Optional<llvm::APSInt> SourceInt =
12924               E->getIntegerConstantExpr(S.Context)) {
12925         // If the source integer is a constant, convert it to the target
12926         // floating point type. Issue a warning if the value changes
12927         // during the whole conversion.
12928         llvm::APFloat TargetFloatValue(
12929             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12930         llvm::APFloat::opStatus ConversionStatus =
12931             TargetFloatValue.convertFromAPInt(
12932                 *SourceInt, SourceBT->isSignedInteger(),
12933                 llvm::APFloat::rmNearestTiesToEven);
12934 
12935         if (ConversionStatus != llvm::APFloat::opOK) {
12936           SmallString<32> PrettySourceValue;
12937           SourceInt->toString(PrettySourceValue, 10);
12938           SmallString<32> PrettyTargetValue;
12939           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12940 
12941           S.DiagRuntimeBehavior(
12942               E->getExprLoc(), E,
12943               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12944                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12945                   << E->getSourceRange() << clang::SourceRange(CC));
12946         }
12947       } else {
12948         // Otherwise, the implicit conversion may lose precision.
12949         DiagnoseImpCast(S, E, T, CC,
12950                         diag::warn_impcast_integer_float_precision);
12951       }
12952     }
12953   }
12954 
12955   DiagnoseNullConversion(S, E, T, CC);
12956 
12957   S.DiscardMisalignedMemberAddress(Target, E);
12958 
12959   if (Target->isBooleanType())
12960     DiagnoseIntInBoolContext(S, E);
12961 
12962   if (!Source->isIntegerType() || !Target->isIntegerType())
12963     return;
12964 
12965   // TODO: remove this early return once the false positives for constant->bool
12966   // in templates, macros, etc, are reduced or removed.
12967   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12968     return;
12969 
12970   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12971       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12972     return adornObjCBoolConversionDiagWithTernaryFixit(
12973         S, E,
12974         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12975             << E->getType());
12976   }
12977 
12978   IntRange SourceTypeRange =
12979       IntRange::forTargetOfCanonicalType(S.Context, Source);
12980   IntRange LikelySourceRange =
12981       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12982   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12983 
12984   if (LikelySourceRange.Width > TargetRange.Width) {
12985     // If the source is a constant, use a default-on diagnostic.
12986     // TODO: this should happen for bitfield stores, too.
12987     Expr::EvalResult Result;
12988     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12989                          S.isConstantEvaluated())) {
12990       llvm::APSInt Value(32);
12991       Value = Result.Val.getInt();
12992 
12993       if (S.SourceMgr.isInSystemMacro(CC))
12994         return;
12995 
12996       std::string PrettySourceValue = toString(Value, 10);
12997       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12998 
12999       S.DiagRuntimeBehavior(
13000           E->getExprLoc(), E,
13001           S.PDiag(diag::warn_impcast_integer_precision_constant)
13002               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13003               << E->getSourceRange() << SourceRange(CC));
13004       return;
13005     }
13006 
13007     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13008     if (S.SourceMgr.isInSystemMacro(CC))
13009       return;
13010 
13011     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13012       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13013                              /* pruneControlFlow */ true);
13014     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13015   }
13016 
13017   if (TargetRange.Width > SourceTypeRange.Width) {
13018     if (auto *UO = dyn_cast<UnaryOperator>(E))
13019       if (UO->getOpcode() == UO_Minus)
13020         if (Source->isUnsignedIntegerType()) {
13021           if (Target->isUnsignedIntegerType())
13022             return DiagnoseImpCast(S, E, T, CC,
13023                                    diag::warn_impcast_high_order_zero_bits);
13024           if (Target->isSignedIntegerType())
13025             return DiagnoseImpCast(S, E, T, CC,
13026                                    diag::warn_impcast_nonnegative_result);
13027         }
13028   }
13029 
13030   if (TargetRange.Width == LikelySourceRange.Width &&
13031       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13032       Source->isSignedIntegerType()) {
13033     // Warn when doing a signed to signed conversion, warn if the positive
13034     // source value is exactly the width of the target type, which will
13035     // cause a negative value to be stored.
13036 
13037     Expr::EvalResult Result;
13038     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13039         !S.SourceMgr.isInSystemMacro(CC)) {
13040       llvm::APSInt Value = Result.Val.getInt();
13041       if (isSameWidthConstantConversion(S, E, T, CC)) {
13042         std::string PrettySourceValue = toString(Value, 10);
13043         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13044 
13045         S.DiagRuntimeBehavior(
13046             E->getExprLoc(), E,
13047             S.PDiag(diag::warn_impcast_integer_precision_constant)
13048                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13049                 << E->getSourceRange() << SourceRange(CC));
13050         return;
13051       }
13052     }
13053 
13054     // Fall through for non-constants to give a sign conversion warning.
13055   }
13056 
13057   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13058       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13059        LikelySourceRange.Width == TargetRange.Width)) {
13060     if (S.SourceMgr.isInSystemMacro(CC))
13061       return;
13062 
13063     unsigned DiagID = diag::warn_impcast_integer_sign;
13064 
13065     // Traditionally, gcc has warned about this under -Wsign-compare.
13066     // We also want to warn about it in -Wconversion.
13067     // So if -Wconversion is off, use a completely identical diagnostic
13068     // in the sign-compare group.
13069     // The conditional-checking code will
13070     if (ICContext) {
13071       DiagID = diag::warn_impcast_integer_sign_conditional;
13072       *ICContext = true;
13073     }
13074 
13075     return DiagnoseImpCast(S, E, T, CC, DiagID);
13076   }
13077 
13078   // Diagnose conversions between different enumeration types.
13079   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13080   // type, to give us better diagnostics.
13081   QualType SourceType = E->getType();
13082   if (!S.getLangOpts().CPlusPlus) {
13083     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13084       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13085         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13086         SourceType = S.Context.getTypeDeclType(Enum);
13087         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13088       }
13089   }
13090 
13091   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13092     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13093       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13094           TargetEnum->getDecl()->hasNameForLinkage() &&
13095           SourceEnum != TargetEnum) {
13096         if (S.SourceMgr.isInSystemMacro(CC))
13097           return;
13098 
13099         return DiagnoseImpCast(S, E, SourceType, T, CC,
13100                                diag::warn_impcast_different_enum_types);
13101       }
13102 }
13103 
13104 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13105                                      SourceLocation CC, QualType T);
13106 
13107 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13108                                     SourceLocation CC, bool &ICContext) {
13109   E = E->IgnoreParenImpCasts();
13110 
13111   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13112     return CheckConditionalOperator(S, CO, CC, T);
13113 
13114   AnalyzeImplicitConversions(S, E, CC);
13115   if (E->getType() != T)
13116     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13117 }
13118 
13119 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13120                                      SourceLocation CC, QualType T) {
13121   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13122 
13123   Expr *TrueExpr = E->getTrueExpr();
13124   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13125     TrueExpr = BCO->getCommon();
13126 
13127   bool Suspicious = false;
13128   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13129   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13130 
13131   if (T->isBooleanType())
13132     DiagnoseIntInBoolContext(S, E);
13133 
13134   // If -Wconversion would have warned about either of the candidates
13135   // for a signedness conversion to the context type...
13136   if (!Suspicious) return;
13137 
13138   // ...but it's currently ignored...
13139   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13140     return;
13141 
13142   // ...then check whether it would have warned about either of the
13143   // candidates for a signedness conversion to the condition type.
13144   if (E->getType() == T) return;
13145 
13146   Suspicious = false;
13147   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13148                           E->getType(), CC, &Suspicious);
13149   if (!Suspicious)
13150     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13151                             E->getType(), CC, &Suspicious);
13152 }
13153 
13154 /// Check conversion of given expression to boolean.
13155 /// Input argument E is a logical expression.
13156 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13157   if (S.getLangOpts().Bool)
13158     return;
13159   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13160     return;
13161   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13162 }
13163 
13164 namespace {
13165 struct AnalyzeImplicitConversionsWorkItem {
13166   Expr *E;
13167   SourceLocation CC;
13168   bool IsListInit;
13169 };
13170 }
13171 
13172 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13173 /// that should be visited are added to WorkList.
13174 static void AnalyzeImplicitConversions(
13175     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13176     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13177   Expr *OrigE = Item.E;
13178   SourceLocation CC = Item.CC;
13179 
13180   QualType T = OrigE->getType();
13181   Expr *E = OrigE->IgnoreParenImpCasts();
13182 
13183   // Propagate whether we are in a C++ list initialization expression.
13184   // If so, we do not issue warnings for implicit int-float conversion
13185   // precision loss, because C++11 narrowing already handles it.
13186   bool IsListInit = Item.IsListInit ||
13187                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13188 
13189   if (E->isTypeDependent() || E->isValueDependent())
13190     return;
13191 
13192   Expr *SourceExpr = E;
13193   // Examine, but don't traverse into the source expression of an
13194   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13195   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13196   // evaluate it in the context of checking the specific conversion to T though.
13197   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13198     if (auto *Src = OVE->getSourceExpr())
13199       SourceExpr = Src;
13200 
13201   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13202     if (UO->getOpcode() == UO_Not &&
13203         UO->getSubExpr()->isKnownToHaveBooleanValue())
13204       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13205           << OrigE->getSourceRange() << T->isBooleanType()
13206           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13207 
13208   // For conditional operators, we analyze the arguments as if they
13209   // were being fed directly into the output.
13210   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13211     CheckConditionalOperator(S, CO, CC, T);
13212     return;
13213   }
13214 
13215   // Check implicit argument conversions for function calls.
13216   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13217     CheckImplicitArgumentConversions(S, Call, CC);
13218 
13219   // Go ahead and check any implicit conversions we might have skipped.
13220   // The non-canonical typecheck is just an optimization;
13221   // CheckImplicitConversion will filter out dead implicit conversions.
13222   if (SourceExpr->getType() != T)
13223     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13224 
13225   // Now continue drilling into this expression.
13226 
13227   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13228     // The bound subexpressions in a PseudoObjectExpr are not reachable
13229     // as transitive children.
13230     // FIXME: Use a more uniform representation for this.
13231     for (auto *SE : POE->semantics())
13232       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13233         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13234   }
13235 
13236   // Skip past explicit casts.
13237   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13238     E = CE->getSubExpr()->IgnoreParenImpCasts();
13239     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13240       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13241     WorkList.push_back({E, CC, IsListInit});
13242     return;
13243   }
13244 
13245   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13246     // Do a somewhat different check with comparison operators.
13247     if (BO->isComparisonOp())
13248       return AnalyzeComparison(S, BO);
13249 
13250     // And with simple assignments.
13251     if (BO->getOpcode() == BO_Assign)
13252       return AnalyzeAssignment(S, BO);
13253     // And with compound assignments.
13254     if (BO->isAssignmentOp())
13255       return AnalyzeCompoundAssignment(S, BO);
13256   }
13257 
13258   // These break the otherwise-useful invariant below.  Fortunately,
13259   // we don't really need to recurse into them, because any internal
13260   // expressions should have been analyzed already when they were
13261   // built into statements.
13262   if (isa<StmtExpr>(E)) return;
13263 
13264   // Don't descend into unevaluated contexts.
13265   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13266 
13267   // Now just recurse over the expression's children.
13268   CC = E->getExprLoc();
13269   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13270   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13271   for (Stmt *SubStmt : E->children()) {
13272     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13273     if (!ChildExpr)
13274       continue;
13275 
13276     if (IsLogicalAndOperator &&
13277         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13278       // Ignore checking string literals that are in logical and operators.
13279       // This is a common pattern for asserts.
13280       continue;
13281     WorkList.push_back({ChildExpr, CC, IsListInit});
13282   }
13283 
13284   if (BO && BO->isLogicalOp()) {
13285     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13286     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13287       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13288 
13289     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13290     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13291       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13292   }
13293 
13294   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13295     if (U->getOpcode() == UO_LNot) {
13296       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13297     } else if (U->getOpcode() != UO_AddrOf) {
13298       if (U->getSubExpr()->getType()->isAtomicType())
13299         S.Diag(U->getSubExpr()->getBeginLoc(),
13300                diag::warn_atomic_implicit_seq_cst);
13301     }
13302   }
13303 }
13304 
13305 /// AnalyzeImplicitConversions - Find and report any interesting
13306 /// implicit conversions in the given expression.  There are a couple
13307 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13308 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13309                                        bool IsListInit/*= false*/) {
13310   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13311   WorkList.push_back({OrigE, CC, IsListInit});
13312   while (!WorkList.empty())
13313     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13314 }
13315 
13316 /// Diagnose integer type and any valid implicit conversion to it.
13317 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13318   // Taking into account implicit conversions,
13319   // allow any integer.
13320   if (!E->getType()->isIntegerType()) {
13321     S.Diag(E->getBeginLoc(),
13322            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13323     return true;
13324   }
13325   // Potentially emit standard warnings for implicit conversions if enabled
13326   // using -Wconversion.
13327   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13328   return false;
13329 }
13330 
13331 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13332 // Returns true when emitting a warning about taking the address of a reference.
13333 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13334                               const PartialDiagnostic &PD) {
13335   E = E->IgnoreParenImpCasts();
13336 
13337   const FunctionDecl *FD = nullptr;
13338 
13339   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13340     if (!DRE->getDecl()->getType()->isReferenceType())
13341       return false;
13342   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13343     if (!M->getMemberDecl()->getType()->isReferenceType())
13344       return false;
13345   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13346     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13347       return false;
13348     FD = Call->getDirectCallee();
13349   } else {
13350     return false;
13351   }
13352 
13353   SemaRef.Diag(E->getExprLoc(), PD);
13354 
13355   // If possible, point to location of function.
13356   if (FD) {
13357     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13358   }
13359 
13360   return true;
13361 }
13362 
13363 // Returns true if the SourceLocation is expanded from any macro body.
13364 // Returns false if the SourceLocation is invalid, is from not in a macro
13365 // expansion, or is from expanded from a top-level macro argument.
13366 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13367   if (Loc.isInvalid())
13368     return false;
13369 
13370   while (Loc.isMacroID()) {
13371     if (SM.isMacroBodyExpansion(Loc))
13372       return true;
13373     Loc = SM.getImmediateMacroCallerLoc(Loc);
13374   }
13375 
13376   return false;
13377 }
13378 
13379 /// Diagnose pointers that are always non-null.
13380 /// \param E the expression containing the pointer
13381 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13382 /// compared to a null pointer
13383 /// \param IsEqual True when the comparison is equal to a null pointer
13384 /// \param Range Extra SourceRange to highlight in the diagnostic
13385 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13386                                         Expr::NullPointerConstantKind NullKind,
13387                                         bool IsEqual, SourceRange Range) {
13388   if (!E)
13389     return;
13390 
13391   // Don't warn inside macros.
13392   if (E->getExprLoc().isMacroID()) {
13393     const SourceManager &SM = getSourceManager();
13394     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13395         IsInAnyMacroBody(SM, Range.getBegin()))
13396       return;
13397   }
13398   E = E->IgnoreImpCasts();
13399 
13400   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13401 
13402   if (isa<CXXThisExpr>(E)) {
13403     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13404                                 : diag::warn_this_bool_conversion;
13405     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13406     return;
13407   }
13408 
13409   bool IsAddressOf = false;
13410 
13411   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13412     if (UO->getOpcode() != UO_AddrOf)
13413       return;
13414     IsAddressOf = true;
13415     E = UO->getSubExpr();
13416   }
13417 
13418   if (IsAddressOf) {
13419     unsigned DiagID = IsCompare
13420                           ? diag::warn_address_of_reference_null_compare
13421                           : diag::warn_address_of_reference_bool_conversion;
13422     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13423                                          << IsEqual;
13424     if (CheckForReference(*this, E, PD)) {
13425       return;
13426     }
13427   }
13428 
13429   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13430     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13431     std::string Str;
13432     llvm::raw_string_ostream S(Str);
13433     E->printPretty(S, nullptr, getPrintingPolicy());
13434     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13435                                 : diag::warn_cast_nonnull_to_bool;
13436     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13437       << E->getSourceRange() << Range << IsEqual;
13438     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13439   };
13440 
13441   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13442   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13443     if (auto *Callee = Call->getDirectCallee()) {
13444       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13445         ComplainAboutNonnullParamOrCall(A);
13446         return;
13447       }
13448     }
13449   }
13450 
13451   // Expect to find a single Decl.  Skip anything more complicated.
13452   ValueDecl *D = nullptr;
13453   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13454     D = R->getDecl();
13455   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13456     D = M->getMemberDecl();
13457   }
13458 
13459   // Weak Decls can be null.
13460   if (!D || D->isWeak())
13461     return;
13462 
13463   // Check for parameter decl with nonnull attribute
13464   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13465     if (getCurFunction() &&
13466         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13467       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13468         ComplainAboutNonnullParamOrCall(A);
13469         return;
13470       }
13471 
13472       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13473         // Skip function template not specialized yet.
13474         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13475           return;
13476         auto ParamIter = llvm::find(FD->parameters(), PV);
13477         assert(ParamIter != FD->param_end());
13478         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13479 
13480         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13481           if (!NonNull->args_size()) {
13482               ComplainAboutNonnullParamOrCall(NonNull);
13483               return;
13484           }
13485 
13486           for (const ParamIdx &ArgNo : NonNull->args()) {
13487             if (ArgNo.getASTIndex() == ParamNo) {
13488               ComplainAboutNonnullParamOrCall(NonNull);
13489               return;
13490             }
13491           }
13492         }
13493       }
13494     }
13495   }
13496 
13497   QualType T = D->getType();
13498   const bool IsArray = T->isArrayType();
13499   const bool IsFunction = T->isFunctionType();
13500 
13501   // Address of function is used to silence the function warning.
13502   if (IsAddressOf && IsFunction) {
13503     return;
13504   }
13505 
13506   // Found nothing.
13507   if (!IsAddressOf && !IsFunction && !IsArray)
13508     return;
13509 
13510   // Pretty print the expression for the diagnostic.
13511   std::string Str;
13512   llvm::raw_string_ostream S(Str);
13513   E->printPretty(S, nullptr, getPrintingPolicy());
13514 
13515   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13516                               : diag::warn_impcast_pointer_to_bool;
13517   enum {
13518     AddressOf,
13519     FunctionPointer,
13520     ArrayPointer
13521   } DiagType;
13522   if (IsAddressOf)
13523     DiagType = AddressOf;
13524   else if (IsFunction)
13525     DiagType = FunctionPointer;
13526   else if (IsArray)
13527     DiagType = ArrayPointer;
13528   else
13529     llvm_unreachable("Could not determine diagnostic.");
13530   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13531                                 << Range << IsEqual;
13532 
13533   if (!IsFunction)
13534     return;
13535 
13536   // Suggest '&' to silence the function warning.
13537   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13538       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13539 
13540   // Check to see if '()' fixit should be emitted.
13541   QualType ReturnType;
13542   UnresolvedSet<4> NonTemplateOverloads;
13543   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13544   if (ReturnType.isNull())
13545     return;
13546 
13547   if (IsCompare) {
13548     // There are two cases here.  If there is null constant, the only suggest
13549     // for a pointer return type.  If the null is 0, then suggest if the return
13550     // type is a pointer or an integer type.
13551     if (!ReturnType->isPointerType()) {
13552       if (NullKind == Expr::NPCK_ZeroExpression ||
13553           NullKind == Expr::NPCK_ZeroLiteral) {
13554         if (!ReturnType->isIntegerType())
13555           return;
13556       } else {
13557         return;
13558       }
13559     }
13560   } else { // !IsCompare
13561     // For function to bool, only suggest if the function pointer has bool
13562     // return type.
13563     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13564       return;
13565   }
13566   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13567       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13568 }
13569 
13570 /// Diagnoses "dangerous" implicit conversions within the given
13571 /// expression (which is a full expression).  Implements -Wconversion
13572 /// and -Wsign-compare.
13573 ///
13574 /// \param CC the "context" location of the implicit conversion, i.e.
13575 ///   the most location of the syntactic entity requiring the implicit
13576 ///   conversion
13577 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13578   // Don't diagnose in unevaluated contexts.
13579   if (isUnevaluatedContext())
13580     return;
13581 
13582   // Don't diagnose for value- or type-dependent expressions.
13583   if (E->isTypeDependent() || E->isValueDependent())
13584     return;
13585 
13586   // Check for array bounds violations in cases where the check isn't triggered
13587   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13588   // ArraySubscriptExpr is on the RHS of a variable initialization.
13589   CheckArrayAccess(E);
13590 
13591   // This is not the right CC for (e.g.) a variable initialization.
13592   AnalyzeImplicitConversions(*this, E, CC);
13593 }
13594 
13595 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13596 /// Input argument E is a logical expression.
13597 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13598   ::CheckBoolLikeConversion(*this, E, CC);
13599 }
13600 
13601 /// Diagnose when expression is an integer constant expression and its evaluation
13602 /// results in integer overflow
13603 void Sema::CheckForIntOverflow (Expr *E) {
13604   // Use a work list to deal with nested struct initializers.
13605   SmallVector<Expr *, 2> Exprs(1, E);
13606 
13607   do {
13608     Expr *OriginalE = Exprs.pop_back_val();
13609     Expr *E = OriginalE->IgnoreParenCasts();
13610 
13611     if (isa<BinaryOperator>(E)) {
13612       E->EvaluateForOverflow(Context);
13613       continue;
13614     }
13615 
13616     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13617       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13618     else if (isa<ObjCBoxedExpr>(OriginalE))
13619       E->EvaluateForOverflow(Context);
13620     else if (auto Call = dyn_cast<CallExpr>(E))
13621       Exprs.append(Call->arg_begin(), Call->arg_end());
13622     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13623       Exprs.append(Message->arg_begin(), Message->arg_end());
13624   } while (!Exprs.empty());
13625 }
13626 
13627 namespace {
13628 
13629 /// Visitor for expressions which looks for unsequenced operations on the
13630 /// same object.
13631 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13632   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13633 
13634   /// A tree of sequenced regions within an expression. Two regions are
13635   /// unsequenced if one is an ancestor or a descendent of the other. When we
13636   /// finish processing an expression with sequencing, such as a comma
13637   /// expression, we fold its tree nodes into its parent, since they are
13638   /// unsequenced with respect to nodes we will visit later.
13639   class SequenceTree {
13640     struct Value {
13641       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13642       unsigned Parent : 31;
13643       unsigned Merged : 1;
13644     };
13645     SmallVector<Value, 8> Values;
13646 
13647   public:
13648     /// A region within an expression which may be sequenced with respect
13649     /// to some other region.
13650     class Seq {
13651       friend class SequenceTree;
13652 
13653       unsigned Index;
13654 
13655       explicit Seq(unsigned N) : Index(N) {}
13656 
13657     public:
13658       Seq() : Index(0) {}
13659     };
13660 
13661     SequenceTree() { Values.push_back(Value(0)); }
13662     Seq root() const { return Seq(0); }
13663 
13664     /// Create a new sequence of operations, which is an unsequenced
13665     /// subset of \p Parent. This sequence of operations is sequenced with
13666     /// respect to other children of \p Parent.
13667     Seq allocate(Seq Parent) {
13668       Values.push_back(Value(Parent.Index));
13669       return Seq(Values.size() - 1);
13670     }
13671 
13672     /// Merge a sequence of operations into its parent.
13673     void merge(Seq S) {
13674       Values[S.Index].Merged = true;
13675     }
13676 
13677     /// Determine whether two operations are unsequenced. This operation
13678     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13679     /// should have been merged into its parent as appropriate.
13680     bool isUnsequenced(Seq Cur, Seq Old) {
13681       unsigned C = representative(Cur.Index);
13682       unsigned Target = representative(Old.Index);
13683       while (C >= Target) {
13684         if (C == Target)
13685           return true;
13686         C = Values[C].Parent;
13687       }
13688       return false;
13689     }
13690 
13691   private:
13692     /// Pick a representative for a sequence.
13693     unsigned representative(unsigned K) {
13694       if (Values[K].Merged)
13695         // Perform path compression as we go.
13696         return Values[K].Parent = representative(Values[K].Parent);
13697       return K;
13698     }
13699   };
13700 
13701   /// An object for which we can track unsequenced uses.
13702   using Object = const NamedDecl *;
13703 
13704   /// Different flavors of object usage which we track. We only track the
13705   /// least-sequenced usage of each kind.
13706   enum UsageKind {
13707     /// A read of an object. Multiple unsequenced reads are OK.
13708     UK_Use,
13709 
13710     /// A modification of an object which is sequenced before the value
13711     /// computation of the expression, such as ++n in C++.
13712     UK_ModAsValue,
13713 
13714     /// A modification of an object which is not sequenced before the value
13715     /// computation of the expression, such as n++.
13716     UK_ModAsSideEffect,
13717 
13718     UK_Count = UK_ModAsSideEffect + 1
13719   };
13720 
13721   /// Bundle together a sequencing region and the expression corresponding
13722   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13723   struct Usage {
13724     const Expr *UsageExpr;
13725     SequenceTree::Seq Seq;
13726 
13727     Usage() : UsageExpr(nullptr), Seq() {}
13728   };
13729 
13730   struct UsageInfo {
13731     Usage Uses[UK_Count];
13732 
13733     /// Have we issued a diagnostic for this object already?
13734     bool Diagnosed;
13735 
13736     UsageInfo() : Uses(), Diagnosed(false) {}
13737   };
13738   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13739 
13740   Sema &SemaRef;
13741 
13742   /// Sequenced regions within the expression.
13743   SequenceTree Tree;
13744 
13745   /// Declaration modifications and references which we have seen.
13746   UsageInfoMap UsageMap;
13747 
13748   /// The region we are currently within.
13749   SequenceTree::Seq Region;
13750 
13751   /// Filled in with declarations which were modified as a side-effect
13752   /// (that is, post-increment operations).
13753   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13754 
13755   /// Expressions to check later. We defer checking these to reduce
13756   /// stack usage.
13757   SmallVectorImpl<const Expr *> &WorkList;
13758 
13759   /// RAII object wrapping the visitation of a sequenced subexpression of an
13760   /// expression. At the end of this process, the side-effects of the evaluation
13761   /// become sequenced with respect to the value computation of the result, so
13762   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13763   /// UK_ModAsValue.
13764   struct SequencedSubexpression {
13765     SequencedSubexpression(SequenceChecker &Self)
13766       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13767       Self.ModAsSideEffect = &ModAsSideEffect;
13768     }
13769 
13770     ~SequencedSubexpression() {
13771       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13772         // Add a new usage with usage kind UK_ModAsValue, and then restore
13773         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13774         // the previous one was empty).
13775         UsageInfo &UI = Self.UsageMap[M.first];
13776         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13777         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13778         SideEffectUsage = M.second;
13779       }
13780       Self.ModAsSideEffect = OldModAsSideEffect;
13781     }
13782 
13783     SequenceChecker &Self;
13784     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13785     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13786   };
13787 
13788   /// RAII object wrapping the visitation of a subexpression which we might
13789   /// choose to evaluate as a constant. If any subexpression is evaluated and
13790   /// found to be non-constant, this allows us to suppress the evaluation of
13791   /// the outer expression.
13792   class EvaluationTracker {
13793   public:
13794     EvaluationTracker(SequenceChecker &Self)
13795         : Self(Self), Prev(Self.EvalTracker) {
13796       Self.EvalTracker = this;
13797     }
13798 
13799     ~EvaluationTracker() {
13800       Self.EvalTracker = Prev;
13801       if (Prev)
13802         Prev->EvalOK &= EvalOK;
13803     }
13804 
13805     bool evaluate(const Expr *E, bool &Result) {
13806       if (!EvalOK || E->isValueDependent())
13807         return false;
13808       EvalOK = E->EvaluateAsBooleanCondition(
13809           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13810       return EvalOK;
13811     }
13812 
13813   private:
13814     SequenceChecker &Self;
13815     EvaluationTracker *Prev;
13816     bool EvalOK = true;
13817   } *EvalTracker = nullptr;
13818 
13819   /// Find the object which is produced by the specified expression,
13820   /// if any.
13821   Object getObject(const Expr *E, bool Mod) const {
13822     E = E->IgnoreParenCasts();
13823     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13824       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13825         return getObject(UO->getSubExpr(), Mod);
13826     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13827       if (BO->getOpcode() == BO_Comma)
13828         return getObject(BO->getRHS(), Mod);
13829       if (Mod && BO->isAssignmentOp())
13830         return getObject(BO->getLHS(), Mod);
13831     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13832       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13833       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13834         return ME->getMemberDecl();
13835     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13836       // FIXME: If this is a reference, map through to its value.
13837       return DRE->getDecl();
13838     return nullptr;
13839   }
13840 
13841   /// Note that an object \p O was modified or used by an expression
13842   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13843   /// the object \p O as obtained via the \p UsageMap.
13844   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13845     // Get the old usage for the given object and usage kind.
13846     Usage &U = UI.Uses[UK];
13847     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13848       // If we have a modification as side effect and are in a sequenced
13849       // subexpression, save the old Usage so that we can restore it later
13850       // in SequencedSubexpression::~SequencedSubexpression.
13851       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13852         ModAsSideEffect->push_back(std::make_pair(O, U));
13853       // Then record the new usage with the current sequencing region.
13854       U.UsageExpr = UsageExpr;
13855       U.Seq = Region;
13856     }
13857   }
13858 
13859   /// Check whether a modification or use of an object \p O in an expression
13860   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13861   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13862   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13863   /// usage and false we are checking for a mod-use unsequenced usage.
13864   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13865                   UsageKind OtherKind, bool IsModMod) {
13866     if (UI.Diagnosed)
13867       return;
13868 
13869     const Usage &U = UI.Uses[OtherKind];
13870     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13871       return;
13872 
13873     const Expr *Mod = U.UsageExpr;
13874     const Expr *ModOrUse = UsageExpr;
13875     if (OtherKind == UK_Use)
13876       std::swap(Mod, ModOrUse);
13877 
13878     SemaRef.DiagRuntimeBehavior(
13879         Mod->getExprLoc(), {Mod, ModOrUse},
13880         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13881                                : diag::warn_unsequenced_mod_use)
13882             << O << SourceRange(ModOrUse->getExprLoc()));
13883     UI.Diagnosed = true;
13884   }
13885 
13886   // A note on note{Pre, Post}{Use, Mod}:
13887   //
13888   // (It helps to follow the algorithm with an expression such as
13889   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13890   //  operations before C++17 and both are well-defined in C++17).
13891   //
13892   // When visiting a node which uses/modify an object we first call notePreUse
13893   // or notePreMod before visiting its sub-expression(s). At this point the
13894   // children of the current node have not yet been visited and so the eventual
13895   // uses/modifications resulting from the children of the current node have not
13896   // been recorded yet.
13897   //
13898   // We then visit the children of the current node. After that notePostUse or
13899   // notePostMod is called. These will 1) detect an unsequenced modification
13900   // as side effect (as in "k++ + k") and 2) add a new usage with the
13901   // appropriate usage kind.
13902   //
13903   // We also have to be careful that some operation sequences modification as
13904   // side effect as well (for example: || or ,). To account for this we wrap
13905   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13906   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13907   // which record usages which are modifications as side effect, and then
13908   // downgrade them (or more accurately restore the previous usage which was a
13909   // modification as side effect) when exiting the scope of the sequenced
13910   // subexpression.
13911 
13912   void notePreUse(Object O, const Expr *UseExpr) {
13913     UsageInfo &UI = UsageMap[O];
13914     // Uses conflict with other modifications.
13915     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13916   }
13917 
13918   void notePostUse(Object O, const Expr *UseExpr) {
13919     UsageInfo &UI = UsageMap[O];
13920     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13921                /*IsModMod=*/false);
13922     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13923   }
13924 
13925   void notePreMod(Object O, const Expr *ModExpr) {
13926     UsageInfo &UI = UsageMap[O];
13927     // Modifications conflict with other modifications and with uses.
13928     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13929     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13930   }
13931 
13932   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13933     UsageInfo &UI = UsageMap[O];
13934     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13935                /*IsModMod=*/true);
13936     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13937   }
13938 
13939 public:
13940   SequenceChecker(Sema &S, const Expr *E,
13941                   SmallVectorImpl<const Expr *> &WorkList)
13942       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13943     Visit(E);
13944     // Silence a -Wunused-private-field since WorkList is now unused.
13945     // TODO: Evaluate if it can be used, and if not remove it.
13946     (void)this->WorkList;
13947   }
13948 
13949   void VisitStmt(const Stmt *S) {
13950     // Skip all statements which aren't expressions for now.
13951   }
13952 
13953   void VisitExpr(const Expr *E) {
13954     // By default, just recurse to evaluated subexpressions.
13955     Base::VisitStmt(E);
13956   }
13957 
13958   void VisitCastExpr(const CastExpr *E) {
13959     Object O = Object();
13960     if (E->getCastKind() == CK_LValueToRValue)
13961       O = getObject(E->getSubExpr(), false);
13962 
13963     if (O)
13964       notePreUse(O, E);
13965     VisitExpr(E);
13966     if (O)
13967       notePostUse(O, E);
13968   }
13969 
13970   void VisitSequencedExpressions(const Expr *SequencedBefore,
13971                                  const Expr *SequencedAfter) {
13972     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13973     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13974     SequenceTree::Seq OldRegion = Region;
13975 
13976     {
13977       SequencedSubexpression SeqBefore(*this);
13978       Region = BeforeRegion;
13979       Visit(SequencedBefore);
13980     }
13981 
13982     Region = AfterRegion;
13983     Visit(SequencedAfter);
13984 
13985     Region = OldRegion;
13986 
13987     Tree.merge(BeforeRegion);
13988     Tree.merge(AfterRegion);
13989   }
13990 
13991   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13992     // C++17 [expr.sub]p1:
13993     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13994     //   expression E1 is sequenced before the expression E2.
13995     if (SemaRef.getLangOpts().CPlusPlus17)
13996       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13997     else {
13998       Visit(ASE->getLHS());
13999       Visit(ASE->getRHS());
14000     }
14001   }
14002 
14003   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14004   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14005   void VisitBinPtrMem(const BinaryOperator *BO) {
14006     // C++17 [expr.mptr.oper]p4:
14007     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14008     //  the expression E1 is sequenced before the expression E2.
14009     if (SemaRef.getLangOpts().CPlusPlus17)
14010       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14011     else {
14012       Visit(BO->getLHS());
14013       Visit(BO->getRHS());
14014     }
14015   }
14016 
14017   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14018   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14019   void VisitBinShlShr(const BinaryOperator *BO) {
14020     // C++17 [expr.shift]p4:
14021     //  The expression E1 is sequenced before the expression E2.
14022     if (SemaRef.getLangOpts().CPlusPlus17)
14023       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14024     else {
14025       Visit(BO->getLHS());
14026       Visit(BO->getRHS());
14027     }
14028   }
14029 
14030   void VisitBinComma(const BinaryOperator *BO) {
14031     // C++11 [expr.comma]p1:
14032     //   Every value computation and side effect associated with the left
14033     //   expression is sequenced before every value computation and side
14034     //   effect associated with the right expression.
14035     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14036   }
14037 
14038   void VisitBinAssign(const BinaryOperator *BO) {
14039     SequenceTree::Seq RHSRegion;
14040     SequenceTree::Seq LHSRegion;
14041     if (SemaRef.getLangOpts().CPlusPlus17) {
14042       RHSRegion = Tree.allocate(Region);
14043       LHSRegion = Tree.allocate(Region);
14044     } else {
14045       RHSRegion = Region;
14046       LHSRegion = Region;
14047     }
14048     SequenceTree::Seq OldRegion = Region;
14049 
14050     // C++11 [expr.ass]p1:
14051     //  [...] the assignment is sequenced after the value computation
14052     //  of the right and left operands, [...]
14053     //
14054     // so check it before inspecting the operands and update the
14055     // map afterwards.
14056     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14057     if (O)
14058       notePreMod(O, BO);
14059 
14060     if (SemaRef.getLangOpts().CPlusPlus17) {
14061       // C++17 [expr.ass]p1:
14062       //  [...] The right operand is sequenced before the left operand. [...]
14063       {
14064         SequencedSubexpression SeqBefore(*this);
14065         Region = RHSRegion;
14066         Visit(BO->getRHS());
14067       }
14068 
14069       Region = LHSRegion;
14070       Visit(BO->getLHS());
14071 
14072       if (O && isa<CompoundAssignOperator>(BO))
14073         notePostUse(O, BO);
14074 
14075     } else {
14076       // C++11 does not specify any sequencing between the LHS and RHS.
14077       Region = LHSRegion;
14078       Visit(BO->getLHS());
14079 
14080       if (O && isa<CompoundAssignOperator>(BO))
14081         notePostUse(O, BO);
14082 
14083       Region = RHSRegion;
14084       Visit(BO->getRHS());
14085     }
14086 
14087     // C++11 [expr.ass]p1:
14088     //  the assignment is sequenced [...] before the value computation of the
14089     //  assignment expression.
14090     // C11 6.5.16/3 has no such rule.
14091     Region = OldRegion;
14092     if (O)
14093       notePostMod(O, BO,
14094                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14095                                                   : UK_ModAsSideEffect);
14096     if (SemaRef.getLangOpts().CPlusPlus17) {
14097       Tree.merge(RHSRegion);
14098       Tree.merge(LHSRegion);
14099     }
14100   }
14101 
14102   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14103     VisitBinAssign(CAO);
14104   }
14105 
14106   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14107   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14108   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14109     Object O = getObject(UO->getSubExpr(), true);
14110     if (!O)
14111       return VisitExpr(UO);
14112 
14113     notePreMod(O, UO);
14114     Visit(UO->getSubExpr());
14115     // C++11 [expr.pre.incr]p1:
14116     //   the expression ++x is equivalent to x+=1
14117     notePostMod(O, UO,
14118                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14119                                                 : UK_ModAsSideEffect);
14120   }
14121 
14122   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14123   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14124   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14125     Object O = getObject(UO->getSubExpr(), true);
14126     if (!O)
14127       return VisitExpr(UO);
14128 
14129     notePreMod(O, UO);
14130     Visit(UO->getSubExpr());
14131     notePostMod(O, UO, UK_ModAsSideEffect);
14132   }
14133 
14134   void VisitBinLOr(const BinaryOperator *BO) {
14135     // C++11 [expr.log.or]p2:
14136     //  If the second expression is evaluated, every value computation and
14137     //  side effect associated with the first expression is sequenced before
14138     //  every value computation and side effect associated with the
14139     //  second expression.
14140     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14141     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14142     SequenceTree::Seq OldRegion = Region;
14143 
14144     EvaluationTracker Eval(*this);
14145     {
14146       SequencedSubexpression Sequenced(*this);
14147       Region = LHSRegion;
14148       Visit(BO->getLHS());
14149     }
14150 
14151     // C++11 [expr.log.or]p1:
14152     //  [...] the second operand is not evaluated if the first operand
14153     //  evaluates to true.
14154     bool EvalResult = false;
14155     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14156     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14157     if (ShouldVisitRHS) {
14158       Region = RHSRegion;
14159       Visit(BO->getRHS());
14160     }
14161 
14162     Region = OldRegion;
14163     Tree.merge(LHSRegion);
14164     Tree.merge(RHSRegion);
14165   }
14166 
14167   void VisitBinLAnd(const BinaryOperator *BO) {
14168     // C++11 [expr.log.and]p2:
14169     //  If the second expression is evaluated, every value computation and
14170     //  side effect associated with the first expression is sequenced before
14171     //  every value computation and side effect associated with the
14172     //  second expression.
14173     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14174     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14175     SequenceTree::Seq OldRegion = Region;
14176 
14177     EvaluationTracker Eval(*this);
14178     {
14179       SequencedSubexpression Sequenced(*this);
14180       Region = LHSRegion;
14181       Visit(BO->getLHS());
14182     }
14183 
14184     // C++11 [expr.log.and]p1:
14185     //  [...] the second operand is not evaluated if the first operand is false.
14186     bool EvalResult = false;
14187     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14188     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14189     if (ShouldVisitRHS) {
14190       Region = RHSRegion;
14191       Visit(BO->getRHS());
14192     }
14193 
14194     Region = OldRegion;
14195     Tree.merge(LHSRegion);
14196     Tree.merge(RHSRegion);
14197   }
14198 
14199   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14200     // C++11 [expr.cond]p1:
14201     //  [...] Every value computation and side effect associated with the first
14202     //  expression is sequenced before every value computation and side effect
14203     //  associated with the second or third expression.
14204     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14205 
14206     // No sequencing is specified between the true and false expression.
14207     // However since exactly one of both is going to be evaluated we can
14208     // consider them to be sequenced. This is needed to avoid warning on
14209     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14210     // both the true and false expressions because we can't evaluate x.
14211     // This will still allow us to detect an expression like (pre C++17)
14212     // "(x ? y += 1 : y += 2) = y".
14213     //
14214     // We don't wrap the visitation of the true and false expression with
14215     // SequencedSubexpression because we don't want to downgrade modifications
14216     // as side effect in the true and false expressions after the visition
14217     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14218     // not warn between the two "y++", but we should warn between the "y++"
14219     // and the "y".
14220     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14221     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14222     SequenceTree::Seq OldRegion = Region;
14223 
14224     EvaluationTracker Eval(*this);
14225     {
14226       SequencedSubexpression Sequenced(*this);
14227       Region = ConditionRegion;
14228       Visit(CO->getCond());
14229     }
14230 
14231     // C++11 [expr.cond]p1:
14232     // [...] The first expression is contextually converted to bool (Clause 4).
14233     // It is evaluated and if it is true, the result of the conditional
14234     // expression is the value of the second expression, otherwise that of the
14235     // third expression. Only one of the second and third expressions is
14236     // evaluated. [...]
14237     bool EvalResult = false;
14238     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14239     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14240     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14241     if (ShouldVisitTrueExpr) {
14242       Region = TrueRegion;
14243       Visit(CO->getTrueExpr());
14244     }
14245     if (ShouldVisitFalseExpr) {
14246       Region = FalseRegion;
14247       Visit(CO->getFalseExpr());
14248     }
14249 
14250     Region = OldRegion;
14251     Tree.merge(ConditionRegion);
14252     Tree.merge(TrueRegion);
14253     Tree.merge(FalseRegion);
14254   }
14255 
14256   void VisitCallExpr(const CallExpr *CE) {
14257     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14258 
14259     if (CE->isUnevaluatedBuiltinCall(Context))
14260       return;
14261 
14262     // C++11 [intro.execution]p15:
14263     //   When calling a function [...], every value computation and side effect
14264     //   associated with any argument expression, or with the postfix expression
14265     //   designating the called function, is sequenced before execution of every
14266     //   expression or statement in the body of the function [and thus before
14267     //   the value computation of its result].
14268     SequencedSubexpression Sequenced(*this);
14269     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14270       // C++17 [expr.call]p5
14271       //   The postfix-expression is sequenced before each expression in the
14272       //   expression-list and any default argument. [...]
14273       SequenceTree::Seq CalleeRegion;
14274       SequenceTree::Seq OtherRegion;
14275       if (SemaRef.getLangOpts().CPlusPlus17) {
14276         CalleeRegion = Tree.allocate(Region);
14277         OtherRegion = Tree.allocate(Region);
14278       } else {
14279         CalleeRegion = Region;
14280         OtherRegion = Region;
14281       }
14282       SequenceTree::Seq OldRegion = Region;
14283 
14284       // Visit the callee expression first.
14285       Region = CalleeRegion;
14286       if (SemaRef.getLangOpts().CPlusPlus17) {
14287         SequencedSubexpression Sequenced(*this);
14288         Visit(CE->getCallee());
14289       } else {
14290         Visit(CE->getCallee());
14291       }
14292 
14293       // Then visit the argument expressions.
14294       Region = OtherRegion;
14295       for (const Expr *Argument : CE->arguments())
14296         Visit(Argument);
14297 
14298       Region = OldRegion;
14299       if (SemaRef.getLangOpts().CPlusPlus17) {
14300         Tree.merge(CalleeRegion);
14301         Tree.merge(OtherRegion);
14302       }
14303     });
14304   }
14305 
14306   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14307     // C++17 [over.match.oper]p2:
14308     //   [...] the operator notation is first transformed to the equivalent
14309     //   function-call notation as summarized in Table 12 (where @ denotes one
14310     //   of the operators covered in the specified subclause). However, the
14311     //   operands are sequenced in the order prescribed for the built-in
14312     //   operator (Clause 8).
14313     //
14314     // From the above only overloaded binary operators and overloaded call
14315     // operators have sequencing rules in C++17 that we need to handle
14316     // separately.
14317     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14318         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14319       return VisitCallExpr(CXXOCE);
14320 
14321     enum {
14322       NoSequencing,
14323       LHSBeforeRHS,
14324       RHSBeforeLHS,
14325       LHSBeforeRest
14326     } SequencingKind;
14327     switch (CXXOCE->getOperator()) {
14328     case OO_Equal:
14329     case OO_PlusEqual:
14330     case OO_MinusEqual:
14331     case OO_StarEqual:
14332     case OO_SlashEqual:
14333     case OO_PercentEqual:
14334     case OO_CaretEqual:
14335     case OO_AmpEqual:
14336     case OO_PipeEqual:
14337     case OO_LessLessEqual:
14338     case OO_GreaterGreaterEqual:
14339       SequencingKind = RHSBeforeLHS;
14340       break;
14341 
14342     case OO_LessLess:
14343     case OO_GreaterGreater:
14344     case OO_AmpAmp:
14345     case OO_PipePipe:
14346     case OO_Comma:
14347     case OO_ArrowStar:
14348     case OO_Subscript:
14349       SequencingKind = LHSBeforeRHS;
14350       break;
14351 
14352     case OO_Call:
14353       SequencingKind = LHSBeforeRest;
14354       break;
14355 
14356     default:
14357       SequencingKind = NoSequencing;
14358       break;
14359     }
14360 
14361     if (SequencingKind == NoSequencing)
14362       return VisitCallExpr(CXXOCE);
14363 
14364     // This is a call, so all subexpressions are sequenced before the result.
14365     SequencedSubexpression Sequenced(*this);
14366 
14367     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14368       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14369              "Should only get there with C++17 and above!");
14370       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14371              "Should only get there with an overloaded binary operator"
14372              " or an overloaded call operator!");
14373 
14374       if (SequencingKind == LHSBeforeRest) {
14375         assert(CXXOCE->getOperator() == OO_Call &&
14376                "We should only have an overloaded call operator here!");
14377 
14378         // This is very similar to VisitCallExpr, except that we only have the
14379         // C++17 case. The postfix-expression is the first argument of the
14380         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14381         // are in the following arguments.
14382         //
14383         // Note that we intentionally do not visit the callee expression since
14384         // it is just a decayed reference to a function.
14385         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14386         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14387         SequenceTree::Seq OldRegion = Region;
14388 
14389         assert(CXXOCE->getNumArgs() >= 1 &&
14390                "An overloaded call operator must have at least one argument"
14391                " for the postfix-expression!");
14392         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14393         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14394                                           CXXOCE->getNumArgs() - 1);
14395 
14396         // Visit the postfix-expression first.
14397         {
14398           Region = PostfixExprRegion;
14399           SequencedSubexpression Sequenced(*this);
14400           Visit(PostfixExpr);
14401         }
14402 
14403         // Then visit the argument expressions.
14404         Region = ArgsRegion;
14405         for (const Expr *Arg : Args)
14406           Visit(Arg);
14407 
14408         Region = OldRegion;
14409         Tree.merge(PostfixExprRegion);
14410         Tree.merge(ArgsRegion);
14411       } else {
14412         assert(CXXOCE->getNumArgs() == 2 &&
14413                "Should only have two arguments here!");
14414         assert((SequencingKind == LHSBeforeRHS ||
14415                 SequencingKind == RHSBeforeLHS) &&
14416                "Unexpected sequencing kind!");
14417 
14418         // We do not visit the callee expression since it is just a decayed
14419         // reference to a function.
14420         const Expr *E1 = CXXOCE->getArg(0);
14421         const Expr *E2 = CXXOCE->getArg(1);
14422         if (SequencingKind == RHSBeforeLHS)
14423           std::swap(E1, E2);
14424 
14425         return VisitSequencedExpressions(E1, E2);
14426       }
14427     });
14428   }
14429 
14430   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14431     // This is a call, so all subexpressions are sequenced before the result.
14432     SequencedSubexpression Sequenced(*this);
14433 
14434     if (!CCE->isListInitialization())
14435       return VisitExpr(CCE);
14436 
14437     // In C++11, list initializations are sequenced.
14438     SmallVector<SequenceTree::Seq, 32> Elts;
14439     SequenceTree::Seq Parent = Region;
14440     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14441                                               E = CCE->arg_end();
14442          I != E; ++I) {
14443       Region = Tree.allocate(Parent);
14444       Elts.push_back(Region);
14445       Visit(*I);
14446     }
14447 
14448     // Forget that the initializers are sequenced.
14449     Region = Parent;
14450     for (unsigned I = 0; I < Elts.size(); ++I)
14451       Tree.merge(Elts[I]);
14452   }
14453 
14454   void VisitInitListExpr(const InitListExpr *ILE) {
14455     if (!SemaRef.getLangOpts().CPlusPlus11)
14456       return VisitExpr(ILE);
14457 
14458     // In C++11, list initializations are sequenced.
14459     SmallVector<SequenceTree::Seq, 32> Elts;
14460     SequenceTree::Seq Parent = Region;
14461     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14462       const Expr *E = ILE->getInit(I);
14463       if (!E)
14464         continue;
14465       Region = Tree.allocate(Parent);
14466       Elts.push_back(Region);
14467       Visit(E);
14468     }
14469 
14470     // Forget that the initializers are sequenced.
14471     Region = Parent;
14472     for (unsigned I = 0; I < Elts.size(); ++I)
14473       Tree.merge(Elts[I]);
14474   }
14475 };
14476 
14477 } // namespace
14478 
14479 void Sema::CheckUnsequencedOperations(const Expr *E) {
14480   SmallVector<const Expr *, 8> WorkList;
14481   WorkList.push_back(E);
14482   while (!WorkList.empty()) {
14483     const Expr *Item = WorkList.pop_back_val();
14484     SequenceChecker(*this, Item, WorkList);
14485   }
14486 }
14487 
14488 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14489                               bool IsConstexpr) {
14490   llvm::SaveAndRestore<bool> ConstantContext(
14491       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14492   CheckImplicitConversions(E, CheckLoc);
14493   if (!E->isInstantiationDependent())
14494     CheckUnsequencedOperations(E);
14495   if (!IsConstexpr && !E->isValueDependent())
14496     CheckForIntOverflow(E);
14497   DiagnoseMisalignedMembers();
14498 }
14499 
14500 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14501                                        FieldDecl *BitField,
14502                                        Expr *Init) {
14503   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14504 }
14505 
14506 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14507                                          SourceLocation Loc) {
14508   if (!PType->isVariablyModifiedType())
14509     return;
14510   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14511     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14512     return;
14513   }
14514   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14515     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14516     return;
14517   }
14518   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14519     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14520     return;
14521   }
14522 
14523   const ArrayType *AT = S.Context.getAsArrayType(PType);
14524   if (!AT)
14525     return;
14526 
14527   if (AT->getSizeModifier() != ArrayType::Star) {
14528     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14529     return;
14530   }
14531 
14532   S.Diag(Loc, diag::err_array_star_in_function_definition);
14533 }
14534 
14535 /// CheckParmsForFunctionDef - Check that the parameters of the given
14536 /// function are appropriate for the definition of a function. This
14537 /// takes care of any checks that cannot be performed on the
14538 /// declaration itself, e.g., that the types of each of the function
14539 /// parameters are complete.
14540 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14541                                     bool CheckParameterNames) {
14542   bool HasInvalidParm = false;
14543   for (ParmVarDecl *Param : Parameters) {
14544     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14545     // function declarator that is part of a function definition of
14546     // that function shall not have incomplete type.
14547     //
14548     // This is also C++ [dcl.fct]p6.
14549     if (!Param->isInvalidDecl() &&
14550         RequireCompleteType(Param->getLocation(), Param->getType(),
14551                             diag::err_typecheck_decl_incomplete_type)) {
14552       Param->setInvalidDecl();
14553       HasInvalidParm = true;
14554     }
14555 
14556     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14557     // declaration of each parameter shall include an identifier.
14558     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14559         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14560       // Diagnose this as an extension in C17 and earlier.
14561       if (!getLangOpts().C2x)
14562         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14563     }
14564 
14565     // C99 6.7.5.3p12:
14566     //   If the function declarator is not part of a definition of that
14567     //   function, parameters may have incomplete type and may use the [*]
14568     //   notation in their sequences of declarator specifiers to specify
14569     //   variable length array types.
14570     QualType PType = Param->getOriginalType();
14571     // FIXME: This diagnostic should point the '[*]' if source-location
14572     // information is added for it.
14573     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14574 
14575     // If the parameter is a c++ class type and it has to be destructed in the
14576     // callee function, declare the destructor so that it can be called by the
14577     // callee function. Do not perform any direct access check on the dtor here.
14578     if (!Param->isInvalidDecl()) {
14579       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14580         if (!ClassDecl->isInvalidDecl() &&
14581             !ClassDecl->hasIrrelevantDestructor() &&
14582             !ClassDecl->isDependentContext() &&
14583             ClassDecl->isParamDestroyedInCallee()) {
14584           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14585           MarkFunctionReferenced(Param->getLocation(), Destructor);
14586           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14587         }
14588       }
14589     }
14590 
14591     // Parameters with the pass_object_size attribute only need to be marked
14592     // constant at function definitions. Because we lack information about
14593     // whether we're on a declaration or definition when we're instantiating the
14594     // attribute, we need to check for constness here.
14595     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14596       if (!Param->getType().isConstQualified())
14597         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14598             << Attr->getSpelling() << 1;
14599 
14600     // Check for parameter names shadowing fields from the class.
14601     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14602       // The owning context for the parameter should be the function, but we
14603       // want to see if this function's declaration context is a record.
14604       DeclContext *DC = Param->getDeclContext();
14605       if (DC && DC->isFunctionOrMethod()) {
14606         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14607           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14608                                      RD, /*DeclIsField*/ false);
14609       }
14610     }
14611   }
14612 
14613   return HasInvalidParm;
14614 }
14615 
14616 Optional<std::pair<CharUnits, CharUnits>>
14617 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14618 
14619 /// Compute the alignment and offset of the base class object given the
14620 /// derived-to-base cast expression and the alignment and offset of the derived
14621 /// class object.
14622 static std::pair<CharUnits, CharUnits>
14623 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14624                                    CharUnits BaseAlignment, CharUnits Offset,
14625                                    ASTContext &Ctx) {
14626   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14627        ++PathI) {
14628     const CXXBaseSpecifier *Base = *PathI;
14629     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14630     if (Base->isVirtual()) {
14631       // The complete object may have a lower alignment than the non-virtual
14632       // alignment of the base, in which case the base may be misaligned. Choose
14633       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14634       // conservative lower bound of the complete object alignment.
14635       CharUnits NonVirtualAlignment =
14636           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14637       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14638       Offset = CharUnits::Zero();
14639     } else {
14640       const ASTRecordLayout &RL =
14641           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14642       Offset += RL.getBaseClassOffset(BaseDecl);
14643     }
14644     DerivedType = Base->getType();
14645   }
14646 
14647   return std::make_pair(BaseAlignment, Offset);
14648 }
14649 
14650 /// Compute the alignment and offset of a binary additive operator.
14651 static Optional<std::pair<CharUnits, CharUnits>>
14652 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14653                                      bool IsSub, ASTContext &Ctx) {
14654   QualType PointeeType = PtrE->getType()->getPointeeType();
14655 
14656   if (!PointeeType->isConstantSizeType())
14657     return llvm::None;
14658 
14659   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14660 
14661   if (!P)
14662     return llvm::None;
14663 
14664   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14665   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14666     CharUnits Offset = EltSize * IdxRes->getExtValue();
14667     if (IsSub)
14668       Offset = -Offset;
14669     return std::make_pair(P->first, P->second + Offset);
14670   }
14671 
14672   // If the integer expression isn't a constant expression, compute the lower
14673   // bound of the alignment using the alignment and offset of the pointer
14674   // expression and the element size.
14675   return std::make_pair(
14676       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14677       CharUnits::Zero());
14678 }
14679 
14680 /// This helper function takes an lvalue expression and returns the alignment of
14681 /// a VarDecl and a constant offset from the VarDecl.
14682 Optional<std::pair<CharUnits, CharUnits>>
14683 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14684   E = E->IgnoreParens();
14685   switch (E->getStmtClass()) {
14686   default:
14687     break;
14688   case Stmt::CStyleCastExprClass:
14689   case Stmt::CXXStaticCastExprClass:
14690   case Stmt::ImplicitCastExprClass: {
14691     auto *CE = cast<CastExpr>(E);
14692     const Expr *From = CE->getSubExpr();
14693     switch (CE->getCastKind()) {
14694     default:
14695       break;
14696     case CK_NoOp:
14697       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14698     case CK_UncheckedDerivedToBase:
14699     case CK_DerivedToBase: {
14700       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14701       if (!P)
14702         break;
14703       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14704                                                 P->second, Ctx);
14705     }
14706     }
14707     break;
14708   }
14709   case Stmt::ArraySubscriptExprClass: {
14710     auto *ASE = cast<ArraySubscriptExpr>(E);
14711     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14712                                                 false, Ctx);
14713   }
14714   case Stmt::DeclRefExprClass: {
14715     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14716       // FIXME: If VD is captured by copy or is an escaping __block variable,
14717       // use the alignment of VD's type.
14718       if (!VD->getType()->isReferenceType())
14719         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14720       if (VD->hasInit())
14721         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14722     }
14723     break;
14724   }
14725   case Stmt::MemberExprClass: {
14726     auto *ME = cast<MemberExpr>(E);
14727     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14728     if (!FD || FD->getType()->isReferenceType() ||
14729         FD->getParent()->isInvalidDecl())
14730       break;
14731     Optional<std::pair<CharUnits, CharUnits>> P;
14732     if (ME->isArrow())
14733       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14734     else
14735       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14736     if (!P)
14737       break;
14738     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14739     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14740     return std::make_pair(P->first,
14741                           P->second + CharUnits::fromQuantity(Offset));
14742   }
14743   case Stmt::UnaryOperatorClass: {
14744     auto *UO = cast<UnaryOperator>(E);
14745     switch (UO->getOpcode()) {
14746     default:
14747       break;
14748     case UO_Deref:
14749       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14750     }
14751     break;
14752   }
14753   case Stmt::BinaryOperatorClass: {
14754     auto *BO = cast<BinaryOperator>(E);
14755     auto Opcode = BO->getOpcode();
14756     switch (Opcode) {
14757     default:
14758       break;
14759     case BO_Comma:
14760       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14761     }
14762     break;
14763   }
14764   }
14765   return llvm::None;
14766 }
14767 
14768 /// This helper function takes a pointer expression and returns the alignment of
14769 /// a VarDecl and a constant offset from the VarDecl.
14770 Optional<std::pair<CharUnits, CharUnits>>
14771 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14772   E = E->IgnoreParens();
14773   switch (E->getStmtClass()) {
14774   default:
14775     break;
14776   case Stmt::CStyleCastExprClass:
14777   case Stmt::CXXStaticCastExprClass:
14778   case Stmt::ImplicitCastExprClass: {
14779     auto *CE = cast<CastExpr>(E);
14780     const Expr *From = CE->getSubExpr();
14781     switch (CE->getCastKind()) {
14782     default:
14783       break;
14784     case CK_NoOp:
14785       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14786     case CK_ArrayToPointerDecay:
14787       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14788     case CK_UncheckedDerivedToBase:
14789     case CK_DerivedToBase: {
14790       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14791       if (!P)
14792         break;
14793       return getDerivedToBaseAlignmentAndOffset(
14794           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14795     }
14796     }
14797     break;
14798   }
14799   case Stmt::CXXThisExprClass: {
14800     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14801     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14802     return std::make_pair(Alignment, CharUnits::Zero());
14803   }
14804   case Stmt::UnaryOperatorClass: {
14805     auto *UO = cast<UnaryOperator>(E);
14806     if (UO->getOpcode() == UO_AddrOf)
14807       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14808     break;
14809   }
14810   case Stmt::BinaryOperatorClass: {
14811     auto *BO = cast<BinaryOperator>(E);
14812     auto Opcode = BO->getOpcode();
14813     switch (Opcode) {
14814     default:
14815       break;
14816     case BO_Add:
14817     case BO_Sub: {
14818       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14819       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14820         std::swap(LHS, RHS);
14821       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14822                                                   Ctx);
14823     }
14824     case BO_Comma:
14825       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14826     }
14827     break;
14828   }
14829   }
14830   return llvm::None;
14831 }
14832 
14833 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14834   // See if we can compute the alignment of a VarDecl and an offset from it.
14835   Optional<std::pair<CharUnits, CharUnits>> P =
14836       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14837 
14838   if (P)
14839     return P->first.alignmentAtOffset(P->second);
14840 
14841   // If that failed, return the type's alignment.
14842   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14843 }
14844 
14845 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14846 /// pointer cast increases the alignment requirements.
14847 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14848   // This is actually a lot of work to potentially be doing on every
14849   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14850   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14851     return;
14852 
14853   // Ignore dependent types.
14854   if (T->isDependentType() || Op->getType()->isDependentType())
14855     return;
14856 
14857   // Require that the destination be a pointer type.
14858   const PointerType *DestPtr = T->getAs<PointerType>();
14859   if (!DestPtr) return;
14860 
14861   // If the destination has alignment 1, we're done.
14862   QualType DestPointee = DestPtr->getPointeeType();
14863   if (DestPointee->isIncompleteType()) return;
14864   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14865   if (DestAlign.isOne()) return;
14866 
14867   // Require that the source be a pointer type.
14868   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14869   if (!SrcPtr) return;
14870   QualType SrcPointee = SrcPtr->getPointeeType();
14871 
14872   // Explicitly allow casts from cv void*.  We already implicitly
14873   // allowed casts to cv void*, since they have alignment 1.
14874   // Also allow casts involving incomplete types, which implicitly
14875   // includes 'void'.
14876   if (SrcPointee->isIncompleteType()) return;
14877 
14878   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14879 
14880   if (SrcAlign >= DestAlign) return;
14881 
14882   Diag(TRange.getBegin(), diag::warn_cast_align)
14883     << Op->getType() << T
14884     << static_cast<unsigned>(SrcAlign.getQuantity())
14885     << static_cast<unsigned>(DestAlign.getQuantity())
14886     << TRange << Op->getSourceRange();
14887 }
14888 
14889 /// Check whether this array fits the idiom of a size-one tail padded
14890 /// array member of a struct.
14891 ///
14892 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14893 /// commonly used to emulate flexible arrays in C89 code.
14894 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14895                                     const NamedDecl *ND) {
14896   if (Size != 1 || !ND) return false;
14897 
14898   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14899   if (!FD) return false;
14900 
14901   // Don't consider sizes resulting from macro expansions or template argument
14902   // substitution to form C89 tail-padded arrays.
14903 
14904   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14905   while (TInfo) {
14906     TypeLoc TL = TInfo->getTypeLoc();
14907     // Look through typedefs.
14908     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14909       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14910       TInfo = TDL->getTypeSourceInfo();
14911       continue;
14912     }
14913     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14914       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14915       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14916         return false;
14917     }
14918     break;
14919   }
14920 
14921   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14922   if (!RD) return false;
14923   if (RD->isUnion()) return false;
14924   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14925     if (!CRD->isStandardLayout()) return false;
14926   }
14927 
14928   // See if this is the last field decl in the record.
14929   const Decl *D = FD;
14930   while ((D = D->getNextDeclInContext()))
14931     if (isa<FieldDecl>(D))
14932       return false;
14933   return true;
14934 }
14935 
14936 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14937                             const ArraySubscriptExpr *ASE,
14938                             bool AllowOnePastEnd, bool IndexNegated) {
14939   // Already diagnosed by the constant evaluator.
14940   if (isConstantEvaluated())
14941     return;
14942 
14943   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14944   if (IndexExpr->isValueDependent())
14945     return;
14946 
14947   const Type *EffectiveType =
14948       BaseExpr->getType()->getPointeeOrArrayElementType();
14949   BaseExpr = BaseExpr->IgnoreParenCasts();
14950   const ConstantArrayType *ArrayTy =
14951       Context.getAsConstantArrayType(BaseExpr->getType());
14952 
14953   const Type *BaseType =
14954       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14955   bool IsUnboundedArray = (BaseType == nullptr);
14956   if (EffectiveType->isDependentType() ||
14957       (!IsUnboundedArray && BaseType->isDependentType()))
14958     return;
14959 
14960   Expr::EvalResult Result;
14961   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14962     return;
14963 
14964   llvm::APSInt index = Result.Val.getInt();
14965   if (IndexNegated) {
14966     index.setIsUnsigned(false);
14967     index = -index;
14968   }
14969 
14970   const NamedDecl *ND = nullptr;
14971   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14972     ND = DRE->getDecl();
14973   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14974     ND = ME->getMemberDecl();
14975 
14976   if (IsUnboundedArray) {
14977     if (index.isUnsigned() || !index.isNegative()) {
14978       const auto &ASTC = getASTContext();
14979       unsigned AddrBits =
14980           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14981               EffectiveType->getCanonicalTypeInternal()));
14982       if (index.getBitWidth() < AddrBits)
14983         index = index.zext(AddrBits);
14984       Optional<CharUnits> ElemCharUnits =
14985           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14986       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14987       // pointer) bounds-checking isn't meaningful.
14988       if (!ElemCharUnits)
14989         return;
14990       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14991       // If index has more active bits than address space, we already know
14992       // we have a bounds violation to warn about.  Otherwise, compute
14993       // address of (index + 1)th element, and warn about bounds violation
14994       // only if that address exceeds address space.
14995       if (index.getActiveBits() <= AddrBits) {
14996         bool Overflow;
14997         llvm::APInt Product(index);
14998         Product += 1;
14999         Product = Product.umul_ov(ElemBytes, Overflow);
15000         if (!Overflow && Product.getActiveBits() <= AddrBits)
15001           return;
15002       }
15003 
15004       // Need to compute max possible elements in address space, since that
15005       // is included in diag message.
15006       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15007       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15008       MaxElems += 1;
15009       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15010       MaxElems = MaxElems.udiv(ElemBytes);
15011 
15012       unsigned DiagID =
15013           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15014               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15015 
15016       // Diag message shows element size in bits and in "bytes" (platform-
15017       // dependent CharUnits)
15018       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15019                           PDiag(DiagID)
15020                               << toString(index, 10, true) << AddrBits
15021                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15022                               << toString(ElemBytes, 10, false)
15023                               << toString(MaxElems, 10, false)
15024                               << (unsigned)MaxElems.getLimitedValue(~0U)
15025                               << IndexExpr->getSourceRange());
15026 
15027       if (!ND) {
15028         // Try harder to find a NamedDecl to point at in the note.
15029         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15030           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15031         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15032           ND = DRE->getDecl();
15033         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15034           ND = ME->getMemberDecl();
15035       }
15036 
15037       if (ND)
15038         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15039                             PDiag(diag::note_array_declared_here) << ND);
15040     }
15041     return;
15042   }
15043 
15044   if (index.isUnsigned() || !index.isNegative()) {
15045     // It is possible that the type of the base expression after
15046     // IgnoreParenCasts is incomplete, even though the type of the base
15047     // expression before IgnoreParenCasts is complete (see PR39746 for an
15048     // example). In this case we have no information about whether the array
15049     // access exceeds the array bounds. However we can still diagnose an array
15050     // access which precedes the array bounds.
15051     if (BaseType->isIncompleteType())
15052       return;
15053 
15054     llvm::APInt size = ArrayTy->getSize();
15055     if (!size.isStrictlyPositive())
15056       return;
15057 
15058     if (BaseType != EffectiveType) {
15059       // Make sure we're comparing apples to apples when comparing index to size
15060       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15061       uint64_t array_typesize = Context.getTypeSize(BaseType);
15062       // Handle ptrarith_typesize being zero, such as when casting to void*
15063       if (!ptrarith_typesize) ptrarith_typesize = 1;
15064       if (ptrarith_typesize != array_typesize) {
15065         // There's a cast to a different size type involved
15066         uint64_t ratio = array_typesize / ptrarith_typesize;
15067         // TODO: Be smarter about handling cases where array_typesize is not a
15068         // multiple of ptrarith_typesize
15069         if (ptrarith_typesize * ratio == array_typesize)
15070           size *= llvm::APInt(size.getBitWidth(), ratio);
15071       }
15072     }
15073 
15074     if (size.getBitWidth() > index.getBitWidth())
15075       index = index.zext(size.getBitWidth());
15076     else if (size.getBitWidth() < index.getBitWidth())
15077       size = size.zext(index.getBitWidth());
15078 
15079     // For array subscripting the index must be less than size, but for pointer
15080     // arithmetic also allow the index (offset) to be equal to size since
15081     // computing the next address after the end of the array is legal and
15082     // commonly done e.g. in C++ iterators and range-based for loops.
15083     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15084       return;
15085 
15086     // Also don't warn for arrays of size 1 which are members of some
15087     // structure. These are often used to approximate flexible arrays in C89
15088     // code.
15089     if (IsTailPaddedMemberArray(*this, size, ND))
15090       return;
15091 
15092     // Suppress the warning if the subscript expression (as identified by the
15093     // ']' location) and the index expression are both from macro expansions
15094     // within a system header.
15095     if (ASE) {
15096       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15097           ASE->getRBracketLoc());
15098       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15099         SourceLocation IndexLoc =
15100             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15101         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15102           return;
15103       }
15104     }
15105 
15106     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15107                           : diag::warn_ptr_arith_exceeds_bounds;
15108 
15109     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15110                         PDiag(DiagID) << toString(index, 10, true)
15111                                       << toString(size, 10, true)
15112                                       << (unsigned)size.getLimitedValue(~0U)
15113                                       << IndexExpr->getSourceRange());
15114   } else {
15115     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15116     if (!ASE) {
15117       DiagID = diag::warn_ptr_arith_precedes_bounds;
15118       if (index.isNegative()) index = -index;
15119     }
15120 
15121     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15122                         PDiag(DiagID) << toString(index, 10, true)
15123                                       << IndexExpr->getSourceRange());
15124   }
15125 
15126   if (!ND) {
15127     // Try harder to find a NamedDecl to point at in the note.
15128     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15129       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15130     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15131       ND = DRE->getDecl();
15132     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15133       ND = ME->getMemberDecl();
15134   }
15135 
15136   if (ND)
15137     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15138                         PDiag(diag::note_array_declared_here) << ND);
15139 }
15140 
15141 void Sema::CheckArrayAccess(const Expr *expr) {
15142   int AllowOnePastEnd = 0;
15143   while (expr) {
15144     expr = expr->IgnoreParenImpCasts();
15145     switch (expr->getStmtClass()) {
15146       case Stmt::ArraySubscriptExprClass: {
15147         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15148         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15149                          AllowOnePastEnd > 0);
15150         expr = ASE->getBase();
15151         break;
15152       }
15153       case Stmt::MemberExprClass: {
15154         expr = cast<MemberExpr>(expr)->getBase();
15155         break;
15156       }
15157       case Stmt::OMPArraySectionExprClass: {
15158         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15159         if (ASE->getLowerBound())
15160           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15161                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15162         return;
15163       }
15164       case Stmt::UnaryOperatorClass: {
15165         // Only unwrap the * and & unary operators
15166         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15167         expr = UO->getSubExpr();
15168         switch (UO->getOpcode()) {
15169           case UO_AddrOf:
15170             AllowOnePastEnd++;
15171             break;
15172           case UO_Deref:
15173             AllowOnePastEnd--;
15174             break;
15175           default:
15176             return;
15177         }
15178         break;
15179       }
15180       case Stmt::ConditionalOperatorClass: {
15181         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15182         if (const Expr *lhs = cond->getLHS())
15183           CheckArrayAccess(lhs);
15184         if (const Expr *rhs = cond->getRHS())
15185           CheckArrayAccess(rhs);
15186         return;
15187       }
15188       case Stmt::CXXOperatorCallExprClass: {
15189         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15190         for (const auto *Arg : OCE->arguments())
15191           CheckArrayAccess(Arg);
15192         return;
15193       }
15194       default:
15195         return;
15196     }
15197   }
15198 }
15199 
15200 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15201 
15202 namespace {
15203 
15204 struct RetainCycleOwner {
15205   VarDecl *Variable = nullptr;
15206   SourceRange Range;
15207   SourceLocation Loc;
15208   bool Indirect = false;
15209 
15210   RetainCycleOwner() = default;
15211 
15212   void setLocsFrom(Expr *e) {
15213     Loc = e->getExprLoc();
15214     Range = e->getSourceRange();
15215   }
15216 };
15217 
15218 } // namespace
15219 
15220 /// Consider whether capturing the given variable can possibly lead to
15221 /// a retain cycle.
15222 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15223   // In ARC, it's captured strongly iff the variable has __strong
15224   // lifetime.  In MRR, it's captured strongly if the variable is
15225   // __block and has an appropriate type.
15226   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15227     return false;
15228 
15229   owner.Variable = var;
15230   if (ref)
15231     owner.setLocsFrom(ref);
15232   return true;
15233 }
15234 
15235 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15236   while (true) {
15237     e = e->IgnoreParens();
15238     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15239       switch (cast->getCastKind()) {
15240       case CK_BitCast:
15241       case CK_LValueBitCast:
15242       case CK_LValueToRValue:
15243       case CK_ARCReclaimReturnedObject:
15244         e = cast->getSubExpr();
15245         continue;
15246 
15247       default:
15248         return false;
15249       }
15250     }
15251 
15252     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15253       ObjCIvarDecl *ivar = ref->getDecl();
15254       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15255         return false;
15256 
15257       // Try to find a retain cycle in the base.
15258       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15259         return false;
15260 
15261       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15262       owner.Indirect = true;
15263       return true;
15264     }
15265 
15266     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15267       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15268       if (!var) return false;
15269       return considerVariable(var, ref, owner);
15270     }
15271 
15272     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15273       if (member->isArrow()) return false;
15274 
15275       // Don't count this as an indirect ownership.
15276       e = member->getBase();
15277       continue;
15278     }
15279 
15280     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15281       // Only pay attention to pseudo-objects on property references.
15282       ObjCPropertyRefExpr *pre
15283         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15284                                               ->IgnoreParens());
15285       if (!pre) return false;
15286       if (pre->isImplicitProperty()) return false;
15287       ObjCPropertyDecl *property = pre->getExplicitProperty();
15288       if (!property->isRetaining() &&
15289           !(property->getPropertyIvarDecl() &&
15290             property->getPropertyIvarDecl()->getType()
15291               .getObjCLifetime() == Qualifiers::OCL_Strong))
15292           return false;
15293 
15294       owner.Indirect = true;
15295       if (pre->isSuperReceiver()) {
15296         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15297         if (!owner.Variable)
15298           return false;
15299         owner.Loc = pre->getLocation();
15300         owner.Range = pre->getSourceRange();
15301         return true;
15302       }
15303       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15304                               ->getSourceExpr());
15305       continue;
15306     }
15307 
15308     // Array ivars?
15309 
15310     return false;
15311   }
15312 }
15313 
15314 namespace {
15315 
15316   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15317     ASTContext &Context;
15318     VarDecl *Variable;
15319     Expr *Capturer = nullptr;
15320     bool VarWillBeReased = false;
15321 
15322     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15323         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15324           Context(Context), Variable(variable) {}
15325 
15326     void VisitDeclRefExpr(DeclRefExpr *ref) {
15327       if (ref->getDecl() == Variable && !Capturer)
15328         Capturer = ref;
15329     }
15330 
15331     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15332       if (Capturer) return;
15333       Visit(ref->getBase());
15334       if (Capturer && ref->isFreeIvar())
15335         Capturer = ref;
15336     }
15337 
15338     void VisitBlockExpr(BlockExpr *block) {
15339       // Look inside nested blocks
15340       if (block->getBlockDecl()->capturesVariable(Variable))
15341         Visit(block->getBlockDecl()->getBody());
15342     }
15343 
15344     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15345       if (Capturer) return;
15346       if (OVE->getSourceExpr())
15347         Visit(OVE->getSourceExpr());
15348     }
15349 
15350     void VisitBinaryOperator(BinaryOperator *BinOp) {
15351       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15352         return;
15353       Expr *LHS = BinOp->getLHS();
15354       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15355         if (DRE->getDecl() != Variable)
15356           return;
15357         if (Expr *RHS = BinOp->getRHS()) {
15358           RHS = RHS->IgnoreParenCasts();
15359           Optional<llvm::APSInt> Value;
15360           VarWillBeReased =
15361               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15362                *Value == 0);
15363         }
15364       }
15365     }
15366   };
15367 
15368 } // namespace
15369 
15370 /// Check whether the given argument is a block which captures a
15371 /// variable.
15372 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15373   assert(owner.Variable && owner.Loc.isValid());
15374 
15375   e = e->IgnoreParenCasts();
15376 
15377   // Look through [^{...} copy] and Block_copy(^{...}).
15378   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15379     Selector Cmd = ME->getSelector();
15380     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15381       e = ME->getInstanceReceiver();
15382       if (!e)
15383         return nullptr;
15384       e = e->IgnoreParenCasts();
15385     }
15386   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15387     if (CE->getNumArgs() == 1) {
15388       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15389       if (Fn) {
15390         const IdentifierInfo *FnI = Fn->getIdentifier();
15391         if (FnI && FnI->isStr("_Block_copy")) {
15392           e = CE->getArg(0)->IgnoreParenCasts();
15393         }
15394       }
15395     }
15396   }
15397 
15398   BlockExpr *block = dyn_cast<BlockExpr>(e);
15399   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15400     return nullptr;
15401 
15402   FindCaptureVisitor visitor(S.Context, owner.Variable);
15403   visitor.Visit(block->getBlockDecl()->getBody());
15404   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15405 }
15406 
15407 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15408                                 RetainCycleOwner &owner) {
15409   assert(capturer);
15410   assert(owner.Variable && owner.Loc.isValid());
15411 
15412   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15413     << owner.Variable << capturer->getSourceRange();
15414   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15415     << owner.Indirect << owner.Range;
15416 }
15417 
15418 /// Check for a keyword selector that starts with the word 'add' or
15419 /// 'set'.
15420 static bool isSetterLikeSelector(Selector sel) {
15421   if (sel.isUnarySelector()) return false;
15422 
15423   StringRef str = sel.getNameForSlot(0);
15424   while (!str.empty() && str.front() == '_') str = str.substr(1);
15425   if (str.startswith("set"))
15426     str = str.substr(3);
15427   else if (str.startswith("add")) {
15428     // Specially allow 'addOperationWithBlock:'.
15429     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15430       return false;
15431     str = str.substr(3);
15432   }
15433   else
15434     return false;
15435 
15436   if (str.empty()) return true;
15437   return !isLowercase(str.front());
15438 }
15439 
15440 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15441                                                     ObjCMessageExpr *Message) {
15442   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15443                                                 Message->getReceiverInterface(),
15444                                                 NSAPI::ClassId_NSMutableArray);
15445   if (!IsMutableArray) {
15446     return None;
15447   }
15448 
15449   Selector Sel = Message->getSelector();
15450 
15451   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15452     S.NSAPIObj->getNSArrayMethodKind(Sel);
15453   if (!MKOpt) {
15454     return None;
15455   }
15456 
15457   NSAPI::NSArrayMethodKind MK = *MKOpt;
15458 
15459   switch (MK) {
15460     case NSAPI::NSMutableArr_addObject:
15461     case NSAPI::NSMutableArr_insertObjectAtIndex:
15462     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15463       return 0;
15464     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15465       return 1;
15466 
15467     default:
15468       return None;
15469   }
15470 
15471   return None;
15472 }
15473 
15474 static
15475 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15476                                                   ObjCMessageExpr *Message) {
15477   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15478                                             Message->getReceiverInterface(),
15479                                             NSAPI::ClassId_NSMutableDictionary);
15480   if (!IsMutableDictionary) {
15481     return None;
15482   }
15483 
15484   Selector Sel = Message->getSelector();
15485 
15486   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15487     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15488   if (!MKOpt) {
15489     return None;
15490   }
15491 
15492   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15493 
15494   switch (MK) {
15495     case NSAPI::NSMutableDict_setObjectForKey:
15496     case NSAPI::NSMutableDict_setValueForKey:
15497     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15498       return 0;
15499 
15500     default:
15501       return None;
15502   }
15503 
15504   return None;
15505 }
15506 
15507 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15508   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15509                                                 Message->getReceiverInterface(),
15510                                                 NSAPI::ClassId_NSMutableSet);
15511 
15512   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15513                                             Message->getReceiverInterface(),
15514                                             NSAPI::ClassId_NSMutableOrderedSet);
15515   if (!IsMutableSet && !IsMutableOrderedSet) {
15516     return None;
15517   }
15518 
15519   Selector Sel = Message->getSelector();
15520 
15521   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15522   if (!MKOpt) {
15523     return None;
15524   }
15525 
15526   NSAPI::NSSetMethodKind MK = *MKOpt;
15527 
15528   switch (MK) {
15529     case NSAPI::NSMutableSet_addObject:
15530     case NSAPI::NSOrderedSet_setObjectAtIndex:
15531     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15532     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15533       return 0;
15534     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15535       return 1;
15536   }
15537 
15538   return None;
15539 }
15540 
15541 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15542   if (!Message->isInstanceMessage()) {
15543     return;
15544   }
15545 
15546   Optional<int> ArgOpt;
15547 
15548   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15549       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15550       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15551     return;
15552   }
15553 
15554   int ArgIndex = *ArgOpt;
15555 
15556   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15557   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15558     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15559   }
15560 
15561   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15562     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15563       if (ArgRE->isObjCSelfExpr()) {
15564         Diag(Message->getSourceRange().getBegin(),
15565              diag::warn_objc_circular_container)
15566           << ArgRE->getDecl() << StringRef("'super'");
15567       }
15568     }
15569   } else {
15570     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15571 
15572     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15573       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15574     }
15575 
15576     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15577       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15578         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15579           ValueDecl *Decl = ReceiverRE->getDecl();
15580           Diag(Message->getSourceRange().getBegin(),
15581                diag::warn_objc_circular_container)
15582             << Decl << Decl;
15583           if (!ArgRE->isObjCSelfExpr()) {
15584             Diag(Decl->getLocation(),
15585                  diag::note_objc_circular_container_declared_here)
15586               << Decl;
15587           }
15588         }
15589       }
15590     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15591       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15592         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15593           ObjCIvarDecl *Decl = IvarRE->getDecl();
15594           Diag(Message->getSourceRange().getBegin(),
15595                diag::warn_objc_circular_container)
15596             << Decl << Decl;
15597           Diag(Decl->getLocation(),
15598                diag::note_objc_circular_container_declared_here)
15599             << Decl;
15600         }
15601       }
15602     }
15603   }
15604 }
15605 
15606 /// Check a message send to see if it's likely to cause a retain cycle.
15607 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15608   // Only check instance methods whose selector looks like a setter.
15609   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15610     return;
15611 
15612   // Try to find a variable that the receiver is strongly owned by.
15613   RetainCycleOwner owner;
15614   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15615     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15616       return;
15617   } else {
15618     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15619     owner.Variable = getCurMethodDecl()->getSelfDecl();
15620     owner.Loc = msg->getSuperLoc();
15621     owner.Range = msg->getSuperLoc();
15622   }
15623 
15624   // Check whether the receiver is captured by any of the arguments.
15625   const ObjCMethodDecl *MD = msg->getMethodDecl();
15626   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15627     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15628       // noescape blocks should not be retained by the method.
15629       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15630         continue;
15631       return diagnoseRetainCycle(*this, capturer, owner);
15632     }
15633   }
15634 }
15635 
15636 /// Check a property assign to see if it's likely to cause a retain cycle.
15637 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15638   RetainCycleOwner owner;
15639   if (!findRetainCycleOwner(*this, receiver, owner))
15640     return;
15641 
15642   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15643     diagnoseRetainCycle(*this, capturer, owner);
15644 }
15645 
15646 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15647   RetainCycleOwner Owner;
15648   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15649     return;
15650 
15651   // Because we don't have an expression for the variable, we have to set the
15652   // location explicitly here.
15653   Owner.Loc = Var->getLocation();
15654   Owner.Range = Var->getSourceRange();
15655 
15656   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15657     diagnoseRetainCycle(*this, Capturer, Owner);
15658 }
15659 
15660 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15661                                      Expr *RHS, bool isProperty) {
15662   // Check if RHS is an Objective-C object literal, which also can get
15663   // immediately zapped in a weak reference.  Note that we explicitly
15664   // allow ObjCStringLiterals, since those are designed to never really die.
15665   RHS = RHS->IgnoreParenImpCasts();
15666 
15667   // This enum needs to match with the 'select' in
15668   // warn_objc_arc_literal_assign (off-by-1).
15669   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15670   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15671     return false;
15672 
15673   S.Diag(Loc, diag::warn_arc_literal_assign)
15674     << (unsigned) Kind
15675     << (isProperty ? 0 : 1)
15676     << RHS->getSourceRange();
15677 
15678   return true;
15679 }
15680 
15681 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15682                                     Qualifiers::ObjCLifetime LT,
15683                                     Expr *RHS, bool isProperty) {
15684   // Strip off any implicit cast added to get to the one ARC-specific.
15685   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15686     if (cast->getCastKind() == CK_ARCConsumeObject) {
15687       S.Diag(Loc, diag::warn_arc_retained_assign)
15688         << (LT == Qualifiers::OCL_ExplicitNone)
15689         << (isProperty ? 0 : 1)
15690         << RHS->getSourceRange();
15691       return true;
15692     }
15693     RHS = cast->getSubExpr();
15694   }
15695 
15696   if (LT == Qualifiers::OCL_Weak &&
15697       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15698     return true;
15699 
15700   return false;
15701 }
15702 
15703 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15704                               QualType LHS, Expr *RHS) {
15705   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15706 
15707   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15708     return false;
15709 
15710   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15711     return true;
15712 
15713   return false;
15714 }
15715 
15716 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15717                               Expr *LHS, Expr *RHS) {
15718   QualType LHSType;
15719   // PropertyRef on LHS type need be directly obtained from
15720   // its declaration as it has a PseudoType.
15721   ObjCPropertyRefExpr *PRE
15722     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15723   if (PRE && !PRE->isImplicitProperty()) {
15724     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15725     if (PD)
15726       LHSType = PD->getType();
15727   }
15728 
15729   if (LHSType.isNull())
15730     LHSType = LHS->getType();
15731 
15732   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15733 
15734   if (LT == Qualifiers::OCL_Weak) {
15735     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15736       getCurFunction()->markSafeWeakUse(LHS);
15737   }
15738 
15739   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15740     return;
15741 
15742   // FIXME. Check for other life times.
15743   if (LT != Qualifiers::OCL_None)
15744     return;
15745 
15746   if (PRE) {
15747     if (PRE->isImplicitProperty())
15748       return;
15749     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15750     if (!PD)
15751       return;
15752 
15753     unsigned Attributes = PD->getPropertyAttributes();
15754     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15755       // when 'assign' attribute was not explicitly specified
15756       // by user, ignore it and rely on property type itself
15757       // for lifetime info.
15758       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15759       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15760           LHSType->isObjCRetainableType())
15761         return;
15762 
15763       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15764         if (cast->getCastKind() == CK_ARCConsumeObject) {
15765           Diag(Loc, diag::warn_arc_retained_property_assign)
15766           << RHS->getSourceRange();
15767           return;
15768         }
15769         RHS = cast->getSubExpr();
15770       }
15771     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15772       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15773         return;
15774     }
15775   }
15776 }
15777 
15778 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15779 
15780 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15781                                         SourceLocation StmtLoc,
15782                                         const NullStmt *Body) {
15783   // Do not warn if the body is a macro that expands to nothing, e.g:
15784   //
15785   // #define CALL(x)
15786   // if (condition)
15787   //   CALL(0);
15788   if (Body->hasLeadingEmptyMacro())
15789     return false;
15790 
15791   // Get line numbers of statement and body.
15792   bool StmtLineInvalid;
15793   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15794                                                       &StmtLineInvalid);
15795   if (StmtLineInvalid)
15796     return false;
15797 
15798   bool BodyLineInvalid;
15799   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15800                                                       &BodyLineInvalid);
15801   if (BodyLineInvalid)
15802     return false;
15803 
15804   // Warn if null statement and body are on the same line.
15805   if (StmtLine != BodyLine)
15806     return false;
15807 
15808   return true;
15809 }
15810 
15811 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15812                                  const Stmt *Body,
15813                                  unsigned DiagID) {
15814   // Since this is a syntactic check, don't emit diagnostic for template
15815   // instantiations, this just adds noise.
15816   if (CurrentInstantiationScope)
15817     return;
15818 
15819   // The body should be a null statement.
15820   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15821   if (!NBody)
15822     return;
15823 
15824   // Do the usual checks.
15825   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15826     return;
15827 
15828   Diag(NBody->getSemiLoc(), DiagID);
15829   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15830 }
15831 
15832 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15833                                  const Stmt *PossibleBody) {
15834   assert(!CurrentInstantiationScope); // Ensured by caller
15835 
15836   SourceLocation StmtLoc;
15837   const Stmt *Body;
15838   unsigned DiagID;
15839   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15840     StmtLoc = FS->getRParenLoc();
15841     Body = FS->getBody();
15842     DiagID = diag::warn_empty_for_body;
15843   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15844     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15845     Body = WS->getBody();
15846     DiagID = diag::warn_empty_while_body;
15847   } else
15848     return; // Neither `for' nor `while'.
15849 
15850   // The body should be a null statement.
15851   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15852   if (!NBody)
15853     return;
15854 
15855   // Skip expensive checks if diagnostic is disabled.
15856   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15857     return;
15858 
15859   // Do the usual checks.
15860   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15861     return;
15862 
15863   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15864   // noise level low, emit diagnostics only if for/while is followed by a
15865   // CompoundStmt, e.g.:
15866   //    for (int i = 0; i < n; i++);
15867   //    {
15868   //      a(i);
15869   //    }
15870   // or if for/while is followed by a statement with more indentation
15871   // than for/while itself:
15872   //    for (int i = 0; i < n; i++);
15873   //      a(i);
15874   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15875   if (!ProbableTypo) {
15876     bool BodyColInvalid;
15877     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15878         PossibleBody->getBeginLoc(), &BodyColInvalid);
15879     if (BodyColInvalid)
15880       return;
15881 
15882     bool StmtColInvalid;
15883     unsigned StmtCol =
15884         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15885     if (StmtColInvalid)
15886       return;
15887 
15888     if (BodyCol > StmtCol)
15889       ProbableTypo = true;
15890   }
15891 
15892   if (ProbableTypo) {
15893     Diag(NBody->getSemiLoc(), DiagID);
15894     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15895   }
15896 }
15897 
15898 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15899 
15900 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15901 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15902                              SourceLocation OpLoc) {
15903   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15904     return;
15905 
15906   if (inTemplateInstantiation())
15907     return;
15908 
15909   // Strip parens and casts away.
15910   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15911   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15912 
15913   // Check for a call expression
15914   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15915   if (!CE || CE->getNumArgs() != 1)
15916     return;
15917 
15918   // Check for a call to std::move
15919   if (!CE->isCallToStdMove())
15920     return;
15921 
15922   // Get argument from std::move
15923   RHSExpr = CE->getArg(0);
15924 
15925   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15926   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15927 
15928   // Two DeclRefExpr's, check that the decls are the same.
15929   if (LHSDeclRef && RHSDeclRef) {
15930     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15931       return;
15932     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15933         RHSDeclRef->getDecl()->getCanonicalDecl())
15934       return;
15935 
15936     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15937                                         << LHSExpr->getSourceRange()
15938                                         << RHSExpr->getSourceRange();
15939     return;
15940   }
15941 
15942   // Member variables require a different approach to check for self moves.
15943   // MemberExpr's are the same if every nested MemberExpr refers to the same
15944   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15945   // the base Expr's are CXXThisExpr's.
15946   const Expr *LHSBase = LHSExpr;
15947   const Expr *RHSBase = RHSExpr;
15948   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15949   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15950   if (!LHSME || !RHSME)
15951     return;
15952 
15953   while (LHSME && RHSME) {
15954     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15955         RHSME->getMemberDecl()->getCanonicalDecl())
15956       return;
15957 
15958     LHSBase = LHSME->getBase();
15959     RHSBase = RHSME->getBase();
15960     LHSME = dyn_cast<MemberExpr>(LHSBase);
15961     RHSME = dyn_cast<MemberExpr>(RHSBase);
15962   }
15963 
15964   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15965   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15966   if (LHSDeclRef && RHSDeclRef) {
15967     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15968       return;
15969     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15970         RHSDeclRef->getDecl()->getCanonicalDecl())
15971       return;
15972 
15973     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15974                                         << LHSExpr->getSourceRange()
15975                                         << RHSExpr->getSourceRange();
15976     return;
15977   }
15978 
15979   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15980     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15981                                         << LHSExpr->getSourceRange()
15982                                         << RHSExpr->getSourceRange();
15983 }
15984 
15985 //===--- Layout compatibility ----------------------------------------------//
15986 
15987 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15988 
15989 /// Check if two enumeration types are layout-compatible.
15990 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15991   // C++11 [dcl.enum] p8:
15992   // Two enumeration types are layout-compatible if they have the same
15993   // underlying type.
15994   return ED1->isComplete() && ED2->isComplete() &&
15995          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15996 }
15997 
15998 /// Check if two fields are layout-compatible.
15999 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16000                                FieldDecl *Field2) {
16001   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16002     return false;
16003 
16004   if (Field1->isBitField() != Field2->isBitField())
16005     return false;
16006 
16007   if (Field1->isBitField()) {
16008     // Make sure that the bit-fields are the same length.
16009     unsigned Bits1 = Field1->getBitWidthValue(C);
16010     unsigned Bits2 = Field2->getBitWidthValue(C);
16011 
16012     if (Bits1 != Bits2)
16013       return false;
16014   }
16015 
16016   return true;
16017 }
16018 
16019 /// Check if two standard-layout structs are layout-compatible.
16020 /// (C++11 [class.mem] p17)
16021 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16022                                      RecordDecl *RD2) {
16023   // If both records are C++ classes, check that base classes match.
16024   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16025     // If one of records is a CXXRecordDecl we are in C++ mode,
16026     // thus the other one is a CXXRecordDecl, too.
16027     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16028     // Check number of base classes.
16029     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16030       return false;
16031 
16032     // Check the base classes.
16033     for (CXXRecordDecl::base_class_const_iterator
16034                Base1 = D1CXX->bases_begin(),
16035            BaseEnd1 = D1CXX->bases_end(),
16036               Base2 = D2CXX->bases_begin();
16037          Base1 != BaseEnd1;
16038          ++Base1, ++Base2) {
16039       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16040         return false;
16041     }
16042   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16043     // If only RD2 is a C++ class, it should have zero base classes.
16044     if (D2CXX->getNumBases() > 0)
16045       return false;
16046   }
16047 
16048   // Check the fields.
16049   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16050                              Field2End = RD2->field_end(),
16051                              Field1 = RD1->field_begin(),
16052                              Field1End = RD1->field_end();
16053   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16054     if (!isLayoutCompatible(C, *Field1, *Field2))
16055       return false;
16056   }
16057   if (Field1 != Field1End || Field2 != Field2End)
16058     return false;
16059 
16060   return true;
16061 }
16062 
16063 /// Check if two standard-layout unions are layout-compatible.
16064 /// (C++11 [class.mem] p18)
16065 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16066                                     RecordDecl *RD2) {
16067   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16068   for (auto *Field2 : RD2->fields())
16069     UnmatchedFields.insert(Field2);
16070 
16071   for (auto *Field1 : RD1->fields()) {
16072     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16073         I = UnmatchedFields.begin(),
16074         E = UnmatchedFields.end();
16075 
16076     for ( ; I != E; ++I) {
16077       if (isLayoutCompatible(C, Field1, *I)) {
16078         bool Result = UnmatchedFields.erase(*I);
16079         (void) Result;
16080         assert(Result);
16081         break;
16082       }
16083     }
16084     if (I == E)
16085       return false;
16086   }
16087 
16088   return UnmatchedFields.empty();
16089 }
16090 
16091 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16092                                RecordDecl *RD2) {
16093   if (RD1->isUnion() != RD2->isUnion())
16094     return false;
16095 
16096   if (RD1->isUnion())
16097     return isLayoutCompatibleUnion(C, RD1, RD2);
16098   else
16099     return isLayoutCompatibleStruct(C, RD1, RD2);
16100 }
16101 
16102 /// Check if two types are layout-compatible in C++11 sense.
16103 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16104   if (T1.isNull() || T2.isNull())
16105     return false;
16106 
16107   // C++11 [basic.types] p11:
16108   // If two types T1 and T2 are the same type, then T1 and T2 are
16109   // layout-compatible types.
16110   if (C.hasSameType(T1, T2))
16111     return true;
16112 
16113   T1 = T1.getCanonicalType().getUnqualifiedType();
16114   T2 = T2.getCanonicalType().getUnqualifiedType();
16115 
16116   const Type::TypeClass TC1 = T1->getTypeClass();
16117   const Type::TypeClass TC2 = T2->getTypeClass();
16118 
16119   if (TC1 != TC2)
16120     return false;
16121 
16122   if (TC1 == Type::Enum) {
16123     return isLayoutCompatible(C,
16124                               cast<EnumType>(T1)->getDecl(),
16125                               cast<EnumType>(T2)->getDecl());
16126   } else if (TC1 == Type::Record) {
16127     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16128       return false;
16129 
16130     return isLayoutCompatible(C,
16131                               cast<RecordType>(T1)->getDecl(),
16132                               cast<RecordType>(T2)->getDecl());
16133   }
16134 
16135   return false;
16136 }
16137 
16138 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16139 
16140 /// Given a type tag expression find the type tag itself.
16141 ///
16142 /// \param TypeExpr Type tag expression, as it appears in user's code.
16143 ///
16144 /// \param VD Declaration of an identifier that appears in a type tag.
16145 ///
16146 /// \param MagicValue Type tag magic value.
16147 ///
16148 /// \param isConstantEvaluated whether the evalaution should be performed in
16149 
16150 /// constant context.
16151 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16152                             const ValueDecl **VD, uint64_t *MagicValue,
16153                             bool isConstantEvaluated) {
16154   while(true) {
16155     if (!TypeExpr)
16156       return false;
16157 
16158     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16159 
16160     switch (TypeExpr->getStmtClass()) {
16161     case Stmt::UnaryOperatorClass: {
16162       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16163       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16164         TypeExpr = UO->getSubExpr();
16165         continue;
16166       }
16167       return false;
16168     }
16169 
16170     case Stmt::DeclRefExprClass: {
16171       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16172       *VD = DRE->getDecl();
16173       return true;
16174     }
16175 
16176     case Stmt::IntegerLiteralClass: {
16177       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16178       llvm::APInt MagicValueAPInt = IL->getValue();
16179       if (MagicValueAPInt.getActiveBits() <= 64) {
16180         *MagicValue = MagicValueAPInt.getZExtValue();
16181         return true;
16182       } else
16183         return false;
16184     }
16185 
16186     case Stmt::BinaryConditionalOperatorClass:
16187     case Stmt::ConditionalOperatorClass: {
16188       const AbstractConditionalOperator *ACO =
16189           cast<AbstractConditionalOperator>(TypeExpr);
16190       bool Result;
16191       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16192                                                      isConstantEvaluated)) {
16193         if (Result)
16194           TypeExpr = ACO->getTrueExpr();
16195         else
16196           TypeExpr = ACO->getFalseExpr();
16197         continue;
16198       }
16199       return false;
16200     }
16201 
16202     case Stmt::BinaryOperatorClass: {
16203       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16204       if (BO->getOpcode() == BO_Comma) {
16205         TypeExpr = BO->getRHS();
16206         continue;
16207       }
16208       return false;
16209     }
16210 
16211     default:
16212       return false;
16213     }
16214   }
16215 }
16216 
16217 /// Retrieve the C type corresponding to type tag TypeExpr.
16218 ///
16219 /// \param TypeExpr Expression that specifies a type tag.
16220 ///
16221 /// \param MagicValues Registered magic values.
16222 ///
16223 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16224 ///        kind.
16225 ///
16226 /// \param TypeInfo Information about the corresponding C type.
16227 ///
16228 /// \param isConstantEvaluated whether the evalaution should be performed in
16229 /// constant context.
16230 ///
16231 /// \returns true if the corresponding C type was found.
16232 static bool GetMatchingCType(
16233     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16234     const ASTContext &Ctx,
16235     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16236         *MagicValues,
16237     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16238     bool isConstantEvaluated) {
16239   FoundWrongKind = false;
16240 
16241   // Variable declaration that has type_tag_for_datatype attribute.
16242   const ValueDecl *VD = nullptr;
16243 
16244   uint64_t MagicValue;
16245 
16246   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16247     return false;
16248 
16249   if (VD) {
16250     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16251       if (I->getArgumentKind() != ArgumentKind) {
16252         FoundWrongKind = true;
16253         return false;
16254       }
16255       TypeInfo.Type = I->getMatchingCType();
16256       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16257       TypeInfo.MustBeNull = I->getMustBeNull();
16258       return true;
16259     }
16260     return false;
16261   }
16262 
16263   if (!MagicValues)
16264     return false;
16265 
16266   llvm::DenseMap<Sema::TypeTagMagicValue,
16267                  Sema::TypeTagData>::const_iterator I =
16268       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16269   if (I == MagicValues->end())
16270     return false;
16271 
16272   TypeInfo = I->second;
16273   return true;
16274 }
16275 
16276 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16277                                       uint64_t MagicValue, QualType Type,
16278                                       bool LayoutCompatible,
16279                                       bool MustBeNull) {
16280   if (!TypeTagForDatatypeMagicValues)
16281     TypeTagForDatatypeMagicValues.reset(
16282         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16283 
16284   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16285   (*TypeTagForDatatypeMagicValues)[Magic] =
16286       TypeTagData(Type, LayoutCompatible, MustBeNull);
16287 }
16288 
16289 static bool IsSameCharType(QualType T1, QualType T2) {
16290   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16291   if (!BT1)
16292     return false;
16293 
16294   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16295   if (!BT2)
16296     return false;
16297 
16298   BuiltinType::Kind T1Kind = BT1->getKind();
16299   BuiltinType::Kind T2Kind = BT2->getKind();
16300 
16301   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16302          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16303          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16304          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16305 }
16306 
16307 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16308                                     const ArrayRef<const Expr *> ExprArgs,
16309                                     SourceLocation CallSiteLoc) {
16310   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16311   bool IsPointerAttr = Attr->getIsPointer();
16312 
16313   // Retrieve the argument representing the 'type_tag'.
16314   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16315   if (TypeTagIdxAST >= ExprArgs.size()) {
16316     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16317         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16318     return;
16319   }
16320   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16321   bool FoundWrongKind;
16322   TypeTagData TypeInfo;
16323   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16324                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16325                         TypeInfo, isConstantEvaluated())) {
16326     if (FoundWrongKind)
16327       Diag(TypeTagExpr->getExprLoc(),
16328            diag::warn_type_tag_for_datatype_wrong_kind)
16329         << TypeTagExpr->getSourceRange();
16330     return;
16331   }
16332 
16333   // Retrieve the argument representing the 'arg_idx'.
16334   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16335   if (ArgumentIdxAST >= ExprArgs.size()) {
16336     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16337         << 1 << Attr->getArgumentIdx().getSourceIndex();
16338     return;
16339   }
16340   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16341   if (IsPointerAttr) {
16342     // Skip implicit cast of pointer to `void *' (as a function argument).
16343     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16344       if (ICE->getType()->isVoidPointerType() &&
16345           ICE->getCastKind() == CK_BitCast)
16346         ArgumentExpr = ICE->getSubExpr();
16347   }
16348   QualType ArgumentType = ArgumentExpr->getType();
16349 
16350   // Passing a `void*' pointer shouldn't trigger a warning.
16351   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16352     return;
16353 
16354   if (TypeInfo.MustBeNull) {
16355     // Type tag with matching void type requires a null pointer.
16356     if (!ArgumentExpr->isNullPointerConstant(Context,
16357                                              Expr::NPC_ValueDependentIsNotNull)) {
16358       Diag(ArgumentExpr->getExprLoc(),
16359            diag::warn_type_safety_null_pointer_required)
16360           << ArgumentKind->getName()
16361           << ArgumentExpr->getSourceRange()
16362           << TypeTagExpr->getSourceRange();
16363     }
16364     return;
16365   }
16366 
16367   QualType RequiredType = TypeInfo.Type;
16368   if (IsPointerAttr)
16369     RequiredType = Context.getPointerType(RequiredType);
16370 
16371   bool mismatch = false;
16372   if (!TypeInfo.LayoutCompatible) {
16373     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16374 
16375     // C++11 [basic.fundamental] p1:
16376     // Plain char, signed char, and unsigned char are three distinct types.
16377     //
16378     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16379     // char' depending on the current char signedness mode.
16380     if (mismatch)
16381       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16382                                            RequiredType->getPointeeType())) ||
16383           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16384         mismatch = false;
16385   } else
16386     if (IsPointerAttr)
16387       mismatch = !isLayoutCompatible(Context,
16388                                      ArgumentType->getPointeeType(),
16389                                      RequiredType->getPointeeType());
16390     else
16391       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16392 
16393   if (mismatch)
16394     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16395         << ArgumentType << ArgumentKind
16396         << TypeInfo.LayoutCompatible << RequiredType
16397         << ArgumentExpr->getSourceRange()
16398         << TypeTagExpr->getSourceRange();
16399 }
16400 
16401 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16402                                          CharUnits Alignment) {
16403   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16404 }
16405 
16406 void Sema::DiagnoseMisalignedMembers() {
16407   for (MisalignedMember &m : MisalignedMembers) {
16408     const NamedDecl *ND = m.RD;
16409     if (ND->getName().empty()) {
16410       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16411         ND = TD;
16412     }
16413     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16414         << m.MD << ND << m.E->getSourceRange();
16415   }
16416   MisalignedMembers.clear();
16417 }
16418 
16419 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16420   E = E->IgnoreParens();
16421   if (!T->isPointerType() && !T->isIntegerType())
16422     return;
16423   if (isa<UnaryOperator>(E) &&
16424       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16425     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16426     if (isa<MemberExpr>(Op)) {
16427       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16428       if (MA != MisalignedMembers.end() &&
16429           (T->isIntegerType() ||
16430            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16431                                    Context.getTypeAlignInChars(
16432                                        T->getPointeeType()) <= MA->Alignment))))
16433         MisalignedMembers.erase(MA);
16434     }
16435   }
16436 }
16437 
16438 void Sema::RefersToMemberWithReducedAlignment(
16439     Expr *E,
16440     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16441         Action) {
16442   const auto *ME = dyn_cast<MemberExpr>(E);
16443   if (!ME)
16444     return;
16445 
16446   // No need to check expressions with an __unaligned-qualified type.
16447   if (E->getType().getQualifiers().hasUnaligned())
16448     return;
16449 
16450   // For a chain of MemberExpr like "a.b.c.d" this list
16451   // will keep FieldDecl's like [d, c, b].
16452   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16453   const MemberExpr *TopME = nullptr;
16454   bool AnyIsPacked = false;
16455   do {
16456     QualType BaseType = ME->getBase()->getType();
16457     if (BaseType->isDependentType())
16458       return;
16459     if (ME->isArrow())
16460       BaseType = BaseType->getPointeeType();
16461     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16462     if (RD->isInvalidDecl())
16463       return;
16464 
16465     ValueDecl *MD = ME->getMemberDecl();
16466     auto *FD = dyn_cast<FieldDecl>(MD);
16467     // We do not care about non-data members.
16468     if (!FD || FD->isInvalidDecl())
16469       return;
16470 
16471     AnyIsPacked =
16472         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16473     ReverseMemberChain.push_back(FD);
16474 
16475     TopME = ME;
16476     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16477   } while (ME);
16478   assert(TopME && "We did not compute a topmost MemberExpr!");
16479 
16480   // Not the scope of this diagnostic.
16481   if (!AnyIsPacked)
16482     return;
16483 
16484   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16485   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16486   // TODO: The innermost base of the member expression may be too complicated.
16487   // For now, just disregard these cases. This is left for future
16488   // improvement.
16489   if (!DRE && !isa<CXXThisExpr>(TopBase))
16490       return;
16491 
16492   // Alignment expected by the whole expression.
16493   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16494 
16495   // No need to do anything else with this case.
16496   if (ExpectedAlignment.isOne())
16497     return;
16498 
16499   // Synthesize offset of the whole access.
16500   CharUnits Offset;
16501   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16502        I++) {
16503     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16504   }
16505 
16506   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16507   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16508       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16509 
16510   // The base expression of the innermost MemberExpr may give
16511   // stronger guarantees than the class containing the member.
16512   if (DRE && !TopME->isArrow()) {
16513     const ValueDecl *VD = DRE->getDecl();
16514     if (!VD->getType()->isReferenceType())
16515       CompleteObjectAlignment =
16516           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16517   }
16518 
16519   // Check if the synthesized offset fulfills the alignment.
16520   if (Offset % ExpectedAlignment != 0 ||
16521       // It may fulfill the offset it but the effective alignment may still be
16522       // lower than the expected expression alignment.
16523       CompleteObjectAlignment < ExpectedAlignment) {
16524     // If this happens, we want to determine a sensible culprit of this.
16525     // Intuitively, watching the chain of member expressions from right to
16526     // left, we start with the required alignment (as required by the field
16527     // type) but some packed attribute in that chain has reduced the alignment.
16528     // It may happen that another packed structure increases it again. But if
16529     // we are here such increase has not been enough. So pointing the first
16530     // FieldDecl that either is packed or else its RecordDecl is,
16531     // seems reasonable.
16532     FieldDecl *FD = nullptr;
16533     CharUnits Alignment;
16534     for (FieldDecl *FDI : ReverseMemberChain) {
16535       if (FDI->hasAttr<PackedAttr>() ||
16536           FDI->getParent()->hasAttr<PackedAttr>()) {
16537         FD = FDI;
16538         Alignment = std::min(
16539             Context.getTypeAlignInChars(FD->getType()),
16540             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16541         break;
16542       }
16543     }
16544     assert(FD && "We did not find a packed FieldDecl!");
16545     Action(E, FD->getParent(), FD, Alignment);
16546   }
16547 }
16548 
16549 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16550   using namespace std::placeholders;
16551 
16552   RefersToMemberWithReducedAlignment(
16553       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16554                      _2, _3, _4));
16555 }
16556 
16557 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16558                                             ExprResult CallResult) {
16559   if (checkArgCount(*this, TheCall, 1))
16560     return ExprError();
16561 
16562   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16563   if (MatrixArg.isInvalid())
16564     return MatrixArg;
16565   Expr *Matrix = MatrixArg.get();
16566 
16567   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16568   if (!MType) {
16569     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16570     return ExprError();
16571   }
16572 
16573   // Create returned matrix type by swapping rows and columns of the argument
16574   // matrix type.
16575   QualType ResultType = Context.getConstantMatrixType(
16576       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16577 
16578   // Change the return type to the type of the returned matrix.
16579   TheCall->setType(ResultType);
16580 
16581   // Update call argument to use the possibly converted matrix argument.
16582   TheCall->setArg(0, Matrix);
16583   return CallResult;
16584 }
16585 
16586 // Get and verify the matrix dimensions.
16587 static llvm::Optional<unsigned>
16588 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16589   SourceLocation ErrorPos;
16590   Optional<llvm::APSInt> Value =
16591       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16592   if (!Value) {
16593     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16594         << Name;
16595     return {};
16596   }
16597   uint64_t Dim = Value->getZExtValue();
16598   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16599     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16600         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16601     return {};
16602   }
16603   return Dim;
16604 }
16605 
16606 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16607                                                   ExprResult CallResult) {
16608   if (!getLangOpts().MatrixTypes) {
16609     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16610     return ExprError();
16611   }
16612 
16613   if (checkArgCount(*this, TheCall, 4))
16614     return ExprError();
16615 
16616   unsigned PtrArgIdx = 0;
16617   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16618   Expr *RowsExpr = TheCall->getArg(1);
16619   Expr *ColumnsExpr = TheCall->getArg(2);
16620   Expr *StrideExpr = TheCall->getArg(3);
16621 
16622   bool ArgError = false;
16623 
16624   // Check pointer argument.
16625   {
16626     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16627     if (PtrConv.isInvalid())
16628       return PtrConv;
16629     PtrExpr = PtrConv.get();
16630     TheCall->setArg(0, PtrExpr);
16631     if (PtrExpr->isTypeDependent()) {
16632       TheCall->setType(Context.DependentTy);
16633       return TheCall;
16634     }
16635   }
16636 
16637   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16638   QualType ElementTy;
16639   if (!PtrTy) {
16640     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16641         << PtrArgIdx + 1;
16642     ArgError = true;
16643   } else {
16644     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16645 
16646     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16647       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16648           << PtrArgIdx + 1;
16649       ArgError = true;
16650     }
16651   }
16652 
16653   // Apply default Lvalue conversions and convert the expression to size_t.
16654   auto ApplyArgumentConversions = [this](Expr *E) {
16655     ExprResult Conv = DefaultLvalueConversion(E);
16656     if (Conv.isInvalid())
16657       return Conv;
16658 
16659     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16660   };
16661 
16662   // Apply conversion to row and column expressions.
16663   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16664   if (!RowsConv.isInvalid()) {
16665     RowsExpr = RowsConv.get();
16666     TheCall->setArg(1, RowsExpr);
16667   } else
16668     RowsExpr = nullptr;
16669 
16670   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16671   if (!ColumnsConv.isInvalid()) {
16672     ColumnsExpr = ColumnsConv.get();
16673     TheCall->setArg(2, ColumnsExpr);
16674   } else
16675     ColumnsExpr = nullptr;
16676 
16677   // If any any part of the result matrix type is still pending, just use
16678   // Context.DependentTy, until all parts are resolved.
16679   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16680       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16681     TheCall->setType(Context.DependentTy);
16682     return CallResult;
16683   }
16684 
16685   // Check row and column dimensions.
16686   llvm::Optional<unsigned> MaybeRows;
16687   if (RowsExpr)
16688     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16689 
16690   llvm::Optional<unsigned> MaybeColumns;
16691   if (ColumnsExpr)
16692     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16693 
16694   // Check stride argument.
16695   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16696   if (StrideConv.isInvalid())
16697     return ExprError();
16698   StrideExpr = StrideConv.get();
16699   TheCall->setArg(3, StrideExpr);
16700 
16701   if (MaybeRows) {
16702     if (Optional<llvm::APSInt> Value =
16703             StrideExpr->getIntegerConstantExpr(Context)) {
16704       uint64_t Stride = Value->getZExtValue();
16705       if (Stride < *MaybeRows) {
16706         Diag(StrideExpr->getBeginLoc(),
16707              diag::err_builtin_matrix_stride_too_small);
16708         ArgError = true;
16709       }
16710     }
16711   }
16712 
16713   if (ArgError || !MaybeRows || !MaybeColumns)
16714     return ExprError();
16715 
16716   TheCall->setType(
16717       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16718   return CallResult;
16719 }
16720 
16721 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16722                                                    ExprResult CallResult) {
16723   if (checkArgCount(*this, TheCall, 3))
16724     return ExprError();
16725 
16726   unsigned PtrArgIdx = 1;
16727   Expr *MatrixExpr = TheCall->getArg(0);
16728   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16729   Expr *StrideExpr = TheCall->getArg(2);
16730 
16731   bool ArgError = false;
16732 
16733   {
16734     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16735     if (MatrixConv.isInvalid())
16736       return MatrixConv;
16737     MatrixExpr = MatrixConv.get();
16738     TheCall->setArg(0, MatrixExpr);
16739   }
16740   if (MatrixExpr->isTypeDependent()) {
16741     TheCall->setType(Context.DependentTy);
16742     return TheCall;
16743   }
16744 
16745   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16746   if (!MatrixTy) {
16747     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16748     ArgError = true;
16749   }
16750 
16751   {
16752     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16753     if (PtrConv.isInvalid())
16754       return PtrConv;
16755     PtrExpr = PtrConv.get();
16756     TheCall->setArg(1, PtrExpr);
16757     if (PtrExpr->isTypeDependent()) {
16758       TheCall->setType(Context.DependentTy);
16759       return TheCall;
16760     }
16761   }
16762 
16763   // Check pointer argument.
16764   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16765   if (!PtrTy) {
16766     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16767         << PtrArgIdx + 1;
16768     ArgError = true;
16769   } else {
16770     QualType ElementTy = PtrTy->getPointeeType();
16771     if (ElementTy.isConstQualified()) {
16772       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16773       ArgError = true;
16774     }
16775     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16776     if (MatrixTy &&
16777         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16778       Diag(PtrExpr->getBeginLoc(),
16779            diag::err_builtin_matrix_pointer_arg_mismatch)
16780           << ElementTy << MatrixTy->getElementType();
16781       ArgError = true;
16782     }
16783   }
16784 
16785   // Apply default Lvalue conversions and convert the stride expression to
16786   // size_t.
16787   {
16788     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16789     if (StrideConv.isInvalid())
16790       return StrideConv;
16791 
16792     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16793     if (StrideConv.isInvalid())
16794       return StrideConv;
16795     StrideExpr = StrideConv.get();
16796     TheCall->setArg(2, StrideExpr);
16797   }
16798 
16799   // Check stride argument.
16800   if (MatrixTy) {
16801     if (Optional<llvm::APSInt> Value =
16802             StrideExpr->getIntegerConstantExpr(Context)) {
16803       uint64_t Stride = Value->getZExtValue();
16804       if (Stride < MatrixTy->getNumRows()) {
16805         Diag(StrideExpr->getBeginLoc(),
16806              diag::err_builtin_matrix_stride_too_small);
16807         ArgError = true;
16808       }
16809     }
16810   }
16811 
16812   if (ArgError)
16813     return ExprError();
16814 
16815   return CallResult;
16816 }
16817 
16818 /// \brief Enforce the bounds of a TCB
16819 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16820 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16821 /// and enforce_tcb_leaf attributes.
16822 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16823                                const FunctionDecl *Callee) {
16824   const FunctionDecl *Caller = getCurFunctionDecl();
16825 
16826   // Calls to builtins are not enforced.
16827   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16828       Callee->getBuiltinID() != 0)
16829     return;
16830 
16831   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16832   // all TCBs the callee is a part of.
16833   llvm::StringSet<> CalleeTCBs;
16834   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16835            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16836   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16837            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16838 
16839   // Go through the TCBs the caller is a part of and emit warnings if Caller
16840   // is in a TCB that the Callee is not.
16841   for_each(
16842       Caller->specific_attrs<EnforceTCBAttr>(),
16843       [&](const auto *A) {
16844         StringRef CallerTCB = A->getTCBName();
16845         if (CalleeTCBs.count(CallerTCB) == 0) {
16846           this->Diag(TheCall->getExprLoc(),
16847                      diag::warn_tcb_enforcement_violation) << Callee
16848                                                            << CallerTCB;
16849         }
16850       });
16851 }
16852