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   case PPC::BI__builtin_darn:
3299   case PPC::BI__builtin_darn_raw:
3300     return true;
3301   }
3302   return false;
3303 }
3304 
3305 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3306                              StringRef FeatureToCheck, unsigned DiagID,
3307                              StringRef DiagArg = "") {
3308   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3309     return false;
3310 
3311   if (DiagArg.empty())
3312     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3313   else
3314     S.Diag(TheCall->getBeginLoc(), DiagID)
3315         << DiagArg << TheCall->getSourceRange();
3316 
3317   return true;
3318 }
3319 
3320 /// Returns true if the argument consists of one contiguous run of 1s with any
3321 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3322 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3323 /// since all 1s are not contiguous.
3324 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3325   llvm::APSInt Result;
3326   // We can't check the value of a dependent argument.
3327   Expr *Arg = TheCall->getArg(ArgNum);
3328   if (Arg->isTypeDependent() || Arg->isValueDependent())
3329     return false;
3330 
3331   // Check constant-ness first.
3332   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3333     return true;
3334 
3335   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3336   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3337     return false;
3338 
3339   return Diag(TheCall->getBeginLoc(),
3340               diag::err_argument_not_contiguous_bit_field)
3341          << ArgNum << Arg->getSourceRange();
3342 }
3343 
3344 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3345                                        CallExpr *TheCall) {
3346   unsigned i = 0, l = 0, u = 0;
3347   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3348   llvm::APSInt Result;
3349 
3350   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3351     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3352            << TheCall->getSourceRange();
3353 
3354   switch (BuiltinID) {
3355   default: return false;
3356   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3357   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3358     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3359            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3360   case PPC::BI__builtin_altivec_dss:
3361     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3362   case PPC::BI__builtin_tbegin:
3363   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3364   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3365   case PPC::BI__builtin_tabortwc:
3366   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3367   case PPC::BI__builtin_tabortwci:
3368   case PPC::BI__builtin_tabortdci:
3369     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3370            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3371   case PPC::BI__builtin_altivec_dst:
3372   case PPC::BI__builtin_altivec_dstt:
3373   case PPC::BI__builtin_altivec_dstst:
3374   case PPC::BI__builtin_altivec_dststt:
3375     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3376   case PPC::BI__builtin_vsx_xxpermdi:
3377   case PPC::BI__builtin_vsx_xxsldwi:
3378     return SemaBuiltinVSX(TheCall);
3379   case PPC::BI__builtin_divwe:
3380   case PPC::BI__builtin_divweu:
3381   case PPC::BI__builtin_divde:
3382   case PPC::BI__builtin_divdeu:
3383     return SemaFeatureCheck(*this, TheCall, "extdiv",
3384                             diag::err_ppc_builtin_only_on_arch, "7");
3385   case PPC::BI__builtin_bpermd:
3386     return SemaFeatureCheck(*this, TheCall, "bpermd",
3387                             diag::err_ppc_builtin_only_on_arch, "7");
3388   case PPC::BI__builtin_unpack_vector_int128:
3389     return SemaFeatureCheck(*this, TheCall, "vsx",
3390                             diag::err_ppc_builtin_only_on_arch, "7") ||
3391            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3392   case PPC::BI__builtin_pack_vector_int128:
3393     return SemaFeatureCheck(*this, TheCall, "vsx",
3394                             diag::err_ppc_builtin_only_on_arch, "7");
3395   case PPC::BI__builtin_altivec_vgnb:
3396      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3397   case PPC::BI__builtin_altivec_vec_replace_elt:
3398   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3399     QualType VecTy = TheCall->getArg(0)->getType();
3400     QualType EltTy = TheCall->getArg(1)->getType();
3401     unsigned Width = Context.getIntWidth(EltTy);
3402     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3403            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3404   }
3405   case PPC::BI__builtin_vsx_xxeval:
3406      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3407   case PPC::BI__builtin_altivec_vsldbi:
3408      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3409   case PPC::BI__builtin_altivec_vsrdbi:
3410      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3411   case PPC::BI__builtin_vsx_xxpermx:
3412      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3413   case PPC::BI__builtin_ppc_tw:
3414   case PPC::BI__builtin_ppc_tdw:
3415     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3416   case PPC::BI__builtin_ppc_cmpeqb:
3417   case PPC::BI__builtin_ppc_setb:
3418   case PPC::BI__builtin_ppc_maddhd:
3419   case PPC::BI__builtin_ppc_maddhdu:
3420   case PPC::BI__builtin_ppc_maddld:
3421     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3422                             diag::err_ppc_builtin_only_on_arch, "9");
3423   case PPC::BI__builtin_ppc_cmprb:
3424     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3425                             diag::err_ppc_builtin_only_on_arch, "9") ||
3426            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3427   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3428   // be a constant that represents a contiguous bit field.
3429   case PPC::BI__builtin_ppc_rlwnm:
3430     return SemaBuiltinConstantArg(TheCall, 1, Result) ||
3431            SemaValueIsRunOfOnes(TheCall, 2);
3432   case PPC::BI__builtin_ppc_rlwimi:
3433   case PPC::BI__builtin_ppc_rldimi:
3434     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3435            SemaValueIsRunOfOnes(TheCall, 3);
3436   case PPC::BI__builtin_ppc_extract_exp:
3437   case PPC::BI__builtin_ppc_extract_sig:
3438   case PPC::BI__builtin_ppc_insert_exp:
3439     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3440                             diag::err_ppc_builtin_only_on_arch, "9");
3441   case PPC::BI__builtin_ppc_addex: {
3442     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3443                          diag::err_ppc_builtin_only_on_arch, "9") ||
3444         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3445       return true;
3446     // Output warning for reserved values 1 to 3.
3447     int ArgValue =
3448         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3449     if (ArgValue != 0)
3450       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3451           << ArgValue;
3452     return false;
3453   }
3454   case PPC::BI__builtin_ppc_mtfsb0:
3455   case PPC::BI__builtin_ppc_mtfsb1:
3456     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3457   case PPC::BI__builtin_ppc_mtfsf:
3458     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3459   case PPC::BI__builtin_ppc_mtfsfi:
3460     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3461            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3462   case PPC::BI__builtin_ppc_alignx:
3463     return SemaBuiltinConstantArgPower2(TheCall, 0);
3464   case PPC::BI__builtin_ppc_rdlam:
3465     return SemaValueIsRunOfOnes(TheCall, 2);
3466   case PPC::BI__builtin_ppc_icbt:
3467   case PPC::BI__builtin_ppc_sthcx:
3468   case PPC::BI__builtin_ppc_stbcx:
3469   case PPC::BI__builtin_ppc_lharx:
3470   case PPC::BI__builtin_ppc_lbarx:
3471     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3472                             diag::err_ppc_builtin_only_on_arch, "8");
3473   case PPC::BI__builtin_vsx_ldrmb:
3474   case PPC::BI__builtin_vsx_strmb:
3475     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3476                             diag::err_ppc_builtin_only_on_arch, "8") ||
3477            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3478   case PPC::BI__builtin_altivec_vcntmbb:
3479   case PPC::BI__builtin_altivec_vcntmbh:
3480   case PPC::BI__builtin_altivec_vcntmbw:
3481   case PPC::BI__builtin_altivec_vcntmbd:
3482     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3483   case PPC::BI__builtin_darn:
3484   case PPC::BI__builtin_darn_raw:
3485   case PPC::BI__builtin_darn_32:
3486     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3487                             diag::err_ppc_builtin_only_on_arch, "9");
3488 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3489   case PPC::BI__builtin_##Name: \
3490     return SemaBuiltinPPCMMACall(TheCall, Types);
3491 #include "clang/Basic/BuiltinsPPC.def"
3492   }
3493   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3494 }
3495 
3496 // Check if the given type is a non-pointer PPC MMA type. This function is used
3497 // in Sema to prevent invalid uses of restricted PPC MMA types.
3498 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3499   if (Type->isPointerType() || Type->isArrayType())
3500     return false;
3501 
3502   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3503 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3504   if (false
3505 #include "clang/Basic/PPCTypes.def"
3506      ) {
3507     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3508     return true;
3509   }
3510   return false;
3511 }
3512 
3513 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3514                                           CallExpr *TheCall) {
3515   // position of memory order and scope arguments in the builtin
3516   unsigned OrderIndex, ScopeIndex;
3517   switch (BuiltinID) {
3518   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3519   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3520   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3521   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3522     OrderIndex = 2;
3523     ScopeIndex = 3;
3524     break;
3525   case AMDGPU::BI__builtin_amdgcn_fence:
3526     OrderIndex = 0;
3527     ScopeIndex = 1;
3528     break;
3529   default:
3530     return false;
3531   }
3532 
3533   ExprResult Arg = TheCall->getArg(OrderIndex);
3534   auto ArgExpr = Arg.get();
3535   Expr::EvalResult ArgResult;
3536 
3537   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3538     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3539            << ArgExpr->getType();
3540   auto Ord = ArgResult.Val.getInt().getZExtValue();
3541 
3542   // Check validity of memory ordering as per C11 / C++11's memody model.
3543   // Only fence needs check. Atomic dec/inc allow all memory orders.
3544   if (!llvm::isValidAtomicOrderingCABI(Ord))
3545     return Diag(ArgExpr->getBeginLoc(),
3546                 diag::warn_atomic_op_has_invalid_memory_order)
3547            << ArgExpr->getSourceRange();
3548   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3549   case llvm::AtomicOrderingCABI::relaxed:
3550   case llvm::AtomicOrderingCABI::consume:
3551     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3552       return Diag(ArgExpr->getBeginLoc(),
3553                   diag::warn_atomic_op_has_invalid_memory_order)
3554              << ArgExpr->getSourceRange();
3555     break;
3556   case llvm::AtomicOrderingCABI::acquire:
3557   case llvm::AtomicOrderingCABI::release:
3558   case llvm::AtomicOrderingCABI::acq_rel:
3559   case llvm::AtomicOrderingCABI::seq_cst:
3560     break;
3561   }
3562 
3563   Arg = TheCall->getArg(ScopeIndex);
3564   ArgExpr = Arg.get();
3565   Expr::EvalResult ArgResult1;
3566   // Check that sync scope is a constant literal
3567   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3568     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3569            << ArgExpr->getType();
3570 
3571   return false;
3572 }
3573 
3574 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3575   llvm::APSInt Result;
3576 
3577   // We can't check the value of a dependent argument.
3578   Expr *Arg = TheCall->getArg(ArgNum);
3579   if (Arg->isTypeDependent() || Arg->isValueDependent())
3580     return false;
3581 
3582   // Check constant-ness first.
3583   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3584     return true;
3585 
3586   int64_t Val = Result.getSExtValue();
3587   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3588     return false;
3589 
3590   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3591          << Arg->getSourceRange();
3592 }
3593 
3594 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3595                                          unsigned BuiltinID,
3596                                          CallExpr *TheCall) {
3597   // CodeGenFunction can also detect this, but this gives a better error
3598   // message.
3599   bool FeatureMissing = false;
3600   SmallVector<StringRef> ReqFeatures;
3601   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3602   Features.split(ReqFeatures, ',');
3603 
3604   // Check if each required feature is included
3605   for (StringRef F : ReqFeatures) {
3606     if (TI.hasFeature(F))
3607       continue;
3608 
3609     // If the feature is 64bit, alter the string so it will print better in
3610     // the diagnostic.
3611     if (F == "64bit")
3612       F = "RV64";
3613 
3614     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3615     F.consume_front("experimental-");
3616     std::string FeatureStr = F.str();
3617     FeatureStr[0] = std::toupper(FeatureStr[0]);
3618 
3619     // Error message
3620     FeatureMissing = true;
3621     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3622         << TheCall->getSourceRange() << StringRef(FeatureStr);
3623   }
3624 
3625   if (FeatureMissing)
3626     return true;
3627 
3628   switch (BuiltinID) {
3629   case RISCV::BI__builtin_rvv_vsetvli:
3630     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3631            CheckRISCVLMUL(TheCall, 2);
3632   case RISCV::BI__builtin_rvv_vsetvlimax:
3633     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3634            CheckRISCVLMUL(TheCall, 1);
3635   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3636   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3637   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3638   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3639   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3640   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3641   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3642   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3643   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3644   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3645   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3646   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3647   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3648   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3649   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3650   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3651   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3652   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3653   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3654   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3655   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3656   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3657   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3658   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3659   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3660   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3661   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3662   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3663   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3664   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3665     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3666   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3667   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3668   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3669   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3670   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3671   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3672   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3673   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3674   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3675   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3676   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3677   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3678   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3679   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3680   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3681   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3682   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3683   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3684   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3685   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3686     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3687   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3688   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3689   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3690   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3691   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3692   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3693   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3694   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3695   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3696   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3697     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3698   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3699   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3700   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3701   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3702   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3703   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3704   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3705   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3706   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3707   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3708   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3709   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3710   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3711   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3712   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3713   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3714   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3715   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3716   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3717   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3718   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3719   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3720   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3721   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3722   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3723   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3724   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3725   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3726   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3727   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3728     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3729   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3730   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3731   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3732   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3733   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3734   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3735   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3736   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3737   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3738   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3739   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3740   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3741   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3742   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3743   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3744   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3745   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3746   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3747   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3748   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3749     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3750   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3751   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3752   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3753   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3754   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3755   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3756   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3757   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3758   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3759   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3760     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3761   }
3762 
3763   return false;
3764 }
3765 
3766 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3767                                            CallExpr *TheCall) {
3768   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3769     Expr *Arg = TheCall->getArg(0);
3770     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3771       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3772         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3773                << Arg->getSourceRange();
3774   }
3775 
3776   // For intrinsics which take an immediate value as part of the instruction,
3777   // range check them here.
3778   unsigned i = 0, l = 0, u = 0;
3779   switch (BuiltinID) {
3780   default: return false;
3781   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3782   case SystemZ::BI__builtin_s390_verimb:
3783   case SystemZ::BI__builtin_s390_verimh:
3784   case SystemZ::BI__builtin_s390_verimf:
3785   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3786   case SystemZ::BI__builtin_s390_vfaeb:
3787   case SystemZ::BI__builtin_s390_vfaeh:
3788   case SystemZ::BI__builtin_s390_vfaef:
3789   case SystemZ::BI__builtin_s390_vfaebs:
3790   case SystemZ::BI__builtin_s390_vfaehs:
3791   case SystemZ::BI__builtin_s390_vfaefs:
3792   case SystemZ::BI__builtin_s390_vfaezb:
3793   case SystemZ::BI__builtin_s390_vfaezh:
3794   case SystemZ::BI__builtin_s390_vfaezf:
3795   case SystemZ::BI__builtin_s390_vfaezbs:
3796   case SystemZ::BI__builtin_s390_vfaezhs:
3797   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3798   case SystemZ::BI__builtin_s390_vfisb:
3799   case SystemZ::BI__builtin_s390_vfidb:
3800     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3801            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3802   case SystemZ::BI__builtin_s390_vftcisb:
3803   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3804   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3805   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3806   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3807   case SystemZ::BI__builtin_s390_vstrcb:
3808   case SystemZ::BI__builtin_s390_vstrch:
3809   case SystemZ::BI__builtin_s390_vstrcf:
3810   case SystemZ::BI__builtin_s390_vstrczb:
3811   case SystemZ::BI__builtin_s390_vstrczh:
3812   case SystemZ::BI__builtin_s390_vstrczf:
3813   case SystemZ::BI__builtin_s390_vstrcbs:
3814   case SystemZ::BI__builtin_s390_vstrchs:
3815   case SystemZ::BI__builtin_s390_vstrcfs:
3816   case SystemZ::BI__builtin_s390_vstrczbs:
3817   case SystemZ::BI__builtin_s390_vstrczhs:
3818   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3819   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3820   case SystemZ::BI__builtin_s390_vfminsb:
3821   case SystemZ::BI__builtin_s390_vfmaxsb:
3822   case SystemZ::BI__builtin_s390_vfmindb:
3823   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3824   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3825   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3826   case SystemZ::BI__builtin_s390_vclfnhs:
3827   case SystemZ::BI__builtin_s390_vclfnls:
3828   case SystemZ::BI__builtin_s390_vcfn:
3829   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3830   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3831   }
3832   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3833 }
3834 
3835 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3836 /// This checks that the target supports __builtin_cpu_supports and
3837 /// that the string argument is constant and valid.
3838 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3839                                    CallExpr *TheCall) {
3840   Expr *Arg = TheCall->getArg(0);
3841 
3842   // Check if the argument is a string literal.
3843   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3844     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3845            << Arg->getSourceRange();
3846 
3847   // Check the contents of the string.
3848   StringRef Feature =
3849       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3850   if (!TI.validateCpuSupports(Feature))
3851     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3852            << Arg->getSourceRange();
3853   return false;
3854 }
3855 
3856 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3857 /// This checks that the target supports __builtin_cpu_is and
3858 /// that the string argument is constant and valid.
3859 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3860   Expr *Arg = TheCall->getArg(0);
3861 
3862   // Check if the argument is a string literal.
3863   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3864     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3865            << Arg->getSourceRange();
3866 
3867   // Check the contents of the string.
3868   StringRef Feature =
3869       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3870   if (!TI.validateCpuIs(Feature))
3871     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3872            << Arg->getSourceRange();
3873   return false;
3874 }
3875 
3876 // Check if the rounding mode is legal.
3877 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3878   // Indicates if this instruction has rounding control or just SAE.
3879   bool HasRC = false;
3880 
3881   unsigned ArgNum = 0;
3882   switch (BuiltinID) {
3883   default:
3884     return false;
3885   case X86::BI__builtin_ia32_vcvttsd2si32:
3886   case X86::BI__builtin_ia32_vcvttsd2si64:
3887   case X86::BI__builtin_ia32_vcvttsd2usi32:
3888   case X86::BI__builtin_ia32_vcvttsd2usi64:
3889   case X86::BI__builtin_ia32_vcvttss2si32:
3890   case X86::BI__builtin_ia32_vcvttss2si64:
3891   case X86::BI__builtin_ia32_vcvttss2usi32:
3892   case X86::BI__builtin_ia32_vcvttss2usi64:
3893   case X86::BI__builtin_ia32_vcvttsh2si32:
3894   case X86::BI__builtin_ia32_vcvttsh2si64:
3895   case X86::BI__builtin_ia32_vcvttsh2usi32:
3896   case X86::BI__builtin_ia32_vcvttsh2usi64:
3897     ArgNum = 1;
3898     break;
3899   case X86::BI__builtin_ia32_maxpd512:
3900   case X86::BI__builtin_ia32_maxps512:
3901   case X86::BI__builtin_ia32_minpd512:
3902   case X86::BI__builtin_ia32_minps512:
3903   case X86::BI__builtin_ia32_maxph512:
3904   case X86::BI__builtin_ia32_minph512:
3905     ArgNum = 2;
3906     break;
3907   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3908   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3909   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3910   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3911   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3912   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3913   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3914   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3915   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3916   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3917   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3918   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3919   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3920   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3921   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3922   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3923   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3924   case X86::BI__builtin_ia32_exp2pd_mask:
3925   case X86::BI__builtin_ia32_exp2ps_mask:
3926   case X86::BI__builtin_ia32_getexppd512_mask:
3927   case X86::BI__builtin_ia32_getexpps512_mask:
3928   case X86::BI__builtin_ia32_getexpph512_mask:
3929   case X86::BI__builtin_ia32_rcp28pd_mask:
3930   case X86::BI__builtin_ia32_rcp28ps_mask:
3931   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3932   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3933   case X86::BI__builtin_ia32_vcomisd:
3934   case X86::BI__builtin_ia32_vcomiss:
3935   case X86::BI__builtin_ia32_vcomish:
3936   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3937     ArgNum = 3;
3938     break;
3939   case X86::BI__builtin_ia32_cmppd512_mask:
3940   case X86::BI__builtin_ia32_cmpps512_mask:
3941   case X86::BI__builtin_ia32_cmpsd_mask:
3942   case X86::BI__builtin_ia32_cmpss_mask:
3943   case X86::BI__builtin_ia32_cmpsh_mask:
3944   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3945   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3946   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3947   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3948   case X86::BI__builtin_ia32_getexpss128_round_mask:
3949   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3950   case X86::BI__builtin_ia32_getmantpd512_mask:
3951   case X86::BI__builtin_ia32_getmantps512_mask:
3952   case X86::BI__builtin_ia32_getmantph512_mask:
3953   case X86::BI__builtin_ia32_maxsd_round_mask:
3954   case X86::BI__builtin_ia32_maxss_round_mask:
3955   case X86::BI__builtin_ia32_maxsh_round_mask:
3956   case X86::BI__builtin_ia32_minsd_round_mask:
3957   case X86::BI__builtin_ia32_minss_round_mask:
3958   case X86::BI__builtin_ia32_minsh_round_mask:
3959   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3960   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3961   case X86::BI__builtin_ia32_reducepd512_mask:
3962   case X86::BI__builtin_ia32_reduceps512_mask:
3963   case X86::BI__builtin_ia32_reduceph512_mask:
3964   case X86::BI__builtin_ia32_rndscalepd_mask:
3965   case X86::BI__builtin_ia32_rndscaleps_mask:
3966   case X86::BI__builtin_ia32_rndscaleph_mask:
3967   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3968   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3969     ArgNum = 4;
3970     break;
3971   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3972   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3973   case X86::BI__builtin_ia32_fixupimmps512_mask:
3974   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3975   case X86::BI__builtin_ia32_fixupimmsd_mask:
3976   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3977   case X86::BI__builtin_ia32_fixupimmss_mask:
3978   case X86::BI__builtin_ia32_fixupimmss_maskz:
3979   case X86::BI__builtin_ia32_getmantsd_round_mask:
3980   case X86::BI__builtin_ia32_getmantss_round_mask:
3981   case X86::BI__builtin_ia32_getmantsh_round_mask:
3982   case X86::BI__builtin_ia32_rangepd512_mask:
3983   case X86::BI__builtin_ia32_rangeps512_mask:
3984   case X86::BI__builtin_ia32_rangesd128_round_mask:
3985   case X86::BI__builtin_ia32_rangess128_round_mask:
3986   case X86::BI__builtin_ia32_reducesd_mask:
3987   case X86::BI__builtin_ia32_reducess_mask:
3988   case X86::BI__builtin_ia32_reducesh_mask:
3989   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3990   case X86::BI__builtin_ia32_rndscaless_round_mask:
3991   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3992     ArgNum = 5;
3993     break;
3994   case X86::BI__builtin_ia32_vcvtsd2si64:
3995   case X86::BI__builtin_ia32_vcvtsd2si32:
3996   case X86::BI__builtin_ia32_vcvtsd2usi32:
3997   case X86::BI__builtin_ia32_vcvtsd2usi64:
3998   case X86::BI__builtin_ia32_vcvtss2si32:
3999   case X86::BI__builtin_ia32_vcvtss2si64:
4000   case X86::BI__builtin_ia32_vcvtss2usi32:
4001   case X86::BI__builtin_ia32_vcvtss2usi64:
4002   case X86::BI__builtin_ia32_vcvtsh2si32:
4003   case X86::BI__builtin_ia32_vcvtsh2si64:
4004   case X86::BI__builtin_ia32_vcvtsh2usi32:
4005   case X86::BI__builtin_ia32_vcvtsh2usi64:
4006   case X86::BI__builtin_ia32_sqrtpd512:
4007   case X86::BI__builtin_ia32_sqrtps512:
4008   case X86::BI__builtin_ia32_sqrtph512:
4009     ArgNum = 1;
4010     HasRC = true;
4011     break;
4012   case X86::BI__builtin_ia32_addph512:
4013   case X86::BI__builtin_ia32_divph512:
4014   case X86::BI__builtin_ia32_mulph512:
4015   case X86::BI__builtin_ia32_subph512:
4016   case X86::BI__builtin_ia32_addpd512:
4017   case X86::BI__builtin_ia32_addps512:
4018   case X86::BI__builtin_ia32_divpd512:
4019   case X86::BI__builtin_ia32_divps512:
4020   case X86::BI__builtin_ia32_mulpd512:
4021   case X86::BI__builtin_ia32_mulps512:
4022   case X86::BI__builtin_ia32_subpd512:
4023   case X86::BI__builtin_ia32_subps512:
4024   case X86::BI__builtin_ia32_cvtsi2sd64:
4025   case X86::BI__builtin_ia32_cvtsi2ss32:
4026   case X86::BI__builtin_ia32_cvtsi2ss64:
4027   case X86::BI__builtin_ia32_cvtusi2sd64:
4028   case X86::BI__builtin_ia32_cvtusi2ss32:
4029   case X86::BI__builtin_ia32_cvtusi2ss64:
4030   case X86::BI__builtin_ia32_vcvtusi2sh:
4031   case X86::BI__builtin_ia32_vcvtusi642sh:
4032   case X86::BI__builtin_ia32_vcvtsi2sh:
4033   case X86::BI__builtin_ia32_vcvtsi642sh:
4034     ArgNum = 2;
4035     HasRC = true;
4036     break;
4037   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4038   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4039   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4040   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4041   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4042   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4043   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4044   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4045   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4046   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4047   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4048   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4049   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4050   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4051   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4052   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4053   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4054   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4055   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4056   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4057   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4058   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4059   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4060   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4061   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4062   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4063   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4064   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4065   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4066     ArgNum = 3;
4067     HasRC = true;
4068     break;
4069   case X86::BI__builtin_ia32_addsh_round_mask:
4070   case X86::BI__builtin_ia32_addss_round_mask:
4071   case X86::BI__builtin_ia32_addsd_round_mask:
4072   case X86::BI__builtin_ia32_divsh_round_mask:
4073   case X86::BI__builtin_ia32_divss_round_mask:
4074   case X86::BI__builtin_ia32_divsd_round_mask:
4075   case X86::BI__builtin_ia32_mulsh_round_mask:
4076   case X86::BI__builtin_ia32_mulss_round_mask:
4077   case X86::BI__builtin_ia32_mulsd_round_mask:
4078   case X86::BI__builtin_ia32_subsh_round_mask:
4079   case X86::BI__builtin_ia32_subss_round_mask:
4080   case X86::BI__builtin_ia32_subsd_round_mask:
4081   case X86::BI__builtin_ia32_scalefph512_mask:
4082   case X86::BI__builtin_ia32_scalefpd512_mask:
4083   case X86::BI__builtin_ia32_scalefps512_mask:
4084   case X86::BI__builtin_ia32_scalefsd_round_mask:
4085   case X86::BI__builtin_ia32_scalefss_round_mask:
4086   case X86::BI__builtin_ia32_scalefsh_round_mask:
4087   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4088   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4089   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4090   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4091   case X86::BI__builtin_ia32_sqrtss_round_mask:
4092   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4093   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4094   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4095   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4096   case X86::BI__builtin_ia32_vfmaddss3_mask:
4097   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4098   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4099   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4100   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4101   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4102   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4103   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4104   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4105   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4106   case X86::BI__builtin_ia32_vfmaddps512_mask:
4107   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4108   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4109   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4110   case X86::BI__builtin_ia32_vfmaddph512_mask:
4111   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4112   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4113   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4114   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4115   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4116   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4117   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4118   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4119   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4120   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4121   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4122   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4123   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4124   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4125   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4126   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4127   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4128   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4129   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4130   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4131   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4132   case X86::BI__builtin_ia32_vfmulcsh_mask:
4133   case X86::BI__builtin_ia32_vfmulcph512_mask:
4134   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4135   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4136     ArgNum = 4;
4137     HasRC = true;
4138     break;
4139   }
4140 
4141   llvm::APSInt Result;
4142 
4143   // We can't check the value of a dependent argument.
4144   Expr *Arg = TheCall->getArg(ArgNum);
4145   if (Arg->isTypeDependent() || Arg->isValueDependent())
4146     return false;
4147 
4148   // Check constant-ness first.
4149   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4150     return true;
4151 
4152   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4153   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4154   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4155   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4156   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4157       Result == 8/*ROUND_NO_EXC*/ ||
4158       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4159       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4160     return false;
4161 
4162   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4163          << Arg->getSourceRange();
4164 }
4165 
4166 // Check if the gather/scatter scale is legal.
4167 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4168                                              CallExpr *TheCall) {
4169   unsigned ArgNum = 0;
4170   switch (BuiltinID) {
4171   default:
4172     return false;
4173   case X86::BI__builtin_ia32_gatherpfdpd:
4174   case X86::BI__builtin_ia32_gatherpfdps:
4175   case X86::BI__builtin_ia32_gatherpfqpd:
4176   case X86::BI__builtin_ia32_gatherpfqps:
4177   case X86::BI__builtin_ia32_scatterpfdpd:
4178   case X86::BI__builtin_ia32_scatterpfdps:
4179   case X86::BI__builtin_ia32_scatterpfqpd:
4180   case X86::BI__builtin_ia32_scatterpfqps:
4181     ArgNum = 3;
4182     break;
4183   case X86::BI__builtin_ia32_gatherd_pd:
4184   case X86::BI__builtin_ia32_gatherd_pd256:
4185   case X86::BI__builtin_ia32_gatherq_pd:
4186   case X86::BI__builtin_ia32_gatherq_pd256:
4187   case X86::BI__builtin_ia32_gatherd_ps:
4188   case X86::BI__builtin_ia32_gatherd_ps256:
4189   case X86::BI__builtin_ia32_gatherq_ps:
4190   case X86::BI__builtin_ia32_gatherq_ps256:
4191   case X86::BI__builtin_ia32_gatherd_q:
4192   case X86::BI__builtin_ia32_gatherd_q256:
4193   case X86::BI__builtin_ia32_gatherq_q:
4194   case X86::BI__builtin_ia32_gatherq_q256:
4195   case X86::BI__builtin_ia32_gatherd_d:
4196   case X86::BI__builtin_ia32_gatherd_d256:
4197   case X86::BI__builtin_ia32_gatherq_d:
4198   case X86::BI__builtin_ia32_gatherq_d256:
4199   case X86::BI__builtin_ia32_gather3div2df:
4200   case X86::BI__builtin_ia32_gather3div2di:
4201   case X86::BI__builtin_ia32_gather3div4df:
4202   case X86::BI__builtin_ia32_gather3div4di:
4203   case X86::BI__builtin_ia32_gather3div4sf:
4204   case X86::BI__builtin_ia32_gather3div4si:
4205   case X86::BI__builtin_ia32_gather3div8sf:
4206   case X86::BI__builtin_ia32_gather3div8si:
4207   case X86::BI__builtin_ia32_gather3siv2df:
4208   case X86::BI__builtin_ia32_gather3siv2di:
4209   case X86::BI__builtin_ia32_gather3siv4df:
4210   case X86::BI__builtin_ia32_gather3siv4di:
4211   case X86::BI__builtin_ia32_gather3siv4sf:
4212   case X86::BI__builtin_ia32_gather3siv4si:
4213   case X86::BI__builtin_ia32_gather3siv8sf:
4214   case X86::BI__builtin_ia32_gather3siv8si:
4215   case X86::BI__builtin_ia32_gathersiv8df:
4216   case X86::BI__builtin_ia32_gathersiv16sf:
4217   case X86::BI__builtin_ia32_gatherdiv8df:
4218   case X86::BI__builtin_ia32_gatherdiv16sf:
4219   case X86::BI__builtin_ia32_gathersiv8di:
4220   case X86::BI__builtin_ia32_gathersiv16si:
4221   case X86::BI__builtin_ia32_gatherdiv8di:
4222   case X86::BI__builtin_ia32_gatherdiv16si:
4223   case X86::BI__builtin_ia32_scatterdiv2df:
4224   case X86::BI__builtin_ia32_scatterdiv2di:
4225   case X86::BI__builtin_ia32_scatterdiv4df:
4226   case X86::BI__builtin_ia32_scatterdiv4di:
4227   case X86::BI__builtin_ia32_scatterdiv4sf:
4228   case X86::BI__builtin_ia32_scatterdiv4si:
4229   case X86::BI__builtin_ia32_scatterdiv8sf:
4230   case X86::BI__builtin_ia32_scatterdiv8si:
4231   case X86::BI__builtin_ia32_scattersiv2df:
4232   case X86::BI__builtin_ia32_scattersiv2di:
4233   case X86::BI__builtin_ia32_scattersiv4df:
4234   case X86::BI__builtin_ia32_scattersiv4di:
4235   case X86::BI__builtin_ia32_scattersiv4sf:
4236   case X86::BI__builtin_ia32_scattersiv4si:
4237   case X86::BI__builtin_ia32_scattersiv8sf:
4238   case X86::BI__builtin_ia32_scattersiv8si:
4239   case X86::BI__builtin_ia32_scattersiv8df:
4240   case X86::BI__builtin_ia32_scattersiv16sf:
4241   case X86::BI__builtin_ia32_scatterdiv8df:
4242   case X86::BI__builtin_ia32_scatterdiv16sf:
4243   case X86::BI__builtin_ia32_scattersiv8di:
4244   case X86::BI__builtin_ia32_scattersiv16si:
4245   case X86::BI__builtin_ia32_scatterdiv8di:
4246   case X86::BI__builtin_ia32_scatterdiv16si:
4247     ArgNum = 4;
4248     break;
4249   }
4250 
4251   llvm::APSInt Result;
4252 
4253   // We can't check the value of a dependent argument.
4254   Expr *Arg = TheCall->getArg(ArgNum);
4255   if (Arg->isTypeDependent() || Arg->isValueDependent())
4256     return false;
4257 
4258   // Check constant-ness first.
4259   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4260     return true;
4261 
4262   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4263     return false;
4264 
4265   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4266          << Arg->getSourceRange();
4267 }
4268 
4269 enum { TileRegLow = 0, TileRegHigh = 7 };
4270 
4271 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4272                                              ArrayRef<int> ArgNums) {
4273   for (int ArgNum : ArgNums) {
4274     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4275       return true;
4276   }
4277   return false;
4278 }
4279 
4280 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4281                                         ArrayRef<int> ArgNums) {
4282   // Because the max number of tile register is TileRegHigh + 1, so here we use
4283   // each bit to represent the usage of them in bitset.
4284   std::bitset<TileRegHigh + 1> ArgValues;
4285   for (int ArgNum : ArgNums) {
4286     Expr *Arg = TheCall->getArg(ArgNum);
4287     if (Arg->isTypeDependent() || Arg->isValueDependent())
4288       continue;
4289 
4290     llvm::APSInt Result;
4291     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4292       return true;
4293     int ArgExtValue = Result.getExtValue();
4294     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4295            "Incorrect tile register num.");
4296     if (ArgValues.test(ArgExtValue))
4297       return Diag(TheCall->getBeginLoc(),
4298                   diag::err_x86_builtin_tile_arg_duplicate)
4299              << TheCall->getArg(ArgNum)->getSourceRange();
4300     ArgValues.set(ArgExtValue);
4301   }
4302   return false;
4303 }
4304 
4305 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4306                                                 ArrayRef<int> ArgNums) {
4307   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4308          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4309 }
4310 
4311 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4312   switch (BuiltinID) {
4313   default:
4314     return false;
4315   case X86::BI__builtin_ia32_tileloadd64:
4316   case X86::BI__builtin_ia32_tileloaddt164:
4317   case X86::BI__builtin_ia32_tilestored64:
4318   case X86::BI__builtin_ia32_tilezero:
4319     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4320   case X86::BI__builtin_ia32_tdpbssd:
4321   case X86::BI__builtin_ia32_tdpbsud:
4322   case X86::BI__builtin_ia32_tdpbusd:
4323   case X86::BI__builtin_ia32_tdpbuud:
4324   case X86::BI__builtin_ia32_tdpbf16ps:
4325     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4326   }
4327 }
4328 static bool isX86_32Builtin(unsigned BuiltinID) {
4329   // These builtins only work on x86-32 targets.
4330   switch (BuiltinID) {
4331   case X86::BI__builtin_ia32_readeflags_u32:
4332   case X86::BI__builtin_ia32_writeeflags_u32:
4333     return true;
4334   }
4335 
4336   return false;
4337 }
4338 
4339 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4340                                        CallExpr *TheCall) {
4341   if (BuiltinID == X86::BI__builtin_cpu_supports)
4342     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4343 
4344   if (BuiltinID == X86::BI__builtin_cpu_is)
4345     return SemaBuiltinCpuIs(*this, TI, TheCall);
4346 
4347   // Check for 32-bit only builtins on a 64-bit target.
4348   const llvm::Triple &TT = TI.getTriple();
4349   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4350     return Diag(TheCall->getCallee()->getBeginLoc(),
4351                 diag::err_32_bit_builtin_64_bit_tgt);
4352 
4353   // If the intrinsic has rounding or SAE make sure its valid.
4354   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4355     return true;
4356 
4357   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4358   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4359     return true;
4360 
4361   // If the intrinsic has a tile arguments, make sure they are valid.
4362   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4363     return true;
4364 
4365   // For intrinsics which take an immediate value as part of the instruction,
4366   // range check them here.
4367   int i = 0, l = 0, u = 0;
4368   switch (BuiltinID) {
4369   default:
4370     return false;
4371   case X86::BI__builtin_ia32_vec_ext_v2si:
4372   case X86::BI__builtin_ia32_vec_ext_v2di:
4373   case X86::BI__builtin_ia32_vextractf128_pd256:
4374   case X86::BI__builtin_ia32_vextractf128_ps256:
4375   case X86::BI__builtin_ia32_vextractf128_si256:
4376   case X86::BI__builtin_ia32_extract128i256:
4377   case X86::BI__builtin_ia32_extractf64x4_mask:
4378   case X86::BI__builtin_ia32_extracti64x4_mask:
4379   case X86::BI__builtin_ia32_extractf32x8_mask:
4380   case X86::BI__builtin_ia32_extracti32x8_mask:
4381   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4382   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4383   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4384   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4385     i = 1; l = 0; u = 1;
4386     break;
4387   case X86::BI__builtin_ia32_vec_set_v2di:
4388   case X86::BI__builtin_ia32_vinsertf128_pd256:
4389   case X86::BI__builtin_ia32_vinsertf128_ps256:
4390   case X86::BI__builtin_ia32_vinsertf128_si256:
4391   case X86::BI__builtin_ia32_insert128i256:
4392   case X86::BI__builtin_ia32_insertf32x8:
4393   case X86::BI__builtin_ia32_inserti32x8:
4394   case X86::BI__builtin_ia32_insertf64x4:
4395   case X86::BI__builtin_ia32_inserti64x4:
4396   case X86::BI__builtin_ia32_insertf64x2_256:
4397   case X86::BI__builtin_ia32_inserti64x2_256:
4398   case X86::BI__builtin_ia32_insertf32x4_256:
4399   case X86::BI__builtin_ia32_inserti32x4_256:
4400     i = 2; l = 0; u = 1;
4401     break;
4402   case X86::BI__builtin_ia32_vpermilpd:
4403   case X86::BI__builtin_ia32_vec_ext_v4hi:
4404   case X86::BI__builtin_ia32_vec_ext_v4si:
4405   case X86::BI__builtin_ia32_vec_ext_v4sf:
4406   case X86::BI__builtin_ia32_vec_ext_v4di:
4407   case X86::BI__builtin_ia32_extractf32x4_mask:
4408   case X86::BI__builtin_ia32_extracti32x4_mask:
4409   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4410   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4411     i = 1; l = 0; u = 3;
4412     break;
4413   case X86::BI_mm_prefetch:
4414   case X86::BI__builtin_ia32_vec_ext_v8hi:
4415   case X86::BI__builtin_ia32_vec_ext_v8si:
4416     i = 1; l = 0; u = 7;
4417     break;
4418   case X86::BI__builtin_ia32_sha1rnds4:
4419   case X86::BI__builtin_ia32_blendpd:
4420   case X86::BI__builtin_ia32_shufpd:
4421   case X86::BI__builtin_ia32_vec_set_v4hi:
4422   case X86::BI__builtin_ia32_vec_set_v4si:
4423   case X86::BI__builtin_ia32_vec_set_v4di:
4424   case X86::BI__builtin_ia32_shuf_f32x4_256:
4425   case X86::BI__builtin_ia32_shuf_f64x2_256:
4426   case X86::BI__builtin_ia32_shuf_i32x4_256:
4427   case X86::BI__builtin_ia32_shuf_i64x2_256:
4428   case X86::BI__builtin_ia32_insertf64x2_512:
4429   case X86::BI__builtin_ia32_inserti64x2_512:
4430   case X86::BI__builtin_ia32_insertf32x4:
4431   case X86::BI__builtin_ia32_inserti32x4:
4432     i = 2; l = 0; u = 3;
4433     break;
4434   case X86::BI__builtin_ia32_vpermil2pd:
4435   case X86::BI__builtin_ia32_vpermil2pd256:
4436   case X86::BI__builtin_ia32_vpermil2ps:
4437   case X86::BI__builtin_ia32_vpermil2ps256:
4438     i = 3; l = 0; u = 3;
4439     break;
4440   case X86::BI__builtin_ia32_cmpb128_mask:
4441   case X86::BI__builtin_ia32_cmpw128_mask:
4442   case X86::BI__builtin_ia32_cmpd128_mask:
4443   case X86::BI__builtin_ia32_cmpq128_mask:
4444   case X86::BI__builtin_ia32_cmpb256_mask:
4445   case X86::BI__builtin_ia32_cmpw256_mask:
4446   case X86::BI__builtin_ia32_cmpd256_mask:
4447   case X86::BI__builtin_ia32_cmpq256_mask:
4448   case X86::BI__builtin_ia32_cmpb512_mask:
4449   case X86::BI__builtin_ia32_cmpw512_mask:
4450   case X86::BI__builtin_ia32_cmpd512_mask:
4451   case X86::BI__builtin_ia32_cmpq512_mask:
4452   case X86::BI__builtin_ia32_ucmpb128_mask:
4453   case X86::BI__builtin_ia32_ucmpw128_mask:
4454   case X86::BI__builtin_ia32_ucmpd128_mask:
4455   case X86::BI__builtin_ia32_ucmpq128_mask:
4456   case X86::BI__builtin_ia32_ucmpb256_mask:
4457   case X86::BI__builtin_ia32_ucmpw256_mask:
4458   case X86::BI__builtin_ia32_ucmpd256_mask:
4459   case X86::BI__builtin_ia32_ucmpq256_mask:
4460   case X86::BI__builtin_ia32_ucmpb512_mask:
4461   case X86::BI__builtin_ia32_ucmpw512_mask:
4462   case X86::BI__builtin_ia32_ucmpd512_mask:
4463   case X86::BI__builtin_ia32_ucmpq512_mask:
4464   case X86::BI__builtin_ia32_vpcomub:
4465   case X86::BI__builtin_ia32_vpcomuw:
4466   case X86::BI__builtin_ia32_vpcomud:
4467   case X86::BI__builtin_ia32_vpcomuq:
4468   case X86::BI__builtin_ia32_vpcomb:
4469   case X86::BI__builtin_ia32_vpcomw:
4470   case X86::BI__builtin_ia32_vpcomd:
4471   case X86::BI__builtin_ia32_vpcomq:
4472   case X86::BI__builtin_ia32_vec_set_v8hi:
4473   case X86::BI__builtin_ia32_vec_set_v8si:
4474     i = 2; l = 0; u = 7;
4475     break;
4476   case X86::BI__builtin_ia32_vpermilpd256:
4477   case X86::BI__builtin_ia32_roundps:
4478   case X86::BI__builtin_ia32_roundpd:
4479   case X86::BI__builtin_ia32_roundps256:
4480   case X86::BI__builtin_ia32_roundpd256:
4481   case X86::BI__builtin_ia32_getmantpd128_mask:
4482   case X86::BI__builtin_ia32_getmantpd256_mask:
4483   case X86::BI__builtin_ia32_getmantps128_mask:
4484   case X86::BI__builtin_ia32_getmantps256_mask:
4485   case X86::BI__builtin_ia32_getmantpd512_mask:
4486   case X86::BI__builtin_ia32_getmantps512_mask:
4487   case X86::BI__builtin_ia32_getmantph128_mask:
4488   case X86::BI__builtin_ia32_getmantph256_mask:
4489   case X86::BI__builtin_ia32_getmantph512_mask:
4490   case X86::BI__builtin_ia32_vec_ext_v16qi:
4491   case X86::BI__builtin_ia32_vec_ext_v16hi:
4492     i = 1; l = 0; u = 15;
4493     break;
4494   case X86::BI__builtin_ia32_pblendd128:
4495   case X86::BI__builtin_ia32_blendps:
4496   case X86::BI__builtin_ia32_blendpd256:
4497   case X86::BI__builtin_ia32_shufpd256:
4498   case X86::BI__builtin_ia32_roundss:
4499   case X86::BI__builtin_ia32_roundsd:
4500   case X86::BI__builtin_ia32_rangepd128_mask:
4501   case X86::BI__builtin_ia32_rangepd256_mask:
4502   case X86::BI__builtin_ia32_rangepd512_mask:
4503   case X86::BI__builtin_ia32_rangeps128_mask:
4504   case X86::BI__builtin_ia32_rangeps256_mask:
4505   case X86::BI__builtin_ia32_rangeps512_mask:
4506   case X86::BI__builtin_ia32_getmantsd_round_mask:
4507   case X86::BI__builtin_ia32_getmantss_round_mask:
4508   case X86::BI__builtin_ia32_getmantsh_round_mask:
4509   case X86::BI__builtin_ia32_vec_set_v16qi:
4510   case X86::BI__builtin_ia32_vec_set_v16hi:
4511     i = 2; l = 0; u = 15;
4512     break;
4513   case X86::BI__builtin_ia32_vec_ext_v32qi:
4514     i = 1; l = 0; u = 31;
4515     break;
4516   case X86::BI__builtin_ia32_cmpps:
4517   case X86::BI__builtin_ia32_cmpss:
4518   case X86::BI__builtin_ia32_cmppd:
4519   case X86::BI__builtin_ia32_cmpsd:
4520   case X86::BI__builtin_ia32_cmpps256:
4521   case X86::BI__builtin_ia32_cmppd256:
4522   case X86::BI__builtin_ia32_cmpps128_mask:
4523   case X86::BI__builtin_ia32_cmppd128_mask:
4524   case X86::BI__builtin_ia32_cmpps256_mask:
4525   case X86::BI__builtin_ia32_cmppd256_mask:
4526   case X86::BI__builtin_ia32_cmpps512_mask:
4527   case X86::BI__builtin_ia32_cmppd512_mask:
4528   case X86::BI__builtin_ia32_cmpsd_mask:
4529   case X86::BI__builtin_ia32_cmpss_mask:
4530   case X86::BI__builtin_ia32_vec_set_v32qi:
4531     i = 2; l = 0; u = 31;
4532     break;
4533   case X86::BI__builtin_ia32_permdf256:
4534   case X86::BI__builtin_ia32_permdi256:
4535   case X86::BI__builtin_ia32_permdf512:
4536   case X86::BI__builtin_ia32_permdi512:
4537   case X86::BI__builtin_ia32_vpermilps:
4538   case X86::BI__builtin_ia32_vpermilps256:
4539   case X86::BI__builtin_ia32_vpermilpd512:
4540   case X86::BI__builtin_ia32_vpermilps512:
4541   case X86::BI__builtin_ia32_pshufd:
4542   case X86::BI__builtin_ia32_pshufd256:
4543   case X86::BI__builtin_ia32_pshufd512:
4544   case X86::BI__builtin_ia32_pshufhw:
4545   case X86::BI__builtin_ia32_pshufhw256:
4546   case X86::BI__builtin_ia32_pshufhw512:
4547   case X86::BI__builtin_ia32_pshuflw:
4548   case X86::BI__builtin_ia32_pshuflw256:
4549   case X86::BI__builtin_ia32_pshuflw512:
4550   case X86::BI__builtin_ia32_vcvtps2ph:
4551   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4552   case X86::BI__builtin_ia32_vcvtps2ph256:
4553   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4554   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4555   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4556   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4557   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4558   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4559   case X86::BI__builtin_ia32_rndscaleps_mask:
4560   case X86::BI__builtin_ia32_rndscalepd_mask:
4561   case X86::BI__builtin_ia32_rndscaleph_mask:
4562   case X86::BI__builtin_ia32_reducepd128_mask:
4563   case X86::BI__builtin_ia32_reducepd256_mask:
4564   case X86::BI__builtin_ia32_reducepd512_mask:
4565   case X86::BI__builtin_ia32_reduceps128_mask:
4566   case X86::BI__builtin_ia32_reduceps256_mask:
4567   case X86::BI__builtin_ia32_reduceps512_mask:
4568   case X86::BI__builtin_ia32_reduceph128_mask:
4569   case X86::BI__builtin_ia32_reduceph256_mask:
4570   case X86::BI__builtin_ia32_reduceph512_mask:
4571   case X86::BI__builtin_ia32_prold512:
4572   case X86::BI__builtin_ia32_prolq512:
4573   case X86::BI__builtin_ia32_prold128:
4574   case X86::BI__builtin_ia32_prold256:
4575   case X86::BI__builtin_ia32_prolq128:
4576   case X86::BI__builtin_ia32_prolq256:
4577   case X86::BI__builtin_ia32_prord512:
4578   case X86::BI__builtin_ia32_prorq512:
4579   case X86::BI__builtin_ia32_prord128:
4580   case X86::BI__builtin_ia32_prord256:
4581   case X86::BI__builtin_ia32_prorq128:
4582   case X86::BI__builtin_ia32_prorq256:
4583   case X86::BI__builtin_ia32_fpclasspd128_mask:
4584   case X86::BI__builtin_ia32_fpclasspd256_mask:
4585   case X86::BI__builtin_ia32_fpclassps128_mask:
4586   case X86::BI__builtin_ia32_fpclassps256_mask:
4587   case X86::BI__builtin_ia32_fpclassps512_mask:
4588   case X86::BI__builtin_ia32_fpclasspd512_mask:
4589   case X86::BI__builtin_ia32_fpclassph128_mask:
4590   case X86::BI__builtin_ia32_fpclassph256_mask:
4591   case X86::BI__builtin_ia32_fpclassph512_mask:
4592   case X86::BI__builtin_ia32_fpclasssd_mask:
4593   case X86::BI__builtin_ia32_fpclassss_mask:
4594   case X86::BI__builtin_ia32_fpclasssh_mask:
4595   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4596   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4597   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4598   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4599   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4600   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4601   case X86::BI__builtin_ia32_kshiftliqi:
4602   case X86::BI__builtin_ia32_kshiftlihi:
4603   case X86::BI__builtin_ia32_kshiftlisi:
4604   case X86::BI__builtin_ia32_kshiftlidi:
4605   case X86::BI__builtin_ia32_kshiftriqi:
4606   case X86::BI__builtin_ia32_kshiftrihi:
4607   case X86::BI__builtin_ia32_kshiftrisi:
4608   case X86::BI__builtin_ia32_kshiftridi:
4609     i = 1; l = 0; u = 255;
4610     break;
4611   case X86::BI__builtin_ia32_vperm2f128_pd256:
4612   case X86::BI__builtin_ia32_vperm2f128_ps256:
4613   case X86::BI__builtin_ia32_vperm2f128_si256:
4614   case X86::BI__builtin_ia32_permti256:
4615   case X86::BI__builtin_ia32_pblendw128:
4616   case X86::BI__builtin_ia32_pblendw256:
4617   case X86::BI__builtin_ia32_blendps256:
4618   case X86::BI__builtin_ia32_pblendd256:
4619   case X86::BI__builtin_ia32_palignr128:
4620   case X86::BI__builtin_ia32_palignr256:
4621   case X86::BI__builtin_ia32_palignr512:
4622   case X86::BI__builtin_ia32_alignq512:
4623   case X86::BI__builtin_ia32_alignd512:
4624   case X86::BI__builtin_ia32_alignd128:
4625   case X86::BI__builtin_ia32_alignd256:
4626   case X86::BI__builtin_ia32_alignq128:
4627   case X86::BI__builtin_ia32_alignq256:
4628   case X86::BI__builtin_ia32_vcomisd:
4629   case X86::BI__builtin_ia32_vcomiss:
4630   case X86::BI__builtin_ia32_shuf_f32x4:
4631   case X86::BI__builtin_ia32_shuf_f64x2:
4632   case X86::BI__builtin_ia32_shuf_i32x4:
4633   case X86::BI__builtin_ia32_shuf_i64x2:
4634   case X86::BI__builtin_ia32_shufpd512:
4635   case X86::BI__builtin_ia32_shufps:
4636   case X86::BI__builtin_ia32_shufps256:
4637   case X86::BI__builtin_ia32_shufps512:
4638   case X86::BI__builtin_ia32_dbpsadbw128:
4639   case X86::BI__builtin_ia32_dbpsadbw256:
4640   case X86::BI__builtin_ia32_dbpsadbw512:
4641   case X86::BI__builtin_ia32_vpshldd128:
4642   case X86::BI__builtin_ia32_vpshldd256:
4643   case X86::BI__builtin_ia32_vpshldd512:
4644   case X86::BI__builtin_ia32_vpshldq128:
4645   case X86::BI__builtin_ia32_vpshldq256:
4646   case X86::BI__builtin_ia32_vpshldq512:
4647   case X86::BI__builtin_ia32_vpshldw128:
4648   case X86::BI__builtin_ia32_vpshldw256:
4649   case X86::BI__builtin_ia32_vpshldw512:
4650   case X86::BI__builtin_ia32_vpshrdd128:
4651   case X86::BI__builtin_ia32_vpshrdd256:
4652   case X86::BI__builtin_ia32_vpshrdd512:
4653   case X86::BI__builtin_ia32_vpshrdq128:
4654   case X86::BI__builtin_ia32_vpshrdq256:
4655   case X86::BI__builtin_ia32_vpshrdq512:
4656   case X86::BI__builtin_ia32_vpshrdw128:
4657   case X86::BI__builtin_ia32_vpshrdw256:
4658   case X86::BI__builtin_ia32_vpshrdw512:
4659     i = 2; l = 0; u = 255;
4660     break;
4661   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4662   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4663   case X86::BI__builtin_ia32_fixupimmps512_mask:
4664   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4665   case X86::BI__builtin_ia32_fixupimmsd_mask:
4666   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4667   case X86::BI__builtin_ia32_fixupimmss_mask:
4668   case X86::BI__builtin_ia32_fixupimmss_maskz:
4669   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4670   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4671   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4672   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4673   case X86::BI__builtin_ia32_fixupimmps128_mask:
4674   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4675   case X86::BI__builtin_ia32_fixupimmps256_mask:
4676   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4677   case X86::BI__builtin_ia32_pternlogd512_mask:
4678   case X86::BI__builtin_ia32_pternlogd512_maskz:
4679   case X86::BI__builtin_ia32_pternlogq512_mask:
4680   case X86::BI__builtin_ia32_pternlogq512_maskz:
4681   case X86::BI__builtin_ia32_pternlogd128_mask:
4682   case X86::BI__builtin_ia32_pternlogd128_maskz:
4683   case X86::BI__builtin_ia32_pternlogd256_mask:
4684   case X86::BI__builtin_ia32_pternlogd256_maskz:
4685   case X86::BI__builtin_ia32_pternlogq128_mask:
4686   case X86::BI__builtin_ia32_pternlogq128_maskz:
4687   case X86::BI__builtin_ia32_pternlogq256_mask:
4688   case X86::BI__builtin_ia32_pternlogq256_maskz:
4689     i = 3; l = 0; u = 255;
4690     break;
4691   case X86::BI__builtin_ia32_gatherpfdpd:
4692   case X86::BI__builtin_ia32_gatherpfdps:
4693   case X86::BI__builtin_ia32_gatherpfqpd:
4694   case X86::BI__builtin_ia32_gatherpfqps:
4695   case X86::BI__builtin_ia32_scatterpfdpd:
4696   case X86::BI__builtin_ia32_scatterpfdps:
4697   case X86::BI__builtin_ia32_scatterpfqpd:
4698   case X86::BI__builtin_ia32_scatterpfqps:
4699     i = 4; l = 2; u = 3;
4700     break;
4701   case X86::BI__builtin_ia32_reducesd_mask:
4702   case X86::BI__builtin_ia32_reducess_mask:
4703   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4704   case X86::BI__builtin_ia32_rndscaless_round_mask:
4705   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4706   case X86::BI__builtin_ia32_reducesh_mask:
4707     i = 4; l = 0; u = 255;
4708     break;
4709   }
4710 
4711   // Note that we don't force a hard error on the range check here, allowing
4712   // template-generated or macro-generated dead code to potentially have out-of-
4713   // range values. These need to code generate, but don't need to necessarily
4714   // make any sense. We use a warning that defaults to an error.
4715   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4716 }
4717 
4718 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4719 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4720 /// Returns true when the format fits the function and the FormatStringInfo has
4721 /// been populated.
4722 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4723                                FormatStringInfo *FSI) {
4724   FSI->HasVAListArg = Format->getFirstArg() == 0;
4725   FSI->FormatIdx = Format->getFormatIdx() - 1;
4726   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4727 
4728   // The way the format attribute works in GCC, the implicit this argument
4729   // of member functions is counted. However, it doesn't appear in our own
4730   // lists, so decrement format_idx in that case.
4731   if (IsCXXMember) {
4732     if(FSI->FormatIdx == 0)
4733       return false;
4734     --FSI->FormatIdx;
4735     if (FSI->FirstDataArg != 0)
4736       --FSI->FirstDataArg;
4737   }
4738   return true;
4739 }
4740 
4741 /// Checks if a the given expression evaluates to null.
4742 ///
4743 /// Returns true if the value evaluates to null.
4744 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4745   // If the expression has non-null type, it doesn't evaluate to null.
4746   if (auto nullability
4747         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4748     if (*nullability == NullabilityKind::NonNull)
4749       return false;
4750   }
4751 
4752   // As a special case, transparent unions initialized with zero are
4753   // considered null for the purposes of the nonnull attribute.
4754   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4755     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4756       if (const CompoundLiteralExpr *CLE =
4757           dyn_cast<CompoundLiteralExpr>(Expr))
4758         if (const InitListExpr *ILE =
4759             dyn_cast<InitListExpr>(CLE->getInitializer()))
4760           Expr = ILE->getInit(0);
4761   }
4762 
4763   bool Result;
4764   return (!Expr->isValueDependent() &&
4765           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4766           !Result);
4767 }
4768 
4769 static void CheckNonNullArgument(Sema &S,
4770                                  const Expr *ArgExpr,
4771                                  SourceLocation CallSiteLoc) {
4772   if (CheckNonNullExpr(S, ArgExpr))
4773     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4774                           S.PDiag(diag::warn_null_arg)
4775                               << ArgExpr->getSourceRange());
4776 }
4777 
4778 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4779   FormatStringInfo FSI;
4780   if ((GetFormatStringType(Format) == FST_NSString) &&
4781       getFormatStringInfo(Format, false, &FSI)) {
4782     Idx = FSI.FormatIdx;
4783     return true;
4784   }
4785   return false;
4786 }
4787 
4788 /// Diagnose use of %s directive in an NSString which is being passed
4789 /// as formatting string to formatting method.
4790 static void
4791 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4792                                         const NamedDecl *FDecl,
4793                                         Expr **Args,
4794                                         unsigned NumArgs) {
4795   unsigned Idx = 0;
4796   bool Format = false;
4797   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4798   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4799     Idx = 2;
4800     Format = true;
4801   }
4802   else
4803     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4804       if (S.GetFormatNSStringIdx(I, Idx)) {
4805         Format = true;
4806         break;
4807       }
4808     }
4809   if (!Format || NumArgs <= Idx)
4810     return;
4811   const Expr *FormatExpr = Args[Idx];
4812   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4813     FormatExpr = CSCE->getSubExpr();
4814   const StringLiteral *FormatString;
4815   if (const ObjCStringLiteral *OSL =
4816       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4817     FormatString = OSL->getString();
4818   else
4819     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4820   if (!FormatString)
4821     return;
4822   if (S.FormatStringHasSArg(FormatString)) {
4823     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4824       << "%s" << 1 << 1;
4825     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4826       << FDecl->getDeclName();
4827   }
4828 }
4829 
4830 /// Determine whether the given type has a non-null nullability annotation.
4831 static bool isNonNullType(ASTContext &ctx, QualType type) {
4832   if (auto nullability = type->getNullability(ctx))
4833     return *nullability == NullabilityKind::NonNull;
4834 
4835   return false;
4836 }
4837 
4838 static void CheckNonNullArguments(Sema &S,
4839                                   const NamedDecl *FDecl,
4840                                   const FunctionProtoType *Proto,
4841                                   ArrayRef<const Expr *> Args,
4842                                   SourceLocation CallSiteLoc) {
4843   assert((FDecl || Proto) && "Need a function declaration or prototype");
4844 
4845   // Already checked by by constant evaluator.
4846   if (S.isConstantEvaluated())
4847     return;
4848   // Check the attributes attached to the method/function itself.
4849   llvm::SmallBitVector NonNullArgs;
4850   if (FDecl) {
4851     // Handle the nonnull attribute on the function/method declaration itself.
4852     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4853       if (!NonNull->args_size()) {
4854         // Easy case: all pointer arguments are nonnull.
4855         for (const auto *Arg : Args)
4856           if (S.isValidPointerAttrType(Arg->getType()))
4857             CheckNonNullArgument(S, Arg, CallSiteLoc);
4858         return;
4859       }
4860 
4861       for (const ParamIdx &Idx : NonNull->args()) {
4862         unsigned IdxAST = Idx.getASTIndex();
4863         if (IdxAST >= Args.size())
4864           continue;
4865         if (NonNullArgs.empty())
4866           NonNullArgs.resize(Args.size());
4867         NonNullArgs.set(IdxAST);
4868       }
4869     }
4870   }
4871 
4872   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4873     // Handle the nonnull attribute on the parameters of the
4874     // function/method.
4875     ArrayRef<ParmVarDecl*> parms;
4876     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4877       parms = FD->parameters();
4878     else
4879       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4880 
4881     unsigned ParamIndex = 0;
4882     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4883          I != E; ++I, ++ParamIndex) {
4884       const ParmVarDecl *PVD = *I;
4885       if (PVD->hasAttr<NonNullAttr>() ||
4886           isNonNullType(S.Context, PVD->getType())) {
4887         if (NonNullArgs.empty())
4888           NonNullArgs.resize(Args.size());
4889 
4890         NonNullArgs.set(ParamIndex);
4891       }
4892     }
4893   } else {
4894     // If we have a non-function, non-method declaration but no
4895     // function prototype, try to dig out the function prototype.
4896     if (!Proto) {
4897       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4898         QualType type = VD->getType().getNonReferenceType();
4899         if (auto pointerType = type->getAs<PointerType>())
4900           type = pointerType->getPointeeType();
4901         else if (auto blockType = type->getAs<BlockPointerType>())
4902           type = blockType->getPointeeType();
4903         // FIXME: data member pointers?
4904 
4905         // Dig out the function prototype, if there is one.
4906         Proto = type->getAs<FunctionProtoType>();
4907       }
4908     }
4909 
4910     // Fill in non-null argument information from the nullability
4911     // information on the parameter types (if we have them).
4912     if (Proto) {
4913       unsigned Index = 0;
4914       for (auto paramType : Proto->getParamTypes()) {
4915         if (isNonNullType(S.Context, paramType)) {
4916           if (NonNullArgs.empty())
4917             NonNullArgs.resize(Args.size());
4918 
4919           NonNullArgs.set(Index);
4920         }
4921 
4922         ++Index;
4923       }
4924     }
4925   }
4926 
4927   // Check for non-null arguments.
4928   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4929        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4930     if (NonNullArgs[ArgIndex])
4931       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4932   }
4933 }
4934 
4935 /// Warn if a pointer or reference argument passed to a function points to an
4936 /// object that is less aligned than the parameter. This can happen when
4937 /// creating a typedef with a lower alignment than the original type and then
4938 /// calling functions defined in terms of the original type.
4939 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4940                              StringRef ParamName, QualType ArgTy,
4941                              QualType ParamTy) {
4942 
4943   // If a function accepts a pointer or reference type
4944   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4945     return;
4946 
4947   // If the parameter is a pointer type, get the pointee type for the
4948   // argument too. If the parameter is a reference type, don't try to get
4949   // the pointee type for the argument.
4950   if (ParamTy->isPointerType())
4951     ArgTy = ArgTy->getPointeeType();
4952 
4953   // Remove reference or pointer
4954   ParamTy = ParamTy->getPointeeType();
4955 
4956   // Find expected alignment, and the actual alignment of the passed object.
4957   // getTypeAlignInChars requires complete types
4958   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4959       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4960       ArgTy->isUndeducedType())
4961     return;
4962 
4963   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4964   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4965 
4966   // If the argument is less aligned than the parameter, there is a
4967   // potential alignment issue.
4968   if (ArgAlign < ParamAlign)
4969     Diag(Loc, diag::warn_param_mismatched_alignment)
4970         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4971         << ParamName << FDecl;
4972 }
4973 
4974 /// Handles the checks for format strings, non-POD arguments to vararg
4975 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4976 /// attributes.
4977 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4978                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4979                      bool IsMemberFunction, SourceLocation Loc,
4980                      SourceRange Range, VariadicCallType CallType) {
4981   // FIXME: We should check as much as we can in the template definition.
4982   if (CurContext->isDependentContext())
4983     return;
4984 
4985   // Printf and scanf checking.
4986   llvm::SmallBitVector CheckedVarArgs;
4987   if (FDecl) {
4988     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4989       // Only create vector if there are format attributes.
4990       CheckedVarArgs.resize(Args.size());
4991 
4992       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4993                            CheckedVarArgs);
4994     }
4995   }
4996 
4997   // Refuse POD arguments that weren't caught by the format string
4998   // checks above.
4999   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
5000   if (CallType != VariadicDoesNotApply &&
5001       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
5002     unsigned NumParams = Proto ? Proto->getNumParams()
5003                        : FDecl && isa<FunctionDecl>(FDecl)
5004                            ? cast<FunctionDecl>(FDecl)->getNumParams()
5005                        : FDecl && isa<ObjCMethodDecl>(FDecl)
5006                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
5007                        : 0;
5008 
5009     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
5010       // Args[ArgIdx] can be null in malformed code.
5011       if (const Expr *Arg = Args[ArgIdx]) {
5012         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
5013           checkVariadicArgument(Arg, CallType);
5014       }
5015     }
5016   }
5017 
5018   if (FDecl || Proto) {
5019     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
5020 
5021     // Type safety checking.
5022     if (FDecl) {
5023       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5024         CheckArgumentWithTypeTag(I, Args, Loc);
5025     }
5026   }
5027 
5028   // Check that passed arguments match the alignment of original arguments.
5029   // Try to get the missing prototype from the declaration.
5030   if (!Proto && FDecl) {
5031     const auto *FT = FDecl->getFunctionType();
5032     if (isa_and_nonnull<FunctionProtoType>(FT))
5033       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5034   }
5035   if (Proto) {
5036     // For variadic functions, we may have more args than parameters.
5037     // For some K&R functions, we may have less args than parameters.
5038     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5039     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5040       // Args[ArgIdx] can be null in malformed code.
5041       if (const Expr *Arg = Args[ArgIdx]) {
5042         if (Arg->containsErrors())
5043           continue;
5044 
5045         QualType ParamTy = Proto->getParamType(ArgIdx);
5046         QualType ArgTy = Arg->getType();
5047         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5048                           ArgTy, ParamTy);
5049       }
5050     }
5051   }
5052 
5053   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5054     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5055     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5056     if (!Arg->isValueDependent()) {
5057       Expr::EvalResult Align;
5058       if (Arg->EvaluateAsInt(Align, Context)) {
5059         const llvm::APSInt &I = Align.Val.getInt();
5060         if (!I.isPowerOf2())
5061           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5062               << Arg->getSourceRange();
5063 
5064         if (I > Sema::MaximumAlignment)
5065           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5066               << Arg->getSourceRange() << Sema::MaximumAlignment;
5067       }
5068     }
5069   }
5070 
5071   if (FD)
5072     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5073 }
5074 
5075 /// CheckConstructorCall - Check a constructor call for correctness and safety
5076 /// properties not enforced by the C type system.
5077 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5078                                 ArrayRef<const Expr *> Args,
5079                                 const FunctionProtoType *Proto,
5080                                 SourceLocation Loc) {
5081   VariadicCallType CallType =
5082       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5083 
5084   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5085   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5086                     Context.getPointerType(Ctor->getThisObjectType()));
5087 
5088   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5089             Loc, SourceRange(), CallType);
5090 }
5091 
5092 /// CheckFunctionCall - Check a direct function call for various correctness
5093 /// and safety properties not strictly enforced by the C type system.
5094 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5095                              const FunctionProtoType *Proto) {
5096   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5097                               isa<CXXMethodDecl>(FDecl);
5098   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5099                           IsMemberOperatorCall;
5100   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5101                                                   TheCall->getCallee());
5102   Expr** Args = TheCall->getArgs();
5103   unsigned NumArgs = TheCall->getNumArgs();
5104 
5105   Expr *ImplicitThis = nullptr;
5106   if (IsMemberOperatorCall) {
5107     // If this is a call to a member operator, hide the first argument
5108     // from checkCall.
5109     // FIXME: Our choice of AST representation here is less than ideal.
5110     ImplicitThis = Args[0];
5111     ++Args;
5112     --NumArgs;
5113   } else if (IsMemberFunction)
5114     ImplicitThis =
5115         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5116 
5117   if (ImplicitThis) {
5118     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5119     // used.
5120     QualType ThisType = ImplicitThis->getType();
5121     if (!ThisType->isPointerType()) {
5122       assert(!ThisType->isReferenceType());
5123       ThisType = Context.getPointerType(ThisType);
5124     }
5125 
5126     QualType ThisTypeFromDecl =
5127         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5128 
5129     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5130                       ThisTypeFromDecl);
5131   }
5132 
5133   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5134             IsMemberFunction, TheCall->getRParenLoc(),
5135             TheCall->getCallee()->getSourceRange(), CallType);
5136 
5137   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5138   // None of the checks below are needed for functions that don't have
5139   // simple names (e.g., C++ conversion functions).
5140   if (!FnInfo)
5141     return false;
5142 
5143   CheckTCBEnforcement(TheCall, FDecl);
5144 
5145   CheckAbsoluteValueFunction(TheCall, FDecl);
5146   CheckMaxUnsignedZero(TheCall, FDecl);
5147 
5148   if (getLangOpts().ObjC)
5149     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5150 
5151   unsigned CMId = FDecl->getMemoryFunctionKind();
5152 
5153   // Handle memory setting and copying functions.
5154   switch (CMId) {
5155   case 0:
5156     return false;
5157   case Builtin::BIstrlcpy: // fallthrough
5158   case Builtin::BIstrlcat:
5159     CheckStrlcpycatArguments(TheCall, FnInfo);
5160     break;
5161   case Builtin::BIstrncat:
5162     CheckStrncatArguments(TheCall, FnInfo);
5163     break;
5164   case Builtin::BIfree:
5165     CheckFreeArguments(TheCall);
5166     break;
5167   default:
5168     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5169   }
5170 
5171   return false;
5172 }
5173 
5174 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5175                                ArrayRef<const Expr *> Args) {
5176   VariadicCallType CallType =
5177       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5178 
5179   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5180             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5181             CallType);
5182 
5183   return false;
5184 }
5185 
5186 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5187                             const FunctionProtoType *Proto) {
5188   QualType Ty;
5189   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5190     Ty = V->getType().getNonReferenceType();
5191   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5192     Ty = F->getType().getNonReferenceType();
5193   else
5194     return false;
5195 
5196   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5197       !Ty->isFunctionProtoType())
5198     return false;
5199 
5200   VariadicCallType CallType;
5201   if (!Proto || !Proto->isVariadic()) {
5202     CallType = VariadicDoesNotApply;
5203   } else if (Ty->isBlockPointerType()) {
5204     CallType = VariadicBlock;
5205   } else { // Ty->isFunctionPointerType()
5206     CallType = VariadicFunction;
5207   }
5208 
5209   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5210             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5211             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5212             TheCall->getCallee()->getSourceRange(), CallType);
5213 
5214   return false;
5215 }
5216 
5217 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5218 /// such as function pointers returned from functions.
5219 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5220   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5221                                                   TheCall->getCallee());
5222   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5223             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5224             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5225             TheCall->getCallee()->getSourceRange(), CallType);
5226 
5227   return false;
5228 }
5229 
5230 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5231   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5232     return false;
5233 
5234   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5235   switch (Op) {
5236   case AtomicExpr::AO__c11_atomic_init:
5237   case AtomicExpr::AO__opencl_atomic_init:
5238     llvm_unreachable("There is no ordering argument for an init");
5239 
5240   case AtomicExpr::AO__c11_atomic_load:
5241   case AtomicExpr::AO__opencl_atomic_load:
5242   case AtomicExpr::AO__atomic_load_n:
5243   case AtomicExpr::AO__atomic_load:
5244     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5245            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5246 
5247   case AtomicExpr::AO__c11_atomic_store:
5248   case AtomicExpr::AO__opencl_atomic_store:
5249   case AtomicExpr::AO__atomic_store:
5250   case AtomicExpr::AO__atomic_store_n:
5251     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5252            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5253            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5254 
5255   default:
5256     return true;
5257   }
5258 }
5259 
5260 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5261                                          AtomicExpr::AtomicOp Op) {
5262   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5263   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5264   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5265   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5266                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5267                          Op);
5268 }
5269 
5270 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5271                                  SourceLocation RParenLoc, MultiExprArg Args,
5272                                  AtomicExpr::AtomicOp Op,
5273                                  AtomicArgumentOrder ArgOrder) {
5274   // All the non-OpenCL operations take one of the following forms.
5275   // The OpenCL operations take the __c11 forms with one extra argument for
5276   // synchronization scope.
5277   enum {
5278     // C    __c11_atomic_init(A *, C)
5279     Init,
5280 
5281     // C    __c11_atomic_load(A *, int)
5282     Load,
5283 
5284     // void __atomic_load(A *, CP, int)
5285     LoadCopy,
5286 
5287     // void __atomic_store(A *, CP, int)
5288     Copy,
5289 
5290     // C    __c11_atomic_add(A *, M, int)
5291     Arithmetic,
5292 
5293     // C    __atomic_exchange_n(A *, CP, int)
5294     Xchg,
5295 
5296     // void __atomic_exchange(A *, C *, CP, int)
5297     GNUXchg,
5298 
5299     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5300     C11CmpXchg,
5301 
5302     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5303     GNUCmpXchg
5304   } Form = Init;
5305 
5306   const unsigned NumForm = GNUCmpXchg + 1;
5307   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5308   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5309   // where:
5310   //   C is an appropriate type,
5311   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5312   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5313   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5314   //   the int parameters are for orderings.
5315 
5316   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5317       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5318       "need to update code for modified forms");
5319   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5320                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5321                         AtomicExpr::AO__atomic_load,
5322                 "need to update code for modified C11 atomics");
5323   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5324                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5325   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5326                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5327                IsOpenCL;
5328   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5329              Op == AtomicExpr::AO__atomic_store_n ||
5330              Op == AtomicExpr::AO__atomic_exchange_n ||
5331              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5332   bool IsAddSub = false;
5333 
5334   switch (Op) {
5335   case AtomicExpr::AO__c11_atomic_init:
5336   case AtomicExpr::AO__opencl_atomic_init:
5337     Form = Init;
5338     break;
5339 
5340   case AtomicExpr::AO__c11_atomic_load:
5341   case AtomicExpr::AO__opencl_atomic_load:
5342   case AtomicExpr::AO__atomic_load_n:
5343     Form = Load;
5344     break;
5345 
5346   case AtomicExpr::AO__atomic_load:
5347     Form = LoadCopy;
5348     break;
5349 
5350   case AtomicExpr::AO__c11_atomic_store:
5351   case AtomicExpr::AO__opencl_atomic_store:
5352   case AtomicExpr::AO__atomic_store:
5353   case AtomicExpr::AO__atomic_store_n:
5354     Form = Copy;
5355     break;
5356 
5357   case AtomicExpr::AO__c11_atomic_fetch_add:
5358   case AtomicExpr::AO__c11_atomic_fetch_sub:
5359   case AtomicExpr::AO__opencl_atomic_fetch_add:
5360   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5361   case AtomicExpr::AO__atomic_fetch_add:
5362   case AtomicExpr::AO__atomic_fetch_sub:
5363   case AtomicExpr::AO__atomic_add_fetch:
5364   case AtomicExpr::AO__atomic_sub_fetch:
5365     IsAddSub = true;
5366     Form = Arithmetic;
5367     break;
5368   case AtomicExpr::AO__c11_atomic_fetch_and:
5369   case AtomicExpr::AO__c11_atomic_fetch_or:
5370   case AtomicExpr::AO__c11_atomic_fetch_xor:
5371   case AtomicExpr::AO__opencl_atomic_fetch_and:
5372   case AtomicExpr::AO__opencl_atomic_fetch_or:
5373   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5374   case AtomicExpr::AO__atomic_fetch_and:
5375   case AtomicExpr::AO__atomic_fetch_or:
5376   case AtomicExpr::AO__atomic_fetch_xor:
5377   case AtomicExpr::AO__atomic_fetch_nand:
5378   case AtomicExpr::AO__atomic_and_fetch:
5379   case AtomicExpr::AO__atomic_or_fetch:
5380   case AtomicExpr::AO__atomic_xor_fetch:
5381   case AtomicExpr::AO__atomic_nand_fetch:
5382     Form = Arithmetic;
5383     break;
5384   case AtomicExpr::AO__c11_atomic_fetch_min:
5385   case AtomicExpr::AO__c11_atomic_fetch_max:
5386   case AtomicExpr::AO__opencl_atomic_fetch_min:
5387   case AtomicExpr::AO__opencl_atomic_fetch_max:
5388   case AtomicExpr::AO__atomic_min_fetch:
5389   case AtomicExpr::AO__atomic_max_fetch:
5390   case AtomicExpr::AO__atomic_fetch_min:
5391   case AtomicExpr::AO__atomic_fetch_max:
5392     Form = Arithmetic;
5393     break;
5394 
5395   case AtomicExpr::AO__c11_atomic_exchange:
5396   case AtomicExpr::AO__opencl_atomic_exchange:
5397   case AtomicExpr::AO__atomic_exchange_n:
5398     Form = Xchg;
5399     break;
5400 
5401   case AtomicExpr::AO__atomic_exchange:
5402     Form = GNUXchg;
5403     break;
5404 
5405   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5406   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5407   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5408   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5409     Form = C11CmpXchg;
5410     break;
5411 
5412   case AtomicExpr::AO__atomic_compare_exchange:
5413   case AtomicExpr::AO__atomic_compare_exchange_n:
5414     Form = GNUCmpXchg;
5415     break;
5416   }
5417 
5418   unsigned AdjustedNumArgs = NumArgs[Form];
5419   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5420     ++AdjustedNumArgs;
5421   // Check we have the right number of arguments.
5422   if (Args.size() < AdjustedNumArgs) {
5423     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5424         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5425         << ExprRange;
5426     return ExprError();
5427   } else if (Args.size() > AdjustedNumArgs) {
5428     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5429          diag::err_typecheck_call_too_many_args)
5430         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5431         << ExprRange;
5432     return ExprError();
5433   }
5434 
5435   // Inspect the first argument of the atomic operation.
5436   Expr *Ptr = Args[0];
5437   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5438   if (ConvertedPtr.isInvalid())
5439     return ExprError();
5440 
5441   Ptr = ConvertedPtr.get();
5442   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5443   if (!pointerType) {
5444     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5445         << Ptr->getType() << Ptr->getSourceRange();
5446     return ExprError();
5447   }
5448 
5449   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5450   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5451   QualType ValType = AtomTy; // 'C'
5452   if (IsC11) {
5453     if (!AtomTy->isAtomicType()) {
5454       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5455           << Ptr->getType() << Ptr->getSourceRange();
5456       return ExprError();
5457     }
5458     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5459         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5460       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5461           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5462           << Ptr->getSourceRange();
5463       return ExprError();
5464     }
5465     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5466   } else if (Form != Load && Form != LoadCopy) {
5467     if (ValType.isConstQualified()) {
5468       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5469           << Ptr->getType() << Ptr->getSourceRange();
5470       return ExprError();
5471     }
5472   }
5473 
5474   // For an arithmetic operation, the implied arithmetic must be well-formed.
5475   if (Form == Arithmetic) {
5476     // gcc does not enforce these rules for GNU atomics, but we do so for
5477     // sanity.
5478     auto IsAllowedValueType = [&](QualType ValType) {
5479       if (ValType->isIntegerType())
5480         return true;
5481       if (ValType->isPointerType())
5482         return true;
5483       if (!ValType->isFloatingType())
5484         return false;
5485       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5486       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5487           &Context.getTargetInfo().getLongDoubleFormat() ==
5488               &llvm::APFloat::x87DoubleExtended())
5489         return false;
5490       return true;
5491     };
5492     if (IsAddSub && !IsAllowedValueType(ValType)) {
5493       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5494           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5495       return ExprError();
5496     }
5497     if (!IsAddSub && !ValType->isIntegerType()) {
5498       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5499           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5500       return ExprError();
5501     }
5502     if (IsC11 && ValType->isPointerType() &&
5503         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5504                             diag::err_incomplete_type)) {
5505       return ExprError();
5506     }
5507   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5508     // For __atomic_*_n operations, the value type must be a scalar integral or
5509     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5510     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5511         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5512     return ExprError();
5513   }
5514 
5515   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5516       !AtomTy->isScalarType()) {
5517     // For GNU atomics, require a trivially-copyable type. This is not part of
5518     // the GNU atomics specification, but we enforce it for sanity.
5519     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5520         << Ptr->getType() << Ptr->getSourceRange();
5521     return ExprError();
5522   }
5523 
5524   switch (ValType.getObjCLifetime()) {
5525   case Qualifiers::OCL_None:
5526   case Qualifiers::OCL_ExplicitNone:
5527     // okay
5528     break;
5529 
5530   case Qualifiers::OCL_Weak:
5531   case Qualifiers::OCL_Strong:
5532   case Qualifiers::OCL_Autoreleasing:
5533     // FIXME: Can this happen? By this point, ValType should be known
5534     // to be trivially copyable.
5535     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5536         << ValType << Ptr->getSourceRange();
5537     return ExprError();
5538   }
5539 
5540   // All atomic operations have an overload which takes a pointer to a volatile
5541   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5542   // into the result or the other operands. Similarly atomic_load takes a
5543   // pointer to a const 'A'.
5544   ValType.removeLocalVolatile();
5545   ValType.removeLocalConst();
5546   QualType ResultType = ValType;
5547   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5548       Form == Init)
5549     ResultType = Context.VoidTy;
5550   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5551     ResultType = Context.BoolTy;
5552 
5553   // The type of a parameter passed 'by value'. In the GNU atomics, such
5554   // arguments are actually passed as pointers.
5555   QualType ByValType = ValType; // 'CP'
5556   bool IsPassedByAddress = false;
5557   if (!IsC11 && !IsN) {
5558     ByValType = Ptr->getType();
5559     IsPassedByAddress = true;
5560   }
5561 
5562   SmallVector<Expr *, 5> APIOrderedArgs;
5563   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5564     APIOrderedArgs.push_back(Args[0]);
5565     switch (Form) {
5566     case Init:
5567     case Load:
5568       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5569       break;
5570     case LoadCopy:
5571     case Copy:
5572     case Arithmetic:
5573     case Xchg:
5574       APIOrderedArgs.push_back(Args[2]); // Val1
5575       APIOrderedArgs.push_back(Args[1]); // Order
5576       break;
5577     case GNUXchg:
5578       APIOrderedArgs.push_back(Args[2]); // Val1
5579       APIOrderedArgs.push_back(Args[3]); // Val2
5580       APIOrderedArgs.push_back(Args[1]); // Order
5581       break;
5582     case C11CmpXchg:
5583       APIOrderedArgs.push_back(Args[2]); // Val1
5584       APIOrderedArgs.push_back(Args[4]); // Val2
5585       APIOrderedArgs.push_back(Args[1]); // Order
5586       APIOrderedArgs.push_back(Args[3]); // OrderFail
5587       break;
5588     case GNUCmpXchg:
5589       APIOrderedArgs.push_back(Args[2]); // Val1
5590       APIOrderedArgs.push_back(Args[4]); // Val2
5591       APIOrderedArgs.push_back(Args[5]); // Weak
5592       APIOrderedArgs.push_back(Args[1]); // Order
5593       APIOrderedArgs.push_back(Args[3]); // OrderFail
5594       break;
5595     }
5596   } else
5597     APIOrderedArgs.append(Args.begin(), Args.end());
5598 
5599   // The first argument's non-CV pointer type is used to deduce the type of
5600   // subsequent arguments, except for:
5601   //  - weak flag (always converted to bool)
5602   //  - memory order (always converted to int)
5603   //  - scope  (always converted to int)
5604   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5605     QualType Ty;
5606     if (i < NumVals[Form] + 1) {
5607       switch (i) {
5608       case 0:
5609         // The first argument is always a pointer. It has a fixed type.
5610         // It is always dereferenced, a nullptr is undefined.
5611         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5612         // Nothing else to do: we already know all we want about this pointer.
5613         continue;
5614       case 1:
5615         // The second argument is the non-atomic operand. For arithmetic, this
5616         // is always passed by value, and for a compare_exchange it is always
5617         // passed by address. For the rest, GNU uses by-address and C11 uses
5618         // by-value.
5619         assert(Form != Load);
5620         if (Form == Arithmetic && ValType->isPointerType())
5621           Ty = Context.getPointerDiffType();
5622         else if (Form == Init || Form == Arithmetic)
5623           Ty = ValType;
5624         else if (Form == Copy || Form == Xchg) {
5625           if (IsPassedByAddress) {
5626             // The value pointer is always dereferenced, a nullptr is undefined.
5627             CheckNonNullArgument(*this, APIOrderedArgs[i],
5628                                  ExprRange.getBegin());
5629           }
5630           Ty = ByValType;
5631         } else {
5632           Expr *ValArg = APIOrderedArgs[i];
5633           // The value pointer is always dereferenced, a nullptr is undefined.
5634           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5635           LangAS AS = LangAS::Default;
5636           // Keep address space of non-atomic pointer type.
5637           if (const PointerType *PtrTy =
5638                   ValArg->getType()->getAs<PointerType>()) {
5639             AS = PtrTy->getPointeeType().getAddressSpace();
5640           }
5641           Ty = Context.getPointerType(
5642               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5643         }
5644         break;
5645       case 2:
5646         // The third argument to compare_exchange / GNU exchange is the desired
5647         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5648         if (IsPassedByAddress)
5649           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5650         Ty = ByValType;
5651         break;
5652       case 3:
5653         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5654         Ty = Context.BoolTy;
5655         break;
5656       }
5657     } else {
5658       // The order(s) and scope are always converted to int.
5659       Ty = Context.IntTy;
5660     }
5661 
5662     InitializedEntity Entity =
5663         InitializedEntity::InitializeParameter(Context, Ty, false);
5664     ExprResult Arg = APIOrderedArgs[i];
5665     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5666     if (Arg.isInvalid())
5667       return true;
5668     APIOrderedArgs[i] = Arg.get();
5669   }
5670 
5671   // Permute the arguments into a 'consistent' order.
5672   SmallVector<Expr*, 5> SubExprs;
5673   SubExprs.push_back(Ptr);
5674   switch (Form) {
5675   case Init:
5676     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5677     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5678     break;
5679   case Load:
5680     SubExprs.push_back(APIOrderedArgs[1]); // Order
5681     break;
5682   case LoadCopy:
5683   case Copy:
5684   case Arithmetic:
5685   case Xchg:
5686     SubExprs.push_back(APIOrderedArgs[2]); // Order
5687     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5688     break;
5689   case GNUXchg:
5690     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5691     SubExprs.push_back(APIOrderedArgs[3]); // Order
5692     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5693     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5694     break;
5695   case C11CmpXchg:
5696     SubExprs.push_back(APIOrderedArgs[3]); // Order
5697     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5698     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5699     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5700     break;
5701   case GNUCmpXchg:
5702     SubExprs.push_back(APIOrderedArgs[4]); // Order
5703     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5704     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5705     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5706     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5707     break;
5708   }
5709 
5710   if (SubExprs.size() >= 2 && Form != Init) {
5711     if (Optional<llvm::APSInt> Result =
5712             SubExprs[1]->getIntegerConstantExpr(Context))
5713       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5714         Diag(SubExprs[1]->getBeginLoc(),
5715              diag::warn_atomic_op_has_invalid_memory_order)
5716             << SubExprs[1]->getSourceRange();
5717   }
5718 
5719   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5720     auto *Scope = Args[Args.size() - 1];
5721     if (Optional<llvm::APSInt> Result =
5722             Scope->getIntegerConstantExpr(Context)) {
5723       if (!ScopeModel->isValid(Result->getZExtValue()))
5724         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5725             << Scope->getSourceRange();
5726     }
5727     SubExprs.push_back(Scope);
5728   }
5729 
5730   AtomicExpr *AE = new (Context)
5731       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5732 
5733   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5734        Op == AtomicExpr::AO__c11_atomic_store ||
5735        Op == AtomicExpr::AO__opencl_atomic_load ||
5736        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5737       Context.AtomicUsesUnsupportedLibcall(AE))
5738     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5739         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5740              Op == AtomicExpr::AO__opencl_atomic_load)
5741                 ? 0
5742                 : 1);
5743 
5744   if (ValType->isExtIntType()) {
5745     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5746     return ExprError();
5747   }
5748 
5749   return AE;
5750 }
5751 
5752 /// checkBuiltinArgument - Given a call to a builtin function, perform
5753 /// normal type-checking on the given argument, updating the call in
5754 /// place.  This is useful when a builtin function requires custom
5755 /// type-checking for some of its arguments but not necessarily all of
5756 /// them.
5757 ///
5758 /// Returns true on error.
5759 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5760   FunctionDecl *Fn = E->getDirectCallee();
5761   assert(Fn && "builtin call without direct callee!");
5762 
5763   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5764   InitializedEntity Entity =
5765     InitializedEntity::InitializeParameter(S.Context, Param);
5766 
5767   ExprResult Arg = E->getArg(0);
5768   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5769   if (Arg.isInvalid())
5770     return true;
5771 
5772   E->setArg(ArgIndex, Arg.get());
5773   return false;
5774 }
5775 
5776 /// We have a call to a function like __sync_fetch_and_add, which is an
5777 /// overloaded function based on the pointer type of its first argument.
5778 /// The main BuildCallExpr routines have already promoted the types of
5779 /// arguments because all of these calls are prototyped as void(...).
5780 ///
5781 /// This function goes through and does final semantic checking for these
5782 /// builtins, as well as generating any warnings.
5783 ExprResult
5784 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5785   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5786   Expr *Callee = TheCall->getCallee();
5787   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5788   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5789 
5790   // Ensure that we have at least one argument to do type inference from.
5791   if (TheCall->getNumArgs() < 1) {
5792     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5793         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5794     return ExprError();
5795   }
5796 
5797   // Inspect the first argument of the atomic builtin.  This should always be
5798   // a pointer type, whose element is an integral scalar or pointer type.
5799   // Because it is a pointer type, we don't have to worry about any implicit
5800   // casts here.
5801   // FIXME: We don't allow floating point scalars as input.
5802   Expr *FirstArg = TheCall->getArg(0);
5803   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5804   if (FirstArgResult.isInvalid())
5805     return ExprError();
5806   FirstArg = FirstArgResult.get();
5807   TheCall->setArg(0, FirstArg);
5808 
5809   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5810   if (!pointerType) {
5811     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5812         << FirstArg->getType() << FirstArg->getSourceRange();
5813     return ExprError();
5814   }
5815 
5816   QualType ValType = pointerType->getPointeeType();
5817   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5818       !ValType->isBlockPointerType()) {
5819     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5820         << FirstArg->getType() << FirstArg->getSourceRange();
5821     return ExprError();
5822   }
5823 
5824   if (ValType.isConstQualified()) {
5825     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5826         << FirstArg->getType() << FirstArg->getSourceRange();
5827     return ExprError();
5828   }
5829 
5830   switch (ValType.getObjCLifetime()) {
5831   case Qualifiers::OCL_None:
5832   case Qualifiers::OCL_ExplicitNone:
5833     // okay
5834     break;
5835 
5836   case Qualifiers::OCL_Weak:
5837   case Qualifiers::OCL_Strong:
5838   case Qualifiers::OCL_Autoreleasing:
5839     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5840         << ValType << FirstArg->getSourceRange();
5841     return ExprError();
5842   }
5843 
5844   // Strip any qualifiers off ValType.
5845   ValType = ValType.getUnqualifiedType();
5846 
5847   // The majority of builtins return a value, but a few have special return
5848   // types, so allow them to override appropriately below.
5849   QualType ResultType = ValType;
5850 
5851   // We need to figure out which concrete builtin this maps onto.  For example,
5852   // __sync_fetch_and_add with a 2 byte object turns into
5853   // __sync_fetch_and_add_2.
5854 #define BUILTIN_ROW(x) \
5855   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5856     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5857 
5858   static const unsigned BuiltinIndices[][5] = {
5859     BUILTIN_ROW(__sync_fetch_and_add),
5860     BUILTIN_ROW(__sync_fetch_and_sub),
5861     BUILTIN_ROW(__sync_fetch_and_or),
5862     BUILTIN_ROW(__sync_fetch_and_and),
5863     BUILTIN_ROW(__sync_fetch_and_xor),
5864     BUILTIN_ROW(__sync_fetch_and_nand),
5865 
5866     BUILTIN_ROW(__sync_add_and_fetch),
5867     BUILTIN_ROW(__sync_sub_and_fetch),
5868     BUILTIN_ROW(__sync_and_and_fetch),
5869     BUILTIN_ROW(__sync_or_and_fetch),
5870     BUILTIN_ROW(__sync_xor_and_fetch),
5871     BUILTIN_ROW(__sync_nand_and_fetch),
5872 
5873     BUILTIN_ROW(__sync_val_compare_and_swap),
5874     BUILTIN_ROW(__sync_bool_compare_and_swap),
5875     BUILTIN_ROW(__sync_lock_test_and_set),
5876     BUILTIN_ROW(__sync_lock_release),
5877     BUILTIN_ROW(__sync_swap)
5878   };
5879 #undef BUILTIN_ROW
5880 
5881   // Determine the index of the size.
5882   unsigned SizeIndex;
5883   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5884   case 1: SizeIndex = 0; break;
5885   case 2: SizeIndex = 1; break;
5886   case 4: SizeIndex = 2; break;
5887   case 8: SizeIndex = 3; break;
5888   case 16: SizeIndex = 4; break;
5889   default:
5890     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5891         << FirstArg->getType() << FirstArg->getSourceRange();
5892     return ExprError();
5893   }
5894 
5895   // Each of these builtins has one pointer argument, followed by some number of
5896   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5897   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5898   // as the number of fixed args.
5899   unsigned BuiltinID = FDecl->getBuiltinID();
5900   unsigned BuiltinIndex, NumFixed = 1;
5901   bool WarnAboutSemanticsChange = false;
5902   switch (BuiltinID) {
5903   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5904   case Builtin::BI__sync_fetch_and_add:
5905   case Builtin::BI__sync_fetch_and_add_1:
5906   case Builtin::BI__sync_fetch_and_add_2:
5907   case Builtin::BI__sync_fetch_and_add_4:
5908   case Builtin::BI__sync_fetch_and_add_8:
5909   case Builtin::BI__sync_fetch_and_add_16:
5910     BuiltinIndex = 0;
5911     break;
5912 
5913   case Builtin::BI__sync_fetch_and_sub:
5914   case Builtin::BI__sync_fetch_and_sub_1:
5915   case Builtin::BI__sync_fetch_and_sub_2:
5916   case Builtin::BI__sync_fetch_and_sub_4:
5917   case Builtin::BI__sync_fetch_and_sub_8:
5918   case Builtin::BI__sync_fetch_and_sub_16:
5919     BuiltinIndex = 1;
5920     break;
5921 
5922   case Builtin::BI__sync_fetch_and_or:
5923   case Builtin::BI__sync_fetch_and_or_1:
5924   case Builtin::BI__sync_fetch_and_or_2:
5925   case Builtin::BI__sync_fetch_and_or_4:
5926   case Builtin::BI__sync_fetch_and_or_8:
5927   case Builtin::BI__sync_fetch_and_or_16:
5928     BuiltinIndex = 2;
5929     break;
5930 
5931   case Builtin::BI__sync_fetch_and_and:
5932   case Builtin::BI__sync_fetch_and_and_1:
5933   case Builtin::BI__sync_fetch_and_and_2:
5934   case Builtin::BI__sync_fetch_and_and_4:
5935   case Builtin::BI__sync_fetch_and_and_8:
5936   case Builtin::BI__sync_fetch_and_and_16:
5937     BuiltinIndex = 3;
5938     break;
5939 
5940   case Builtin::BI__sync_fetch_and_xor:
5941   case Builtin::BI__sync_fetch_and_xor_1:
5942   case Builtin::BI__sync_fetch_and_xor_2:
5943   case Builtin::BI__sync_fetch_and_xor_4:
5944   case Builtin::BI__sync_fetch_and_xor_8:
5945   case Builtin::BI__sync_fetch_and_xor_16:
5946     BuiltinIndex = 4;
5947     break;
5948 
5949   case Builtin::BI__sync_fetch_and_nand:
5950   case Builtin::BI__sync_fetch_and_nand_1:
5951   case Builtin::BI__sync_fetch_and_nand_2:
5952   case Builtin::BI__sync_fetch_and_nand_4:
5953   case Builtin::BI__sync_fetch_and_nand_8:
5954   case Builtin::BI__sync_fetch_and_nand_16:
5955     BuiltinIndex = 5;
5956     WarnAboutSemanticsChange = true;
5957     break;
5958 
5959   case Builtin::BI__sync_add_and_fetch:
5960   case Builtin::BI__sync_add_and_fetch_1:
5961   case Builtin::BI__sync_add_and_fetch_2:
5962   case Builtin::BI__sync_add_and_fetch_4:
5963   case Builtin::BI__sync_add_and_fetch_8:
5964   case Builtin::BI__sync_add_and_fetch_16:
5965     BuiltinIndex = 6;
5966     break;
5967 
5968   case Builtin::BI__sync_sub_and_fetch:
5969   case Builtin::BI__sync_sub_and_fetch_1:
5970   case Builtin::BI__sync_sub_and_fetch_2:
5971   case Builtin::BI__sync_sub_and_fetch_4:
5972   case Builtin::BI__sync_sub_and_fetch_8:
5973   case Builtin::BI__sync_sub_and_fetch_16:
5974     BuiltinIndex = 7;
5975     break;
5976 
5977   case Builtin::BI__sync_and_and_fetch:
5978   case Builtin::BI__sync_and_and_fetch_1:
5979   case Builtin::BI__sync_and_and_fetch_2:
5980   case Builtin::BI__sync_and_and_fetch_4:
5981   case Builtin::BI__sync_and_and_fetch_8:
5982   case Builtin::BI__sync_and_and_fetch_16:
5983     BuiltinIndex = 8;
5984     break;
5985 
5986   case Builtin::BI__sync_or_and_fetch:
5987   case Builtin::BI__sync_or_and_fetch_1:
5988   case Builtin::BI__sync_or_and_fetch_2:
5989   case Builtin::BI__sync_or_and_fetch_4:
5990   case Builtin::BI__sync_or_and_fetch_8:
5991   case Builtin::BI__sync_or_and_fetch_16:
5992     BuiltinIndex = 9;
5993     break;
5994 
5995   case Builtin::BI__sync_xor_and_fetch:
5996   case Builtin::BI__sync_xor_and_fetch_1:
5997   case Builtin::BI__sync_xor_and_fetch_2:
5998   case Builtin::BI__sync_xor_and_fetch_4:
5999   case Builtin::BI__sync_xor_and_fetch_8:
6000   case Builtin::BI__sync_xor_and_fetch_16:
6001     BuiltinIndex = 10;
6002     break;
6003 
6004   case Builtin::BI__sync_nand_and_fetch:
6005   case Builtin::BI__sync_nand_and_fetch_1:
6006   case Builtin::BI__sync_nand_and_fetch_2:
6007   case Builtin::BI__sync_nand_and_fetch_4:
6008   case Builtin::BI__sync_nand_and_fetch_8:
6009   case Builtin::BI__sync_nand_and_fetch_16:
6010     BuiltinIndex = 11;
6011     WarnAboutSemanticsChange = true;
6012     break;
6013 
6014   case Builtin::BI__sync_val_compare_and_swap:
6015   case Builtin::BI__sync_val_compare_and_swap_1:
6016   case Builtin::BI__sync_val_compare_and_swap_2:
6017   case Builtin::BI__sync_val_compare_and_swap_4:
6018   case Builtin::BI__sync_val_compare_and_swap_8:
6019   case Builtin::BI__sync_val_compare_and_swap_16:
6020     BuiltinIndex = 12;
6021     NumFixed = 2;
6022     break;
6023 
6024   case Builtin::BI__sync_bool_compare_and_swap:
6025   case Builtin::BI__sync_bool_compare_and_swap_1:
6026   case Builtin::BI__sync_bool_compare_and_swap_2:
6027   case Builtin::BI__sync_bool_compare_and_swap_4:
6028   case Builtin::BI__sync_bool_compare_and_swap_8:
6029   case Builtin::BI__sync_bool_compare_and_swap_16:
6030     BuiltinIndex = 13;
6031     NumFixed = 2;
6032     ResultType = Context.BoolTy;
6033     break;
6034 
6035   case Builtin::BI__sync_lock_test_and_set:
6036   case Builtin::BI__sync_lock_test_and_set_1:
6037   case Builtin::BI__sync_lock_test_and_set_2:
6038   case Builtin::BI__sync_lock_test_and_set_4:
6039   case Builtin::BI__sync_lock_test_and_set_8:
6040   case Builtin::BI__sync_lock_test_and_set_16:
6041     BuiltinIndex = 14;
6042     break;
6043 
6044   case Builtin::BI__sync_lock_release:
6045   case Builtin::BI__sync_lock_release_1:
6046   case Builtin::BI__sync_lock_release_2:
6047   case Builtin::BI__sync_lock_release_4:
6048   case Builtin::BI__sync_lock_release_8:
6049   case Builtin::BI__sync_lock_release_16:
6050     BuiltinIndex = 15;
6051     NumFixed = 0;
6052     ResultType = Context.VoidTy;
6053     break;
6054 
6055   case Builtin::BI__sync_swap:
6056   case Builtin::BI__sync_swap_1:
6057   case Builtin::BI__sync_swap_2:
6058   case Builtin::BI__sync_swap_4:
6059   case Builtin::BI__sync_swap_8:
6060   case Builtin::BI__sync_swap_16:
6061     BuiltinIndex = 16;
6062     break;
6063   }
6064 
6065   // Now that we know how many fixed arguments we expect, first check that we
6066   // have at least that many.
6067   if (TheCall->getNumArgs() < 1+NumFixed) {
6068     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6069         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6070         << Callee->getSourceRange();
6071     return ExprError();
6072   }
6073 
6074   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6075       << Callee->getSourceRange();
6076 
6077   if (WarnAboutSemanticsChange) {
6078     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6079         << Callee->getSourceRange();
6080   }
6081 
6082   // Get the decl for the concrete builtin from this, we can tell what the
6083   // concrete integer type we should convert to is.
6084   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6085   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6086   FunctionDecl *NewBuiltinDecl;
6087   if (NewBuiltinID == BuiltinID)
6088     NewBuiltinDecl = FDecl;
6089   else {
6090     // Perform builtin lookup to avoid redeclaring it.
6091     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6092     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6093     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6094     assert(Res.getFoundDecl());
6095     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6096     if (!NewBuiltinDecl)
6097       return ExprError();
6098   }
6099 
6100   // The first argument --- the pointer --- has a fixed type; we
6101   // deduce the types of the rest of the arguments accordingly.  Walk
6102   // the remaining arguments, converting them to the deduced value type.
6103   for (unsigned i = 0; i != NumFixed; ++i) {
6104     ExprResult Arg = TheCall->getArg(i+1);
6105 
6106     // GCC does an implicit conversion to the pointer or integer ValType.  This
6107     // can fail in some cases (1i -> int**), check for this error case now.
6108     // Initialize the argument.
6109     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6110                                                    ValType, /*consume*/ false);
6111     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6112     if (Arg.isInvalid())
6113       return ExprError();
6114 
6115     // Okay, we have something that *can* be converted to the right type.  Check
6116     // to see if there is a potentially weird extension going on here.  This can
6117     // happen when you do an atomic operation on something like an char* and
6118     // pass in 42.  The 42 gets converted to char.  This is even more strange
6119     // for things like 45.123 -> char, etc.
6120     // FIXME: Do this check.
6121     TheCall->setArg(i+1, Arg.get());
6122   }
6123 
6124   // Create a new DeclRefExpr to refer to the new decl.
6125   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6126       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6127       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6128       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6129 
6130   // Set the callee in the CallExpr.
6131   // FIXME: This loses syntactic information.
6132   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6133   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6134                                               CK_BuiltinFnToFnPtr);
6135   TheCall->setCallee(PromotedCall.get());
6136 
6137   // Change the result type of the call to match the original value type. This
6138   // is arbitrary, but the codegen for these builtins ins design to handle it
6139   // gracefully.
6140   TheCall->setType(ResultType);
6141 
6142   // Prohibit use of _ExtInt with atomic builtins.
6143   // The arguments would have already been converted to the first argument's
6144   // type, so only need to check the first argument.
6145   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6146   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6147     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6148     return ExprError();
6149   }
6150 
6151   return TheCallResult;
6152 }
6153 
6154 /// SemaBuiltinNontemporalOverloaded - We have a call to
6155 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6156 /// overloaded function based on the pointer type of its last argument.
6157 ///
6158 /// This function goes through and does final semantic checking for these
6159 /// builtins.
6160 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6161   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6162   DeclRefExpr *DRE =
6163       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6164   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6165   unsigned BuiltinID = FDecl->getBuiltinID();
6166   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6167           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6168          "Unexpected nontemporal load/store builtin!");
6169   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6170   unsigned numArgs = isStore ? 2 : 1;
6171 
6172   // Ensure that we have the proper number of arguments.
6173   if (checkArgCount(*this, TheCall, numArgs))
6174     return ExprError();
6175 
6176   // Inspect the last argument of the nontemporal builtin.  This should always
6177   // be a pointer type, from which we imply the type of the memory access.
6178   // Because it is a pointer type, we don't have to worry about any implicit
6179   // casts here.
6180   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6181   ExprResult PointerArgResult =
6182       DefaultFunctionArrayLvalueConversion(PointerArg);
6183 
6184   if (PointerArgResult.isInvalid())
6185     return ExprError();
6186   PointerArg = PointerArgResult.get();
6187   TheCall->setArg(numArgs - 1, PointerArg);
6188 
6189   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6190   if (!pointerType) {
6191     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6192         << PointerArg->getType() << PointerArg->getSourceRange();
6193     return ExprError();
6194   }
6195 
6196   QualType ValType = pointerType->getPointeeType();
6197 
6198   // Strip any qualifiers off ValType.
6199   ValType = ValType.getUnqualifiedType();
6200   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6201       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6202       !ValType->isVectorType()) {
6203     Diag(DRE->getBeginLoc(),
6204          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6205         << PointerArg->getType() << PointerArg->getSourceRange();
6206     return ExprError();
6207   }
6208 
6209   if (!isStore) {
6210     TheCall->setType(ValType);
6211     return TheCallResult;
6212   }
6213 
6214   ExprResult ValArg = TheCall->getArg(0);
6215   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6216       Context, ValType, /*consume*/ false);
6217   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6218   if (ValArg.isInvalid())
6219     return ExprError();
6220 
6221   TheCall->setArg(0, ValArg.get());
6222   TheCall->setType(Context.VoidTy);
6223   return TheCallResult;
6224 }
6225 
6226 /// CheckObjCString - Checks that the argument to the builtin
6227 /// CFString constructor is correct
6228 /// Note: It might also make sense to do the UTF-16 conversion here (would
6229 /// simplify the backend).
6230 bool Sema::CheckObjCString(Expr *Arg) {
6231   Arg = Arg->IgnoreParenCasts();
6232   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6233 
6234   if (!Literal || !Literal->isAscii()) {
6235     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6236         << Arg->getSourceRange();
6237     return true;
6238   }
6239 
6240   if (Literal->containsNonAsciiOrNull()) {
6241     StringRef String = Literal->getString();
6242     unsigned NumBytes = String.size();
6243     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6244     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6245     llvm::UTF16 *ToPtr = &ToBuf[0];
6246 
6247     llvm::ConversionResult Result =
6248         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6249                                  ToPtr + NumBytes, llvm::strictConversion);
6250     // Check for conversion failure.
6251     if (Result != llvm::conversionOK)
6252       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6253           << Arg->getSourceRange();
6254   }
6255   return false;
6256 }
6257 
6258 /// CheckObjCString - Checks that the format string argument to the os_log()
6259 /// and os_trace() functions is correct, and converts it to const char *.
6260 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6261   Arg = Arg->IgnoreParenCasts();
6262   auto *Literal = dyn_cast<StringLiteral>(Arg);
6263   if (!Literal) {
6264     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6265       Literal = ObjcLiteral->getString();
6266     }
6267   }
6268 
6269   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6270     return ExprError(
6271         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6272         << Arg->getSourceRange());
6273   }
6274 
6275   ExprResult Result(Literal);
6276   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6277   InitializedEntity Entity =
6278       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6279   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6280   return Result;
6281 }
6282 
6283 /// Check that the user is calling the appropriate va_start builtin for the
6284 /// target and calling convention.
6285 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6286   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6287   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6288   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6289                     TT.getArch() == llvm::Triple::aarch64_32);
6290   bool IsWindows = TT.isOSWindows();
6291   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6292   if (IsX64 || IsAArch64) {
6293     CallingConv CC = CC_C;
6294     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6295       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6296     if (IsMSVAStart) {
6297       // Don't allow this in System V ABI functions.
6298       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6299         return S.Diag(Fn->getBeginLoc(),
6300                       diag::err_ms_va_start_used_in_sysv_function);
6301     } else {
6302       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6303       // On x64 Windows, don't allow this in System V ABI functions.
6304       // (Yes, that means there's no corresponding way to support variadic
6305       // System V ABI functions on Windows.)
6306       if ((IsWindows && CC == CC_X86_64SysV) ||
6307           (!IsWindows && CC == CC_Win64))
6308         return S.Diag(Fn->getBeginLoc(),
6309                       diag::err_va_start_used_in_wrong_abi_function)
6310                << !IsWindows;
6311     }
6312     return false;
6313   }
6314 
6315   if (IsMSVAStart)
6316     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6317   return false;
6318 }
6319 
6320 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6321                                              ParmVarDecl **LastParam = nullptr) {
6322   // Determine whether the current function, block, or obj-c method is variadic
6323   // and get its parameter list.
6324   bool IsVariadic = false;
6325   ArrayRef<ParmVarDecl *> Params;
6326   DeclContext *Caller = S.CurContext;
6327   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6328     IsVariadic = Block->isVariadic();
6329     Params = Block->parameters();
6330   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6331     IsVariadic = FD->isVariadic();
6332     Params = FD->parameters();
6333   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6334     IsVariadic = MD->isVariadic();
6335     // FIXME: This isn't correct for methods (results in bogus warning).
6336     Params = MD->parameters();
6337   } else if (isa<CapturedDecl>(Caller)) {
6338     // We don't support va_start in a CapturedDecl.
6339     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6340     return true;
6341   } else {
6342     // This must be some other declcontext that parses exprs.
6343     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6344     return true;
6345   }
6346 
6347   if (!IsVariadic) {
6348     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6349     return true;
6350   }
6351 
6352   if (LastParam)
6353     *LastParam = Params.empty() ? nullptr : Params.back();
6354 
6355   return false;
6356 }
6357 
6358 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6359 /// for validity.  Emit an error and return true on failure; return false
6360 /// on success.
6361 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6362   Expr *Fn = TheCall->getCallee();
6363 
6364   if (checkVAStartABI(*this, BuiltinID, Fn))
6365     return true;
6366 
6367   if (checkArgCount(*this, TheCall, 2))
6368     return true;
6369 
6370   // Type-check the first argument normally.
6371   if (checkBuiltinArgument(*this, TheCall, 0))
6372     return true;
6373 
6374   // Check that the current function is variadic, and get its last parameter.
6375   ParmVarDecl *LastParam;
6376   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6377     return true;
6378 
6379   // Verify that the second argument to the builtin is the last argument of the
6380   // current function or method.
6381   bool SecondArgIsLastNamedArgument = false;
6382   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6383 
6384   // These are valid if SecondArgIsLastNamedArgument is false after the next
6385   // block.
6386   QualType Type;
6387   SourceLocation ParamLoc;
6388   bool IsCRegister = false;
6389 
6390   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6391     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6392       SecondArgIsLastNamedArgument = PV == LastParam;
6393 
6394       Type = PV->getType();
6395       ParamLoc = PV->getLocation();
6396       IsCRegister =
6397           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6398     }
6399   }
6400 
6401   if (!SecondArgIsLastNamedArgument)
6402     Diag(TheCall->getArg(1)->getBeginLoc(),
6403          diag::warn_second_arg_of_va_start_not_last_named_param);
6404   else if (IsCRegister || Type->isReferenceType() ||
6405            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6406              // Promotable integers are UB, but enumerations need a bit of
6407              // extra checking to see what their promotable type actually is.
6408              if (!Type->isPromotableIntegerType())
6409                return false;
6410              if (!Type->isEnumeralType())
6411                return true;
6412              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6413              return !(ED &&
6414                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6415            }()) {
6416     unsigned Reason = 0;
6417     if (Type->isReferenceType())  Reason = 1;
6418     else if (IsCRegister)         Reason = 2;
6419     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6420     Diag(ParamLoc, diag::note_parameter_type) << Type;
6421   }
6422 
6423   TheCall->setType(Context.VoidTy);
6424   return false;
6425 }
6426 
6427 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6428   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6429     const LangOptions &LO = getLangOpts();
6430 
6431     if (LO.CPlusPlus)
6432       return Arg->getType()
6433                  .getCanonicalType()
6434                  .getTypePtr()
6435                  ->getPointeeType()
6436                  .withoutLocalFastQualifiers() == Context.CharTy;
6437 
6438     // In C, allow aliasing through `char *`, this is required for AArch64 at
6439     // least.
6440     return true;
6441   };
6442 
6443   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6444   //                 const char *named_addr);
6445 
6446   Expr *Func = Call->getCallee();
6447 
6448   if (Call->getNumArgs() < 3)
6449     return Diag(Call->getEndLoc(),
6450                 diag::err_typecheck_call_too_few_args_at_least)
6451            << 0 /*function call*/ << 3 << Call->getNumArgs();
6452 
6453   // Type-check the first argument normally.
6454   if (checkBuiltinArgument(*this, Call, 0))
6455     return true;
6456 
6457   // Check that the current function is variadic.
6458   if (checkVAStartIsInVariadicFunction(*this, Func))
6459     return true;
6460 
6461   // __va_start on Windows does not validate the parameter qualifiers
6462 
6463   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6464   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6465 
6466   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6467   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6468 
6469   const QualType &ConstCharPtrTy =
6470       Context.getPointerType(Context.CharTy.withConst());
6471   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6472     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6473         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6474         << 0                                      /* qualifier difference */
6475         << 3                                      /* parameter mismatch */
6476         << 2 << Arg1->getType() << ConstCharPtrTy;
6477 
6478   const QualType SizeTy = Context.getSizeType();
6479   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6480     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6481         << Arg2->getType() << SizeTy << 1 /* different class */
6482         << 0                              /* qualifier difference */
6483         << 3                              /* parameter mismatch */
6484         << 3 << Arg2->getType() << SizeTy;
6485 
6486   return false;
6487 }
6488 
6489 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6490 /// friends.  This is declared to take (...), so we have to check everything.
6491 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6492   if (checkArgCount(*this, TheCall, 2))
6493     return true;
6494 
6495   ExprResult OrigArg0 = TheCall->getArg(0);
6496   ExprResult OrigArg1 = TheCall->getArg(1);
6497 
6498   // Do standard promotions between the two arguments, returning their common
6499   // type.
6500   QualType Res = UsualArithmeticConversions(
6501       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6502   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6503     return true;
6504 
6505   // Make sure any conversions are pushed back into the call; this is
6506   // type safe since unordered compare builtins are declared as "_Bool
6507   // foo(...)".
6508   TheCall->setArg(0, OrigArg0.get());
6509   TheCall->setArg(1, OrigArg1.get());
6510 
6511   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6512     return false;
6513 
6514   // If the common type isn't a real floating type, then the arguments were
6515   // invalid for this operation.
6516   if (Res.isNull() || !Res->isRealFloatingType())
6517     return Diag(OrigArg0.get()->getBeginLoc(),
6518                 diag::err_typecheck_call_invalid_ordered_compare)
6519            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6520            << SourceRange(OrigArg0.get()->getBeginLoc(),
6521                           OrigArg1.get()->getEndLoc());
6522 
6523   return false;
6524 }
6525 
6526 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6527 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6528 /// to check everything. We expect the last argument to be a floating point
6529 /// value.
6530 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6531   if (checkArgCount(*this, TheCall, NumArgs))
6532     return true;
6533 
6534   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6535   // on all preceding parameters just being int.  Try all of those.
6536   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6537     Expr *Arg = TheCall->getArg(i);
6538 
6539     if (Arg->isTypeDependent())
6540       return false;
6541 
6542     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6543 
6544     if (Res.isInvalid())
6545       return true;
6546     TheCall->setArg(i, Res.get());
6547   }
6548 
6549   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6550 
6551   if (OrigArg->isTypeDependent())
6552     return false;
6553 
6554   // Usual Unary Conversions will convert half to float, which we want for
6555   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6556   // type how it is, but do normal L->Rvalue conversions.
6557   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6558     OrigArg = UsualUnaryConversions(OrigArg).get();
6559   else
6560     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6561   TheCall->setArg(NumArgs - 1, OrigArg);
6562 
6563   // This operation requires a non-_Complex floating-point number.
6564   if (!OrigArg->getType()->isRealFloatingType())
6565     return Diag(OrigArg->getBeginLoc(),
6566                 diag::err_typecheck_call_invalid_unary_fp)
6567            << OrigArg->getType() << OrigArg->getSourceRange();
6568 
6569   return false;
6570 }
6571 
6572 /// Perform semantic analysis for a call to __builtin_complex.
6573 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6574   if (checkArgCount(*this, TheCall, 2))
6575     return true;
6576 
6577   bool Dependent = false;
6578   for (unsigned I = 0; I != 2; ++I) {
6579     Expr *Arg = TheCall->getArg(I);
6580     QualType T = Arg->getType();
6581     if (T->isDependentType()) {
6582       Dependent = true;
6583       continue;
6584     }
6585 
6586     // Despite supporting _Complex int, GCC requires a real floating point type
6587     // for the operands of __builtin_complex.
6588     if (!T->isRealFloatingType()) {
6589       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6590              << Arg->getType() << Arg->getSourceRange();
6591     }
6592 
6593     ExprResult Converted = DefaultLvalueConversion(Arg);
6594     if (Converted.isInvalid())
6595       return true;
6596     TheCall->setArg(I, Converted.get());
6597   }
6598 
6599   if (Dependent) {
6600     TheCall->setType(Context.DependentTy);
6601     return false;
6602   }
6603 
6604   Expr *Real = TheCall->getArg(0);
6605   Expr *Imag = TheCall->getArg(1);
6606   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6607     return Diag(Real->getBeginLoc(),
6608                 diag::err_typecheck_call_different_arg_types)
6609            << Real->getType() << Imag->getType()
6610            << Real->getSourceRange() << Imag->getSourceRange();
6611   }
6612 
6613   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6614   // don't allow this builtin to form those types either.
6615   // FIXME: Should we allow these types?
6616   if (Real->getType()->isFloat16Type())
6617     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6618            << "_Float16";
6619   if (Real->getType()->isHalfType())
6620     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6621            << "half";
6622 
6623   TheCall->setType(Context.getComplexType(Real->getType()));
6624   return false;
6625 }
6626 
6627 // Customized Sema Checking for VSX builtins that have the following signature:
6628 // vector [...] builtinName(vector [...], vector [...], const int);
6629 // Which takes the same type of vectors (any legal vector type) for the first
6630 // two arguments and takes compile time constant for the third argument.
6631 // Example builtins are :
6632 // vector double vec_xxpermdi(vector double, vector double, int);
6633 // vector short vec_xxsldwi(vector short, vector short, int);
6634 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6635   unsigned ExpectedNumArgs = 3;
6636   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6637     return true;
6638 
6639   // Check the third argument is a compile time constant
6640   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6641     return Diag(TheCall->getBeginLoc(),
6642                 diag::err_vsx_builtin_nonconstant_argument)
6643            << 3 /* argument index */ << TheCall->getDirectCallee()
6644            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6645                           TheCall->getArg(2)->getEndLoc());
6646 
6647   QualType Arg1Ty = TheCall->getArg(0)->getType();
6648   QualType Arg2Ty = TheCall->getArg(1)->getType();
6649 
6650   // Check the type of argument 1 and argument 2 are vectors.
6651   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6652   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6653       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6654     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6655            << TheCall->getDirectCallee()
6656            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6657                           TheCall->getArg(1)->getEndLoc());
6658   }
6659 
6660   // Check the first two arguments are the same type.
6661   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6662     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6663            << TheCall->getDirectCallee()
6664            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6665                           TheCall->getArg(1)->getEndLoc());
6666   }
6667 
6668   // When default clang type checking is turned off and the customized type
6669   // checking is used, the returning type of the function must be explicitly
6670   // set. Otherwise it is _Bool by default.
6671   TheCall->setType(Arg1Ty);
6672 
6673   return false;
6674 }
6675 
6676 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6677 // This is declared to take (...), so we have to check everything.
6678 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6679   if (TheCall->getNumArgs() < 2)
6680     return ExprError(Diag(TheCall->getEndLoc(),
6681                           diag::err_typecheck_call_too_few_args_at_least)
6682                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6683                      << TheCall->getSourceRange());
6684 
6685   // Determine which of the following types of shufflevector we're checking:
6686   // 1) unary, vector mask: (lhs, mask)
6687   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6688   QualType resType = TheCall->getArg(0)->getType();
6689   unsigned numElements = 0;
6690 
6691   if (!TheCall->getArg(0)->isTypeDependent() &&
6692       !TheCall->getArg(1)->isTypeDependent()) {
6693     QualType LHSType = TheCall->getArg(0)->getType();
6694     QualType RHSType = TheCall->getArg(1)->getType();
6695 
6696     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6697       return ExprError(
6698           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6699           << TheCall->getDirectCallee()
6700           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6701                          TheCall->getArg(1)->getEndLoc()));
6702 
6703     numElements = LHSType->castAs<VectorType>()->getNumElements();
6704     unsigned numResElements = TheCall->getNumArgs() - 2;
6705 
6706     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6707     // with mask.  If so, verify that RHS is an integer vector type with the
6708     // same number of elts as lhs.
6709     if (TheCall->getNumArgs() == 2) {
6710       if (!RHSType->hasIntegerRepresentation() ||
6711           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6712         return ExprError(Diag(TheCall->getBeginLoc(),
6713                               diag::err_vec_builtin_incompatible_vector)
6714                          << TheCall->getDirectCallee()
6715                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6716                                         TheCall->getArg(1)->getEndLoc()));
6717     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6718       return ExprError(Diag(TheCall->getBeginLoc(),
6719                             diag::err_vec_builtin_incompatible_vector)
6720                        << TheCall->getDirectCallee()
6721                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6722                                       TheCall->getArg(1)->getEndLoc()));
6723     } else if (numElements != numResElements) {
6724       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6725       resType = Context.getVectorType(eltType, numResElements,
6726                                       VectorType::GenericVector);
6727     }
6728   }
6729 
6730   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6731     if (TheCall->getArg(i)->isTypeDependent() ||
6732         TheCall->getArg(i)->isValueDependent())
6733       continue;
6734 
6735     Optional<llvm::APSInt> Result;
6736     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6737       return ExprError(Diag(TheCall->getBeginLoc(),
6738                             diag::err_shufflevector_nonconstant_argument)
6739                        << TheCall->getArg(i)->getSourceRange());
6740 
6741     // Allow -1 which will be translated to undef in the IR.
6742     if (Result->isSigned() && Result->isAllOnesValue())
6743       continue;
6744 
6745     if (Result->getActiveBits() > 64 ||
6746         Result->getZExtValue() >= numElements * 2)
6747       return ExprError(Diag(TheCall->getBeginLoc(),
6748                             diag::err_shufflevector_argument_too_large)
6749                        << TheCall->getArg(i)->getSourceRange());
6750   }
6751 
6752   SmallVector<Expr*, 32> exprs;
6753 
6754   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6755     exprs.push_back(TheCall->getArg(i));
6756     TheCall->setArg(i, nullptr);
6757   }
6758 
6759   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6760                                          TheCall->getCallee()->getBeginLoc(),
6761                                          TheCall->getRParenLoc());
6762 }
6763 
6764 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6765 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6766                                        SourceLocation BuiltinLoc,
6767                                        SourceLocation RParenLoc) {
6768   ExprValueKind VK = VK_PRValue;
6769   ExprObjectKind OK = OK_Ordinary;
6770   QualType DstTy = TInfo->getType();
6771   QualType SrcTy = E->getType();
6772 
6773   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6774     return ExprError(Diag(BuiltinLoc,
6775                           diag::err_convertvector_non_vector)
6776                      << E->getSourceRange());
6777   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6778     return ExprError(Diag(BuiltinLoc,
6779                           diag::err_convertvector_non_vector_type));
6780 
6781   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6782     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6783     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6784     if (SrcElts != DstElts)
6785       return ExprError(Diag(BuiltinLoc,
6786                             diag::err_convertvector_incompatible_vector)
6787                        << E->getSourceRange());
6788   }
6789 
6790   return new (Context)
6791       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6792 }
6793 
6794 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6795 // This is declared to take (const void*, ...) and can take two
6796 // optional constant int args.
6797 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6798   unsigned NumArgs = TheCall->getNumArgs();
6799 
6800   if (NumArgs > 3)
6801     return Diag(TheCall->getEndLoc(),
6802                 diag::err_typecheck_call_too_many_args_at_most)
6803            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6804 
6805   // Argument 0 is checked for us and the remaining arguments must be
6806   // constant integers.
6807   for (unsigned i = 1; i != NumArgs; ++i)
6808     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6809       return true;
6810 
6811   return false;
6812 }
6813 
6814 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6815 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6816   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6817     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6818            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6819   if (checkArgCount(*this, TheCall, 1))
6820     return true;
6821   Expr *Arg = TheCall->getArg(0);
6822   if (Arg->isInstantiationDependent())
6823     return false;
6824 
6825   QualType ArgTy = Arg->getType();
6826   if (!ArgTy->hasFloatingRepresentation())
6827     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6828            << ArgTy;
6829   if (Arg->isLValue()) {
6830     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6831     TheCall->setArg(0, FirstArg.get());
6832   }
6833   TheCall->setType(TheCall->getArg(0)->getType());
6834   return false;
6835 }
6836 
6837 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6838 // __assume does not evaluate its arguments, and should warn if its argument
6839 // has side effects.
6840 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6841   Expr *Arg = TheCall->getArg(0);
6842   if (Arg->isInstantiationDependent()) return false;
6843 
6844   if (Arg->HasSideEffects(Context))
6845     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6846         << Arg->getSourceRange()
6847         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6848 
6849   return false;
6850 }
6851 
6852 /// Handle __builtin_alloca_with_align. This is declared
6853 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6854 /// than 8.
6855 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6856   // The alignment must be a constant integer.
6857   Expr *Arg = TheCall->getArg(1);
6858 
6859   // We can't check the value of a dependent argument.
6860   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6861     if (const auto *UE =
6862             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6863       if (UE->getKind() == UETT_AlignOf ||
6864           UE->getKind() == UETT_PreferredAlignOf)
6865         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6866             << Arg->getSourceRange();
6867 
6868     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6869 
6870     if (!Result.isPowerOf2())
6871       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6872              << Arg->getSourceRange();
6873 
6874     if (Result < Context.getCharWidth())
6875       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6876              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6877 
6878     if (Result > std::numeric_limits<int32_t>::max())
6879       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6880              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6881   }
6882 
6883   return false;
6884 }
6885 
6886 /// Handle __builtin_assume_aligned. This is declared
6887 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6888 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6889   unsigned NumArgs = TheCall->getNumArgs();
6890 
6891   if (NumArgs > 3)
6892     return Diag(TheCall->getEndLoc(),
6893                 diag::err_typecheck_call_too_many_args_at_most)
6894            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6895 
6896   // The alignment must be a constant integer.
6897   Expr *Arg = TheCall->getArg(1);
6898 
6899   // We can't check the value of a dependent argument.
6900   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6901     llvm::APSInt Result;
6902     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6903       return true;
6904 
6905     if (!Result.isPowerOf2())
6906       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6907              << Arg->getSourceRange();
6908 
6909     if (Result > Sema::MaximumAlignment)
6910       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6911           << Arg->getSourceRange() << Sema::MaximumAlignment;
6912   }
6913 
6914   if (NumArgs > 2) {
6915     ExprResult Arg(TheCall->getArg(2));
6916     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6917       Context.getSizeType(), false);
6918     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6919     if (Arg.isInvalid()) return true;
6920     TheCall->setArg(2, Arg.get());
6921   }
6922 
6923   return false;
6924 }
6925 
6926 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6927   unsigned BuiltinID =
6928       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6929   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6930 
6931   unsigned NumArgs = TheCall->getNumArgs();
6932   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6933   if (NumArgs < NumRequiredArgs) {
6934     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6935            << 0 /* function call */ << NumRequiredArgs << NumArgs
6936            << TheCall->getSourceRange();
6937   }
6938   if (NumArgs >= NumRequiredArgs + 0x100) {
6939     return Diag(TheCall->getEndLoc(),
6940                 diag::err_typecheck_call_too_many_args_at_most)
6941            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6942            << TheCall->getSourceRange();
6943   }
6944   unsigned i = 0;
6945 
6946   // For formatting call, check buffer arg.
6947   if (!IsSizeCall) {
6948     ExprResult Arg(TheCall->getArg(i));
6949     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6950         Context, Context.VoidPtrTy, false);
6951     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6952     if (Arg.isInvalid())
6953       return true;
6954     TheCall->setArg(i, Arg.get());
6955     i++;
6956   }
6957 
6958   // Check string literal arg.
6959   unsigned FormatIdx = i;
6960   {
6961     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6962     if (Arg.isInvalid())
6963       return true;
6964     TheCall->setArg(i, Arg.get());
6965     i++;
6966   }
6967 
6968   // Make sure variadic args are scalar.
6969   unsigned FirstDataArg = i;
6970   while (i < NumArgs) {
6971     ExprResult Arg = DefaultVariadicArgumentPromotion(
6972         TheCall->getArg(i), VariadicFunction, nullptr);
6973     if (Arg.isInvalid())
6974       return true;
6975     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6976     if (ArgSize.getQuantity() >= 0x100) {
6977       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6978              << i << (int)ArgSize.getQuantity() << 0xff
6979              << TheCall->getSourceRange();
6980     }
6981     TheCall->setArg(i, Arg.get());
6982     i++;
6983   }
6984 
6985   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6986   // call to avoid duplicate diagnostics.
6987   if (!IsSizeCall) {
6988     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6989     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6990     bool Success = CheckFormatArguments(
6991         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6992         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6993         CheckedVarArgs);
6994     if (!Success)
6995       return true;
6996   }
6997 
6998   if (IsSizeCall) {
6999     TheCall->setType(Context.getSizeType());
7000   } else {
7001     TheCall->setType(Context.VoidPtrTy);
7002   }
7003   return false;
7004 }
7005 
7006 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
7007 /// TheCall is a constant expression.
7008 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
7009                                   llvm::APSInt &Result) {
7010   Expr *Arg = TheCall->getArg(ArgNum);
7011   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
7012   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
7013 
7014   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
7015 
7016   Optional<llvm::APSInt> R;
7017   if (!(R = Arg->getIntegerConstantExpr(Context)))
7018     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
7019            << FDecl->getDeclName() << Arg->getSourceRange();
7020   Result = *R;
7021   return false;
7022 }
7023 
7024 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
7025 /// TheCall is a constant expression in the range [Low, High].
7026 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
7027                                        int Low, int High, bool RangeIsError) {
7028   if (isConstantEvaluated())
7029     return false;
7030   llvm::APSInt Result;
7031 
7032   // We can't check the value of a dependent argument.
7033   Expr *Arg = TheCall->getArg(ArgNum);
7034   if (Arg->isTypeDependent() || Arg->isValueDependent())
7035     return false;
7036 
7037   // Check constant-ness first.
7038   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7039     return true;
7040 
7041   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7042     if (RangeIsError)
7043       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7044              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7045     else
7046       // Defer the warning until we know if the code will be emitted so that
7047       // dead code can ignore this.
7048       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7049                           PDiag(diag::warn_argument_invalid_range)
7050                               << toString(Result, 10) << Low << High
7051                               << Arg->getSourceRange());
7052   }
7053 
7054   return false;
7055 }
7056 
7057 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7058 /// TheCall is a constant expression is a multiple of Num..
7059 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7060                                           unsigned Num) {
7061   llvm::APSInt Result;
7062 
7063   // We can't check the value of a dependent argument.
7064   Expr *Arg = TheCall->getArg(ArgNum);
7065   if (Arg->isTypeDependent() || Arg->isValueDependent())
7066     return false;
7067 
7068   // Check constant-ness first.
7069   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7070     return true;
7071 
7072   if (Result.getSExtValue() % Num != 0)
7073     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7074            << Num << Arg->getSourceRange();
7075 
7076   return false;
7077 }
7078 
7079 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7080 /// constant expression representing a power of 2.
7081 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7082   llvm::APSInt Result;
7083 
7084   // We can't check the value of a dependent argument.
7085   Expr *Arg = TheCall->getArg(ArgNum);
7086   if (Arg->isTypeDependent() || Arg->isValueDependent())
7087     return false;
7088 
7089   // Check constant-ness first.
7090   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7091     return true;
7092 
7093   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7094   // and only if x is a power of 2.
7095   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7096     return false;
7097 
7098   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7099          << Arg->getSourceRange();
7100 }
7101 
7102 static bool IsShiftedByte(llvm::APSInt Value) {
7103   if (Value.isNegative())
7104     return false;
7105 
7106   // Check if it's a shifted byte, by shifting it down
7107   while (true) {
7108     // If the value fits in the bottom byte, the check passes.
7109     if (Value < 0x100)
7110       return true;
7111 
7112     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7113     // fails.
7114     if ((Value & 0xFF) != 0)
7115       return false;
7116 
7117     // If the bottom 8 bits are all 0, but something above that is nonzero,
7118     // then shifting the value right by 8 bits won't affect whether it's a
7119     // shifted byte or not. So do that, and go round again.
7120     Value >>= 8;
7121   }
7122 }
7123 
7124 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7125 /// a constant expression representing an arbitrary byte value shifted left by
7126 /// a multiple of 8 bits.
7127 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7128                                              unsigned ArgBits) {
7129   llvm::APSInt Result;
7130 
7131   // We can't check the value of a dependent argument.
7132   Expr *Arg = TheCall->getArg(ArgNum);
7133   if (Arg->isTypeDependent() || Arg->isValueDependent())
7134     return false;
7135 
7136   // Check constant-ness first.
7137   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7138     return true;
7139 
7140   // Truncate to the given size.
7141   Result = Result.getLoBits(ArgBits);
7142   Result.setIsUnsigned(true);
7143 
7144   if (IsShiftedByte(Result))
7145     return false;
7146 
7147   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7148          << Arg->getSourceRange();
7149 }
7150 
7151 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7152 /// TheCall is a constant expression representing either a shifted byte value,
7153 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7154 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7155 /// Arm MVE intrinsics.
7156 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7157                                                    int ArgNum,
7158                                                    unsigned ArgBits) {
7159   llvm::APSInt Result;
7160 
7161   // We can't check the value of a dependent argument.
7162   Expr *Arg = TheCall->getArg(ArgNum);
7163   if (Arg->isTypeDependent() || Arg->isValueDependent())
7164     return false;
7165 
7166   // Check constant-ness first.
7167   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7168     return true;
7169 
7170   // Truncate to the given size.
7171   Result = Result.getLoBits(ArgBits);
7172   Result.setIsUnsigned(true);
7173 
7174   // Check to see if it's in either of the required forms.
7175   if (IsShiftedByte(Result) ||
7176       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7177     return false;
7178 
7179   return Diag(TheCall->getBeginLoc(),
7180               diag::err_argument_not_shifted_byte_or_xxff)
7181          << Arg->getSourceRange();
7182 }
7183 
7184 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7185 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7186   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7187     if (checkArgCount(*this, TheCall, 2))
7188       return true;
7189     Expr *Arg0 = TheCall->getArg(0);
7190     Expr *Arg1 = TheCall->getArg(1);
7191 
7192     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7193     if (FirstArg.isInvalid())
7194       return true;
7195     QualType FirstArgType = FirstArg.get()->getType();
7196     if (!FirstArgType->isAnyPointerType())
7197       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7198                << "first" << FirstArgType << Arg0->getSourceRange();
7199     TheCall->setArg(0, FirstArg.get());
7200 
7201     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7202     if (SecArg.isInvalid())
7203       return true;
7204     QualType SecArgType = SecArg.get()->getType();
7205     if (!SecArgType->isIntegerType())
7206       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7207                << "second" << SecArgType << Arg1->getSourceRange();
7208 
7209     // Derive the return type from the pointer argument.
7210     TheCall->setType(FirstArgType);
7211     return false;
7212   }
7213 
7214   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7215     if (checkArgCount(*this, TheCall, 2))
7216       return true;
7217 
7218     Expr *Arg0 = TheCall->getArg(0);
7219     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7220     if (FirstArg.isInvalid())
7221       return true;
7222     QualType FirstArgType = FirstArg.get()->getType();
7223     if (!FirstArgType->isAnyPointerType())
7224       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7225                << "first" << FirstArgType << Arg0->getSourceRange();
7226     TheCall->setArg(0, FirstArg.get());
7227 
7228     // Derive the return type from the pointer argument.
7229     TheCall->setType(FirstArgType);
7230 
7231     // Second arg must be an constant in range [0,15]
7232     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7233   }
7234 
7235   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7236     if (checkArgCount(*this, TheCall, 2))
7237       return true;
7238     Expr *Arg0 = TheCall->getArg(0);
7239     Expr *Arg1 = TheCall->getArg(1);
7240 
7241     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7242     if (FirstArg.isInvalid())
7243       return true;
7244     QualType FirstArgType = FirstArg.get()->getType();
7245     if (!FirstArgType->isAnyPointerType())
7246       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7247                << "first" << FirstArgType << Arg0->getSourceRange();
7248 
7249     QualType SecArgType = Arg1->getType();
7250     if (!SecArgType->isIntegerType())
7251       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7252                << "second" << SecArgType << Arg1->getSourceRange();
7253     TheCall->setType(Context.IntTy);
7254     return false;
7255   }
7256 
7257   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7258       BuiltinID == AArch64::BI__builtin_arm_stg) {
7259     if (checkArgCount(*this, TheCall, 1))
7260       return true;
7261     Expr *Arg0 = TheCall->getArg(0);
7262     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7263     if (FirstArg.isInvalid())
7264       return true;
7265 
7266     QualType FirstArgType = FirstArg.get()->getType();
7267     if (!FirstArgType->isAnyPointerType())
7268       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7269                << "first" << FirstArgType << Arg0->getSourceRange();
7270     TheCall->setArg(0, FirstArg.get());
7271 
7272     // Derive the return type from the pointer argument.
7273     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7274       TheCall->setType(FirstArgType);
7275     return false;
7276   }
7277 
7278   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7279     Expr *ArgA = TheCall->getArg(0);
7280     Expr *ArgB = TheCall->getArg(1);
7281 
7282     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7283     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7284 
7285     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7286       return true;
7287 
7288     QualType ArgTypeA = ArgExprA.get()->getType();
7289     QualType ArgTypeB = ArgExprB.get()->getType();
7290 
7291     auto isNull = [&] (Expr *E) -> bool {
7292       return E->isNullPointerConstant(
7293                         Context, Expr::NPC_ValueDependentIsNotNull); };
7294 
7295     // argument should be either a pointer or null
7296     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7297       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7298         << "first" << ArgTypeA << ArgA->getSourceRange();
7299 
7300     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7301       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7302         << "second" << ArgTypeB << ArgB->getSourceRange();
7303 
7304     // Ensure Pointee types are compatible
7305     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7306         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7307       QualType pointeeA = ArgTypeA->getPointeeType();
7308       QualType pointeeB = ArgTypeB->getPointeeType();
7309       if (!Context.typesAreCompatible(
7310              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7311              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7312         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7313           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7314           << ArgB->getSourceRange();
7315       }
7316     }
7317 
7318     // at least one argument should be pointer type
7319     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7320       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7321         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7322 
7323     if (isNull(ArgA)) // adopt type of the other pointer
7324       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7325 
7326     if (isNull(ArgB))
7327       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7328 
7329     TheCall->setArg(0, ArgExprA.get());
7330     TheCall->setArg(1, ArgExprB.get());
7331     TheCall->setType(Context.LongLongTy);
7332     return false;
7333   }
7334   assert(false && "Unhandled ARM MTE intrinsic");
7335   return true;
7336 }
7337 
7338 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7339 /// TheCall is an ARM/AArch64 special register string literal.
7340 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7341                                     int ArgNum, unsigned ExpectedFieldNum,
7342                                     bool AllowName) {
7343   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7344                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7345                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7346                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7347                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7348                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7349   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7350                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7351                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7352                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7353                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7354                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7355   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7356 
7357   // We can't check the value of a dependent argument.
7358   Expr *Arg = TheCall->getArg(ArgNum);
7359   if (Arg->isTypeDependent() || Arg->isValueDependent())
7360     return false;
7361 
7362   // Check if the argument is a string literal.
7363   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7364     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7365            << Arg->getSourceRange();
7366 
7367   // Check the type of special register given.
7368   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7369   SmallVector<StringRef, 6> Fields;
7370   Reg.split(Fields, ":");
7371 
7372   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7373     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7374            << Arg->getSourceRange();
7375 
7376   // If the string is the name of a register then we cannot check that it is
7377   // valid here but if the string is of one the forms described in ACLE then we
7378   // can check that the supplied fields are integers and within the valid
7379   // ranges.
7380   if (Fields.size() > 1) {
7381     bool FiveFields = Fields.size() == 5;
7382 
7383     bool ValidString = true;
7384     if (IsARMBuiltin) {
7385       ValidString &= Fields[0].startswith_insensitive("cp") ||
7386                      Fields[0].startswith_insensitive("p");
7387       if (ValidString)
7388         Fields[0] = Fields[0].drop_front(
7389             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7390 
7391       ValidString &= Fields[2].startswith_insensitive("c");
7392       if (ValidString)
7393         Fields[2] = Fields[2].drop_front(1);
7394 
7395       if (FiveFields) {
7396         ValidString &= Fields[3].startswith_insensitive("c");
7397         if (ValidString)
7398           Fields[3] = Fields[3].drop_front(1);
7399       }
7400     }
7401 
7402     SmallVector<int, 5> Ranges;
7403     if (FiveFields)
7404       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7405     else
7406       Ranges.append({15, 7, 15});
7407 
7408     for (unsigned i=0; i<Fields.size(); ++i) {
7409       int IntField;
7410       ValidString &= !Fields[i].getAsInteger(10, IntField);
7411       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7412     }
7413 
7414     if (!ValidString)
7415       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7416              << Arg->getSourceRange();
7417   } else if (IsAArch64Builtin && Fields.size() == 1) {
7418     // If the register name is one of those that appear in the condition below
7419     // and the special register builtin being used is one of the write builtins,
7420     // then we require that the argument provided for writing to the register
7421     // is an integer constant expression. This is because it will be lowered to
7422     // an MSR (immediate) instruction, so we need to know the immediate at
7423     // compile time.
7424     if (TheCall->getNumArgs() != 2)
7425       return false;
7426 
7427     std::string RegLower = Reg.lower();
7428     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7429         RegLower != "pan" && RegLower != "uao")
7430       return false;
7431 
7432     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7433   }
7434 
7435   return false;
7436 }
7437 
7438 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7439 /// Emit an error and return true on failure; return false on success.
7440 /// TypeStr is a string containing the type descriptor of the value returned by
7441 /// the builtin and the descriptors of the expected type of the arguments.
7442 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7443 
7444   assert((TypeStr[0] != '\0') &&
7445          "Invalid types in PPC MMA builtin declaration");
7446 
7447   unsigned Mask = 0;
7448   unsigned ArgNum = 0;
7449 
7450   // The first type in TypeStr is the type of the value returned by the
7451   // builtin. So we first read that type and change the type of TheCall.
7452   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7453   TheCall->setType(type);
7454 
7455   while (*TypeStr != '\0') {
7456     Mask = 0;
7457     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7458     if (ArgNum >= TheCall->getNumArgs()) {
7459       ArgNum++;
7460       break;
7461     }
7462 
7463     Expr *Arg = TheCall->getArg(ArgNum);
7464     QualType ArgType = Arg->getType();
7465 
7466     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7467         (!ExpectedType->isVoidPointerType() &&
7468            ArgType.getCanonicalType() != ExpectedType))
7469       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7470              << ArgType << ExpectedType << 1 << 0 << 0;
7471 
7472     // If the value of the Mask is not 0, we have a constraint in the size of
7473     // the integer argument so here we ensure the argument is a constant that
7474     // is in the valid range.
7475     if (Mask != 0 &&
7476         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7477       return true;
7478 
7479     ArgNum++;
7480   }
7481 
7482   // In case we exited early from the previous loop, there are other types to
7483   // read from TypeStr. So we need to read them all to ensure we have the right
7484   // number of arguments in TheCall and if it is not the case, to display a
7485   // better error message.
7486   while (*TypeStr != '\0') {
7487     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7488     ArgNum++;
7489   }
7490   if (checkArgCount(*this, TheCall, ArgNum))
7491     return true;
7492 
7493   return false;
7494 }
7495 
7496 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7497 /// This checks that the target supports __builtin_longjmp and
7498 /// that val is a constant 1.
7499 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7500   if (!Context.getTargetInfo().hasSjLjLowering())
7501     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7502            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7503 
7504   Expr *Arg = TheCall->getArg(1);
7505   llvm::APSInt Result;
7506 
7507   // TODO: This is less than ideal. Overload this to take a value.
7508   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7509     return true;
7510 
7511   if (Result != 1)
7512     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7513            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7514 
7515   return false;
7516 }
7517 
7518 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7519 /// This checks that the target supports __builtin_setjmp.
7520 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7521   if (!Context.getTargetInfo().hasSjLjLowering())
7522     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7523            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7524   return false;
7525 }
7526 
7527 namespace {
7528 
7529 class UncoveredArgHandler {
7530   enum { Unknown = -1, AllCovered = -2 };
7531 
7532   signed FirstUncoveredArg = Unknown;
7533   SmallVector<const Expr *, 4> DiagnosticExprs;
7534 
7535 public:
7536   UncoveredArgHandler() = default;
7537 
7538   bool hasUncoveredArg() const {
7539     return (FirstUncoveredArg >= 0);
7540   }
7541 
7542   unsigned getUncoveredArg() const {
7543     assert(hasUncoveredArg() && "no uncovered argument");
7544     return FirstUncoveredArg;
7545   }
7546 
7547   void setAllCovered() {
7548     // A string has been found with all arguments covered, so clear out
7549     // the diagnostics.
7550     DiagnosticExprs.clear();
7551     FirstUncoveredArg = AllCovered;
7552   }
7553 
7554   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7555     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7556 
7557     // Don't update if a previous string covers all arguments.
7558     if (FirstUncoveredArg == AllCovered)
7559       return;
7560 
7561     // UncoveredArgHandler tracks the highest uncovered argument index
7562     // and with it all the strings that match this index.
7563     if (NewFirstUncoveredArg == FirstUncoveredArg)
7564       DiagnosticExprs.push_back(StrExpr);
7565     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7566       DiagnosticExprs.clear();
7567       DiagnosticExprs.push_back(StrExpr);
7568       FirstUncoveredArg = NewFirstUncoveredArg;
7569     }
7570   }
7571 
7572   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7573 };
7574 
7575 enum StringLiteralCheckType {
7576   SLCT_NotALiteral,
7577   SLCT_UncheckedLiteral,
7578   SLCT_CheckedLiteral
7579 };
7580 
7581 } // namespace
7582 
7583 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7584                                      BinaryOperatorKind BinOpKind,
7585                                      bool AddendIsRight) {
7586   unsigned BitWidth = Offset.getBitWidth();
7587   unsigned AddendBitWidth = Addend.getBitWidth();
7588   // There might be negative interim results.
7589   if (Addend.isUnsigned()) {
7590     Addend = Addend.zext(++AddendBitWidth);
7591     Addend.setIsSigned(true);
7592   }
7593   // Adjust the bit width of the APSInts.
7594   if (AddendBitWidth > BitWidth) {
7595     Offset = Offset.sext(AddendBitWidth);
7596     BitWidth = AddendBitWidth;
7597   } else if (BitWidth > AddendBitWidth) {
7598     Addend = Addend.sext(BitWidth);
7599   }
7600 
7601   bool Ov = false;
7602   llvm::APSInt ResOffset = Offset;
7603   if (BinOpKind == BO_Add)
7604     ResOffset = Offset.sadd_ov(Addend, Ov);
7605   else {
7606     assert(AddendIsRight && BinOpKind == BO_Sub &&
7607            "operator must be add or sub with addend on the right");
7608     ResOffset = Offset.ssub_ov(Addend, Ov);
7609   }
7610 
7611   // We add an offset to a pointer here so we should support an offset as big as
7612   // possible.
7613   if (Ov) {
7614     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7615            "index (intermediate) result too big");
7616     Offset = Offset.sext(2 * BitWidth);
7617     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7618     return;
7619   }
7620 
7621   Offset = ResOffset;
7622 }
7623 
7624 namespace {
7625 
7626 // This is a wrapper class around StringLiteral to support offsetted string
7627 // literals as format strings. It takes the offset into account when returning
7628 // the string and its length or the source locations to display notes correctly.
7629 class FormatStringLiteral {
7630   const StringLiteral *FExpr;
7631   int64_t Offset;
7632 
7633  public:
7634   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7635       : FExpr(fexpr), Offset(Offset) {}
7636 
7637   StringRef getString() const {
7638     return FExpr->getString().drop_front(Offset);
7639   }
7640 
7641   unsigned getByteLength() const {
7642     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7643   }
7644 
7645   unsigned getLength() const { return FExpr->getLength() - Offset; }
7646   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7647 
7648   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7649 
7650   QualType getType() const { return FExpr->getType(); }
7651 
7652   bool isAscii() const { return FExpr->isAscii(); }
7653   bool isWide() const { return FExpr->isWide(); }
7654   bool isUTF8() const { return FExpr->isUTF8(); }
7655   bool isUTF16() const { return FExpr->isUTF16(); }
7656   bool isUTF32() const { return FExpr->isUTF32(); }
7657   bool isPascal() const { return FExpr->isPascal(); }
7658 
7659   SourceLocation getLocationOfByte(
7660       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7661       const TargetInfo &Target, unsigned *StartToken = nullptr,
7662       unsigned *StartTokenByteOffset = nullptr) const {
7663     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7664                                     StartToken, StartTokenByteOffset);
7665   }
7666 
7667   SourceLocation getBeginLoc() const LLVM_READONLY {
7668     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7669   }
7670 
7671   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7672 };
7673 
7674 }  // namespace
7675 
7676 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7677                               const Expr *OrigFormatExpr,
7678                               ArrayRef<const Expr *> Args,
7679                               bool HasVAListArg, unsigned format_idx,
7680                               unsigned firstDataArg,
7681                               Sema::FormatStringType Type,
7682                               bool inFunctionCall,
7683                               Sema::VariadicCallType CallType,
7684                               llvm::SmallBitVector &CheckedVarArgs,
7685                               UncoveredArgHandler &UncoveredArg,
7686                               bool IgnoreStringsWithoutSpecifiers);
7687 
7688 // Determine if an expression is a string literal or constant string.
7689 // If this function returns false on the arguments to a function expecting a
7690 // format string, we will usually need to emit a warning.
7691 // True string literals are then checked by CheckFormatString.
7692 static StringLiteralCheckType
7693 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7694                       bool HasVAListArg, unsigned format_idx,
7695                       unsigned firstDataArg, Sema::FormatStringType Type,
7696                       Sema::VariadicCallType CallType, bool InFunctionCall,
7697                       llvm::SmallBitVector &CheckedVarArgs,
7698                       UncoveredArgHandler &UncoveredArg,
7699                       llvm::APSInt Offset,
7700                       bool IgnoreStringsWithoutSpecifiers = false) {
7701   if (S.isConstantEvaluated())
7702     return SLCT_NotALiteral;
7703  tryAgain:
7704   assert(Offset.isSigned() && "invalid offset");
7705 
7706   if (E->isTypeDependent() || E->isValueDependent())
7707     return SLCT_NotALiteral;
7708 
7709   E = E->IgnoreParenCasts();
7710 
7711   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7712     // Technically -Wformat-nonliteral does not warn about this case.
7713     // The behavior of printf and friends in this case is implementation
7714     // dependent.  Ideally if the format string cannot be null then
7715     // it should have a 'nonnull' attribute in the function prototype.
7716     return SLCT_UncheckedLiteral;
7717 
7718   switch (E->getStmtClass()) {
7719   case Stmt::BinaryConditionalOperatorClass:
7720   case Stmt::ConditionalOperatorClass: {
7721     // The expression is a literal if both sub-expressions were, and it was
7722     // completely checked only if both sub-expressions were checked.
7723     const AbstractConditionalOperator *C =
7724         cast<AbstractConditionalOperator>(E);
7725 
7726     // Determine whether it is necessary to check both sub-expressions, for
7727     // example, because the condition expression is a constant that can be
7728     // evaluated at compile time.
7729     bool CheckLeft = true, CheckRight = true;
7730 
7731     bool Cond;
7732     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7733                                                  S.isConstantEvaluated())) {
7734       if (Cond)
7735         CheckRight = false;
7736       else
7737         CheckLeft = false;
7738     }
7739 
7740     // We need to maintain the offsets for the right and the left hand side
7741     // separately to check if every possible indexed expression is a valid
7742     // string literal. They might have different offsets for different string
7743     // literals in the end.
7744     StringLiteralCheckType Left;
7745     if (!CheckLeft)
7746       Left = SLCT_UncheckedLiteral;
7747     else {
7748       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7749                                    HasVAListArg, format_idx, firstDataArg,
7750                                    Type, CallType, InFunctionCall,
7751                                    CheckedVarArgs, UncoveredArg, Offset,
7752                                    IgnoreStringsWithoutSpecifiers);
7753       if (Left == SLCT_NotALiteral || !CheckRight) {
7754         return Left;
7755       }
7756     }
7757 
7758     StringLiteralCheckType Right = checkFormatStringExpr(
7759         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7760         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7761         IgnoreStringsWithoutSpecifiers);
7762 
7763     return (CheckLeft && Left < Right) ? Left : Right;
7764   }
7765 
7766   case Stmt::ImplicitCastExprClass:
7767     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7768     goto tryAgain;
7769 
7770   case Stmt::OpaqueValueExprClass:
7771     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7772       E = src;
7773       goto tryAgain;
7774     }
7775     return SLCT_NotALiteral;
7776 
7777   case Stmt::PredefinedExprClass:
7778     // While __func__, etc., are technically not string literals, they
7779     // cannot contain format specifiers and thus are not a security
7780     // liability.
7781     return SLCT_UncheckedLiteral;
7782 
7783   case Stmt::DeclRefExprClass: {
7784     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7785 
7786     // As an exception, do not flag errors for variables binding to
7787     // const string literals.
7788     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7789       bool isConstant = false;
7790       QualType T = DR->getType();
7791 
7792       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7793         isConstant = AT->getElementType().isConstant(S.Context);
7794       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7795         isConstant = T.isConstant(S.Context) &&
7796                      PT->getPointeeType().isConstant(S.Context);
7797       } else if (T->isObjCObjectPointerType()) {
7798         // In ObjC, there is usually no "const ObjectPointer" type,
7799         // so don't check if the pointee type is constant.
7800         isConstant = T.isConstant(S.Context);
7801       }
7802 
7803       if (isConstant) {
7804         if (const Expr *Init = VD->getAnyInitializer()) {
7805           // Look through initializers like const char c[] = { "foo" }
7806           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7807             if (InitList->isStringLiteralInit())
7808               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7809           }
7810           return checkFormatStringExpr(S, Init, Args,
7811                                        HasVAListArg, format_idx,
7812                                        firstDataArg, Type, CallType,
7813                                        /*InFunctionCall*/ false, CheckedVarArgs,
7814                                        UncoveredArg, Offset);
7815         }
7816       }
7817 
7818       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7819       // special check to see if the format string is a function parameter
7820       // of the function calling the printf function.  If the function
7821       // has an attribute indicating it is a printf-like function, then we
7822       // should suppress warnings concerning non-literals being used in a call
7823       // to a vprintf function.  For example:
7824       //
7825       // void
7826       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7827       //      va_list ap;
7828       //      va_start(ap, fmt);
7829       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7830       //      ...
7831       // }
7832       if (HasVAListArg) {
7833         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7834           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7835             int PVIndex = PV->getFunctionScopeIndex() + 1;
7836             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7837               // adjust for implicit parameter
7838               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7839                 if (MD->isInstance())
7840                   ++PVIndex;
7841               // We also check if the formats are compatible.
7842               // We can't pass a 'scanf' string to a 'printf' function.
7843               if (PVIndex == PVFormat->getFormatIdx() &&
7844                   Type == S.GetFormatStringType(PVFormat))
7845                 return SLCT_UncheckedLiteral;
7846             }
7847           }
7848         }
7849       }
7850     }
7851 
7852     return SLCT_NotALiteral;
7853   }
7854 
7855   case Stmt::CallExprClass:
7856   case Stmt::CXXMemberCallExprClass: {
7857     const CallExpr *CE = cast<CallExpr>(E);
7858     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7859       bool IsFirst = true;
7860       StringLiteralCheckType CommonResult;
7861       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7862         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7863         StringLiteralCheckType Result = checkFormatStringExpr(
7864             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7865             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7866             IgnoreStringsWithoutSpecifiers);
7867         if (IsFirst) {
7868           CommonResult = Result;
7869           IsFirst = false;
7870         }
7871       }
7872       if (!IsFirst)
7873         return CommonResult;
7874 
7875       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7876         unsigned BuiltinID = FD->getBuiltinID();
7877         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7878             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7879           const Expr *Arg = CE->getArg(0);
7880           return checkFormatStringExpr(S, Arg, Args,
7881                                        HasVAListArg, format_idx,
7882                                        firstDataArg, Type, CallType,
7883                                        InFunctionCall, CheckedVarArgs,
7884                                        UncoveredArg, Offset,
7885                                        IgnoreStringsWithoutSpecifiers);
7886         }
7887       }
7888     }
7889 
7890     return SLCT_NotALiteral;
7891   }
7892   case Stmt::ObjCMessageExprClass: {
7893     const auto *ME = cast<ObjCMessageExpr>(E);
7894     if (const auto *MD = ME->getMethodDecl()) {
7895       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7896         // As a special case heuristic, if we're using the method -[NSBundle
7897         // localizedStringForKey:value:table:], ignore any key strings that lack
7898         // format specifiers. The idea is that if the key doesn't have any
7899         // format specifiers then its probably just a key to map to the
7900         // localized strings. If it does have format specifiers though, then its
7901         // likely that the text of the key is the format string in the
7902         // programmer's language, and should be checked.
7903         const ObjCInterfaceDecl *IFace;
7904         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7905             IFace->getIdentifier()->isStr("NSBundle") &&
7906             MD->getSelector().isKeywordSelector(
7907                 {"localizedStringForKey", "value", "table"})) {
7908           IgnoreStringsWithoutSpecifiers = true;
7909         }
7910 
7911         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7912         return checkFormatStringExpr(
7913             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7914             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7915             IgnoreStringsWithoutSpecifiers);
7916       }
7917     }
7918 
7919     return SLCT_NotALiteral;
7920   }
7921   case Stmt::ObjCStringLiteralClass:
7922   case Stmt::StringLiteralClass: {
7923     const StringLiteral *StrE = nullptr;
7924 
7925     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7926       StrE = ObjCFExpr->getString();
7927     else
7928       StrE = cast<StringLiteral>(E);
7929 
7930     if (StrE) {
7931       if (Offset.isNegative() || Offset > StrE->getLength()) {
7932         // TODO: It would be better to have an explicit warning for out of
7933         // bounds literals.
7934         return SLCT_NotALiteral;
7935       }
7936       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7937       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7938                         firstDataArg, Type, InFunctionCall, CallType,
7939                         CheckedVarArgs, UncoveredArg,
7940                         IgnoreStringsWithoutSpecifiers);
7941       return SLCT_CheckedLiteral;
7942     }
7943 
7944     return SLCT_NotALiteral;
7945   }
7946   case Stmt::BinaryOperatorClass: {
7947     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7948 
7949     // A string literal + an int offset is still a string literal.
7950     if (BinOp->isAdditiveOp()) {
7951       Expr::EvalResult LResult, RResult;
7952 
7953       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7954           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7955       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7956           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7957 
7958       if (LIsInt != RIsInt) {
7959         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7960 
7961         if (LIsInt) {
7962           if (BinOpKind == BO_Add) {
7963             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7964             E = BinOp->getRHS();
7965             goto tryAgain;
7966           }
7967         } else {
7968           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7969           E = BinOp->getLHS();
7970           goto tryAgain;
7971         }
7972       }
7973     }
7974 
7975     return SLCT_NotALiteral;
7976   }
7977   case Stmt::UnaryOperatorClass: {
7978     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7979     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7980     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7981       Expr::EvalResult IndexResult;
7982       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7983                                        Expr::SE_NoSideEffects,
7984                                        S.isConstantEvaluated())) {
7985         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7986                    /*RHS is int*/ true);
7987         E = ASE->getBase();
7988         goto tryAgain;
7989       }
7990     }
7991 
7992     return SLCT_NotALiteral;
7993   }
7994 
7995   default:
7996     return SLCT_NotALiteral;
7997   }
7998 }
7999 
8000 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
8001   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
8002       .Case("scanf", FST_Scanf)
8003       .Cases("printf", "printf0", FST_Printf)
8004       .Cases("NSString", "CFString", FST_NSString)
8005       .Case("strftime", FST_Strftime)
8006       .Case("strfmon", FST_Strfmon)
8007       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
8008       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
8009       .Case("os_trace", FST_OSLog)
8010       .Case("os_log", FST_OSLog)
8011       .Default(FST_Unknown);
8012 }
8013 
8014 /// CheckFormatArguments - Check calls to printf and scanf (and similar
8015 /// functions) for correct use of format strings.
8016 /// Returns true if a format string has been fully checked.
8017 bool Sema::CheckFormatArguments(const FormatAttr *Format,
8018                                 ArrayRef<const Expr *> Args,
8019                                 bool IsCXXMember,
8020                                 VariadicCallType CallType,
8021                                 SourceLocation Loc, SourceRange Range,
8022                                 llvm::SmallBitVector &CheckedVarArgs) {
8023   FormatStringInfo FSI;
8024   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
8025     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
8026                                 FSI.FirstDataArg, GetFormatStringType(Format),
8027                                 CallType, Loc, Range, CheckedVarArgs);
8028   return false;
8029 }
8030 
8031 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8032                                 bool HasVAListArg, unsigned format_idx,
8033                                 unsigned firstDataArg, FormatStringType Type,
8034                                 VariadicCallType CallType,
8035                                 SourceLocation Loc, SourceRange Range,
8036                                 llvm::SmallBitVector &CheckedVarArgs) {
8037   // CHECK: printf/scanf-like function is called with no format string.
8038   if (format_idx >= Args.size()) {
8039     Diag(Loc, diag::warn_missing_format_string) << Range;
8040     return false;
8041   }
8042 
8043   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8044 
8045   // CHECK: format string is not a string literal.
8046   //
8047   // Dynamically generated format strings are difficult to
8048   // automatically vet at compile time.  Requiring that format strings
8049   // are string literals: (1) permits the checking of format strings by
8050   // the compiler and thereby (2) can practically remove the source of
8051   // many format string exploits.
8052 
8053   // Format string can be either ObjC string (e.g. @"%d") or
8054   // C string (e.g. "%d")
8055   // ObjC string uses the same format specifiers as C string, so we can use
8056   // the same format string checking logic for both ObjC and C strings.
8057   UncoveredArgHandler UncoveredArg;
8058   StringLiteralCheckType CT =
8059       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8060                             format_idx, firstDataArg, Type, CallType,
8061                             /*IsFunctionCall*/ true, CheckedVarArgs,
8062                             UncoveredArg,
8063                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8064 
8065   // Generate a diagnostic where an uncovered argument is detected.
8066   if (UncoveredArg.hasUncoveredArg()) {
8067     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8068     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8069     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8070   }
8071 
8072   if (CT != SLCT_NotALiteral)
8073     // Literal format string found, check done!
8074     return CT == SLCT_CheckedLiteral;
8075 
8076   // Strftime is particular as it always uses a single 'time' argument,
8077   // so it is safe to pass a non-literal string.
8078   if (Type == FST_Strftime)
8079     return false;
8080 
8081   // Do not emit diag when the string param is a macro expansion and the
8082   // format is either NSString or CFString. This is a hack to prevent
8083   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8084   // which are usually used in place of NS and CF string literals.
8085   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8086   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8087     return false;
8088 
8089   // If there are no arguments specified, warn with -Wformat-security, otherwise
8090   // warn only with -Wformat-nonliteral.
8091   if (Args.size() == firstDataArg) {
8092     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8093       << OrigFormatExpr->getSourceRange();
8094     switch (Type) {
8095     default:
8096       break;
8097     case FST_Kprintf:
8098     case FST_FreeBSDKPrintf:
8099     case FST_Printf:
8100       Diag(FormatLoc, diag::note_format_security_fixit)
8101         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8102       break;
8103     case FST_NSString:
8104       Diag(FormatLoc, diag::note_format_security_fixit)
8105         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8106       break;
8107     }
8108   } else {
8109     Diag(FormatLoc, diag::warn_format_nonliteral)
8110       << OrigFormatExpr->getSourceRange();
8111   }
8112   return false;
8113 }
8114 
8115 namespace {
8116 
8117 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8118 protected:
8119   Sema &S;
8120   const FormatStringLiteral *FExpr;
8121   const Expr *OrigFormatExpr;
8122   const Sema::FormatStringType FSType;
8123   const unsigned FirstDataArg;
8124   const unsigned NumDataArgs;
8125   const char *Beg; // Start of format string.
8126   const bool HasVAListArg;
8127   ArrayRef<const Expr *> Args;
8128   unsigned FormatIdx;
8129   llvm::SmallBitVector CoveredArgs;
8130   bool usesPositionalArgs = false;
8131   bool atFirstArg = true;
8132   bool inFunctionCall;
8133   Sema::VariadicCallType CallType;
8134   llvm::SmallBitVector &CheckedVarArgs;
8135   UncoveredArgHandler &UncoveredArg;
8136 
8137 public:
8138   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8139                      const Expr *origFormatExpr,
8140                      const Sema::FormatStringType type, unsigned firstDataArg,
8141                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8142                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8143                      bool inFunctionCall, Sema::VariadicCallType callType,
8144                      llvm::SmallBitVector &CheckedVarArgs,
8145                      UncoveredArgHandler &UncoveredArg)
8146       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8147         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8148         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8149         inFunctionCall(inFunctionCall), CallType(callType),
8150         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8151     CoveredArgs.resize(numDataArgs);
8152     CoveredArgs.reset();
8153   }
8154 
8155   void DoneProcessing();
8156 
8157   void HandleIncompleteSpecifier(const char *startSpecifier,
8158                                  unsigned specifierLen) override;
8159 
8160   void HandleInvalidLengthModifier(
8161                            const analyze_format_string::FormatSpecifier &FS,
8162                            const analyze_format_string::ConversionSpecifier &CS,
8163                            const char *startSpecifier, unsigned specifierLen,
8164                            unsigned DiagID);
8165 
8166   void HandleNonStandardLengthModifier(
8167                     const analyze_format_string::FormatSpecifier &FS,
8168                     const char *startSpecifier, unsigned specifierLen);
8169 
8170   void HandleNonStandardConversionSpecifier(
8171                     const analyze_format_string::ConversionSpecifier &CS,
8172                     const char *startSpecifier, unsigned specifierLen);
8173 
8174   void HandlePosition(const char *startPos, unsigned posLen) override;
8175 
8176   void HandleInvalidPosition(const char *startSpecifier,
8177                              unsigned specifierLen,
8178                              analyze_format_string::PositionContext p) override;
8179 
8180   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8181 
8182   void HandleNullChar(const char *nullCharacter) override;
8183 
8184   template <typename Range>
8185   static void
8186   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8187                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8188                        bool IsStringLocation, Range StringRange,
8189                        ArrayRef<FixItHint> Fixit = None);
8190 
8191 protected:
8192   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8193                                         const char *startSpec,
8194                                         unsigned specifierLen,
8195                                         const char *csStart, unsigned csLen);
8196 
8197   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8198                                          const char *startSpec,
8199                                          unsigned specifierLen);
8200 
8201   SourceRange getFormatStringRange();
8202   CharSourceRange getSpecifierRange(const char *startSpecifier,
8203                                     unsigned specifierLen);
8204   SourceLocation getLocationOfByte(const char *x);
8205 
8206   const Expr *getDataArg(unsigned i) const;
8207 
8208   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8209                     const analyze_format_string::ConversionSpecifier &CS,
8210                     const char *startSpecifier, unsigned specifierLen,
8211                     unsigned argIndex);
8212 
8213   template <typename Range>
8214   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8215                             bool IsStringLocation, Range StringRange,
8216                             ArrayRef<FixItHint> Fixit = None);
8217 };
8218 
8219 } // namespace
8220 
8221 SourceRange CheckFormatHandler::getFormatStringRange() {
8222   return OrigFormatExpr->getSourceRange();
8223 }
8224 
8225 CharSourceRange CheckFormatHandler::
8226 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8227   SourceLocation Start = getLocationOfByte(startSpecifier);
8228   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8229 
8230   // Advance the end SourceLocation by one due to half-open ranges.
8231   End = End.getLocWithOffset(1);
8232 
8233   return CharSourceRange::getCharRange(Start, End);
8234 }
8235 
8236 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8237   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8238                                   S.getLangOpts(), S.Context.getTargetInfo());
8239 }
8240 
8241 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8242                                                    unsigned specifierLen){
8243   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8244                        getLocationOfByte(startSpecifier),
8245                        /*IsStringLocation*/true,
8246                        getSpecifierRange(startSpecifier, specifierLen));
8247 }
8248 
8249 void CheckFormatHandler::HandleInvalidLengthModifier(
8250     const analyze_format_string::FormatSpecifier &FS,
8251     const analyze_format_string::ConversionSpecifier &CS,
8252     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8253   using namespace analyze_format_string;
8254 
8255   const LengthModifier &LM = FS.getLengthModifier();
8256   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8257 
8258   // See if we know how to fix this length modifier.
8259   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8260   if (FixedLM) {
8261     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8262                          getLocationOfByte(LM.getStart()),
8263                          /*IsStringLocation*/true,
8264                          getSpecifierRange(startSpecifier, specifierLen));
8265 
8266     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8267       << FixedLM->toString()
8268       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8269 
8270   } else {
8271     FixItHint Hint;
8272     if (DiagID == diag::warn_format_nonsensical_length)
8273       Hint = FixItHint::CreateRemoval(LMRange);
8274 
8275     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8276                          getLocationOfByte(LM.getStart()),
8277                          /*IsStringLocation*/true,
8278                          getSpecifierRange(startSpecifier, specifierLen),
8279                          Hint);
8280   }
8281 }
8282 
8283 void CheckFormatHandler::HandleNonStandardLengthModifier(
8284     const analyze_format_string::FormatSpecifier &FS,
8285     const char *startSpecifier, unsigned specifierLen) {
8286   using namespace analyze_format_string;
8287 
8288   const LengthModifier &LM = FS.getLengthModifier();
8289   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8290 
8291   // See if we know how to fix this length modifier.
8292   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8293   if (FixedLM) {
8294     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8295                            << LM.toString() << 0,
8296                          getLocationOfByte(LM.getStart()),
8297                          /*IsStringLocation*/true,
8298                          getSpecifierRange(startSpecifier, specifierLen));
8299 
8300     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8301       << FixedLM->toString()
8302       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8303 
8304   } else {
8305     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8306                            << LM.toString() << 0,
8307                          getLocationOfByte(LM.getStart()),
8308                          /*IsStringLocation*/true,
8309                          getSpecifierRange(startSpecifier, specifierLen));
8310   }
8311 }
8312 
8313 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8314     const analyze_format_string::ConversionSpecifier &CS,
8315     const char *startSpecifier, unsigned specifierLen) {
8316   using namespace analyze_format_string;
8317 
8318   // See if we know how to fix this conversion specifier.
8319   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8320   if (FixedCS) {
8321     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8322                           << CS.toString() << /*conversion specifier*/1,
8323                          getLocationOfByte(CS.getStart()),
8324                          /*IsStringLocation*/true,
8325                          getSpecifierRange(startSpecifier, specifierLen));
8326 
8327     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8328     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8329       << FixedCS->toString()
8330       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8331   } else {
8332     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8333                           << CS.toString() << /*conversion specifier*/1,
8334                          getLocationOfByte(CS.getStart()),
8335                          /*IsStringLocation*/true,
8336                          getSpecifierRange(startSpecifier, specifierLen));
8337   }
8338 }
8339 
8340 void CheckFormatHandler::HandlePosition(const char *startPos,
8341                                         unsigned posLen) {
8342   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8343                                getLocationOfByte(startPos),
8344                                /*IsStringLocation*/true,
8345                                getSpecifierRange(startPos, posLen));
8346 }
8347 
8348 void
8349 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8350                                      analyze_format_string::PositionContext p) {
8351   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8352                          << (unsigned) p,
8353                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8354                        getSpecifierRange(startPos, posLen));
8355 }
8356 
8357 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8358                                             unsigned posLen) {
8359   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8360                                getLocationOfByte(startPos),
8361                                /*IsStringLocation*/true,
8362                                getSpecifierRange(startPos, posLen));
8363 }
8364 
8365 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8366   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8367     // The presence of a null character is likely an error.
8368     EmitFormatDiagnostic(
8369       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8370       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8371       getFormatStringRange());
8372   }
8373 }
8374 
8375 // Note that this may return NULL if there was an error parsing or building
8376 // one of the argument expressions.
8377 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8378   return Args[FirstDataArg + i];
8379 }
8380 
8381 void CheckFormatHandler::DoneProcessing() {
8382   // Does the number of data arguments exceed the number of
8383   // format conversions in the format string?
8384   if (!HasVAListArg) {
8385       // Find any arguments that weren't covered.
8386     CoveredArgs.flip();
8387     signed notCoveredArg = CoveredArgs.find_first();
8388     if (notCoveredArg >= 0) {
8389       assert((unsigned)notCoveredArg < NumDataArgs);
8390       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8391     } else {
8392       UncoveredArg.setAllCovered();
8393     }
8394   }
8395 }
8396 
8397 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8398                                    const Expr *ArgExpr) {
8399   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8400          "Invalid state");
8401 
8402   if (!ArgExpr)
8403     return;
8404 
8405   SourceLocation Loc = ArgExpr->getBeginLoc();
8406 
8407   if (S.getSourceManager().isInSystemMacro(Loc))
8408     return;
8409 
8410   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8411   for (auto E : DiagnosticExprs)
8412     PDiag << E->getSourceRange();
8413 
8414   CheckFormatHandler::EmitFormatDiagnostic(
8415                                   S, IsFunctionCall, DiagnosticExprs[0],
8416                                   PDiag, Loc, /*IsStringLocation*/false,
8417                                   DiagnosticExprs[0]->getSourceRange());
8418 }
8419 
8420 bool
8421 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8422                                                      SourceLocation Loc,
8423                                                      const char *startSpec,
8424                                                      unsigned specifierLen,
8425                                                      const char *csStart,
8426                                                      unsigned csLen) {
8427   bool keepGoing = true;
8428   if (argIndex < NumDataArgs) {
8429     // Consider the argument coverered, even though the specifier doesn't
8430     // make sense.
8431     CoveredArgs.set(argIndex);
8432   }
8433   else {
8434     // If argIndex exceeds the number of data arguments we
8435     // don't issue a warning because that is just a cascade of warnings (and
8436     // they may have intended '%%' anyway). We don't want to continue processing
8437     // the format string after this point, however, as we will like just get
8438     // gibberish when trying to match arguments.
8439     keepGoing = false;
8440   }
8441 
8442   StringRef Specifier(csStart, csLen);
8443 
8444   // If the specifier in non-printable, it could be the first byte of a UTF-8
8445   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8446   // hex value.
8447   std::string CodePointStr;
8448   if (!llvm::sys::locale::isPrint(*csStart)) {
8449     llvm::UTF32 CodePoint;
8450     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8451     const llvm::UTF8 *E =
8452         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8453     llvm::ConversionResult Result =
8454         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8455 
8456     if (Result != llvm::conversionOK) {
8457       unsigned char FirstChar = *csStart;
8458       CodePoint = (llvm::UTF32)FirstChar;
8459     }
8460 
8461     llvm::raw_string_ostream OS(CodePointStr);
8462     if (CodePoint < 256)
8463       OS << "\\x" << llvm::format("%02x", CodePoint);
8464     else if (CodePoint <= 0xFFFF)
8465       OS << "\\u" << llvm::format("%04x", CodePoint);
8466     else
8467       OS << "\\U" << llvm::format("%08x", CodePoint);
8468     OS.flush();
8469     Specifier = CodePointStr;
8470   }
8471 
8472   EmitFormatDiagnostic(
8473       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8474       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8475 
8476   return keepGoing;
8477 }
8478 
8479 void
8480 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8481                                                       const char *startSpec,
8482                                                       unsigned specifierLen) {
8483   EmitFormatDiagnostic(
8484     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8485     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8486 }
8487 
8488 bool
8489 CheckFormatHandler::CheckNumArgs(
8490   const analyze_format_string::FormatSpecifier &FS,
8491   const analyze_format_string::ConversionSpecifier &CS,
8492   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8493 
8494   if (argIndex >= NumDataArgs) {
8495     PartialDiagnostic PDiag = FS.usesPositionalArg()
8496       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8497            << (argIndex+1) << NumDataArgs)
8498       : S.PDiag(diag::warn_printf_insufficient_data_args);
8499     EmitFormatDiagnostic(
8500       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8501       getSpecifierRange(startSpecifier, specifierLen));
8502 
8503     // Since more arguments than conversion tokens are given, by extension
8504     // all arguments are covered, so mark this as so.
8505     UncoveredArg.setAllCovered();
8506     return false;
8507   }
8508   return true;
8509 }
8510 
8511 template<typename Range>
8512 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8513                                               SourceLocation Loc,
8514                                               bool IsStringLocation,
8515                                               Range StringRange,
8516                                               ArrayRef<FixItHint> FixIt) {
8517   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8518                        Loc, IsStringLocation, StringRange, FixIt);
8519 }
8520 
8521 /// If the format string is not within the function call, emit a note
8522 /// so that the function call and string are in diagnostic messages.
8523 ///
8524 /// \param InFunctionCall if true, the format string is within the function
8525 /// call and only one diagnostic message will be produced.  Otherwise, an
8526 /// extra note will be emitted pointing to location of the format string.
8527 ///
8528 /// \param ArgumentExpr the expression that is passed as the format string
8529 /// argument in the function call.  Used for getting locations when two
8530 /// diagnostics are emitted.
8531 ///
8532 /// \param PDiag the callee should already have provided any strings for the
8533 /// diagnostic message.  This function only adds locations and fixits
8534 /// to diagnostics.
8535 ///
8536 /// \param Loc primary location for diagnostic.  If two diagnostics are
8537 /// required, one will be at Loc and a new SourceLocation will be created for
8538 /// the other one.
8539 ///
8540 /// \param IsStringLocation if true, Loc points to the format string should be
8541 /// used for the note.  Otherwise, Loc points to the argument list and will
8542 /// be used with PDiag.
8543 ///
8544 /// \param StringRange some or all of the string to highlight.  This is
8545 /// templated so it can accept either a CharSourceRange or a SourceRange.
8546 ///
8547 /// \param FixIt optional fix it hint for the format string.
8548 template <typename Range>
8549 void CheckFormatHandler::EmitFormatDiagnostic(
8550     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8551     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8552     Range StringRange, ArrayRef<FixItHint> FixIt) {
8553   if (InFunctionCall) {
8554     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8555     D << StringRange;
8556     D << FixIt;
8557   } else {
8558     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8559       << ArgumentExpr->getSourceRange();
8560 
8561     const Sema::SemaDiagnosticBuilder &Note =
8562       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8563              diag::note_format_string_defined);
8564 
8565     Note << StringRange;
8566     Note << FixIt;
8567   }
8568 }
8569 
8570 //===--- CHECK: Printf format string checking ------------------------------===//
8571 
8572 namespace {
8573 
8574 class CheckPrintfHandler : public CheckFormatHandler {
8575 public:
8576   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8577                      const Expr *origFormatExpr,
8578                      const Sema::FormatStringType type, unsigned firstDataArg,
8579                      unsigned numDataArgs, bool isObjC, const char *beg,
8580                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8581                      unsigned formatIdx, bool inFunctionCall,
8582                      Sema::VariadicCallType CallType,
8583                      llvm::SmallBitVector &CheckedVarArgs,
8584                      UncoveredArgHandler &UncoveredArg)
8585       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8586                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8587                            inFunctionCall, CallType, CheckedVarArgs,
8588                            UncoveredArg) {}
8589 
8590   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8591 
8592   /// Returns true if '%@' specifiers are allowed in the format string.
8593   bool allowsObjCArg() const {
8594     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8595            FSType == Sema::FST_OSTrace;
8596   }
8597 
8598   bool HandleInvalidPrintfConversionSpecifier(
8599                                       const analyze_printf::PrintfSpecifier &FS,
8600                                       const char *startSpecifier,
8601                                       unsigned specifierLen) override;
8602 
8603   void handleInvalidMaskType(StringRef MaskType) override;
8604 
8605   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8606                              const char *startSpecifier,
8607                              unsigned specifierLen) override;
8608   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8609                        const char *StartSpecifier,
8610                        unsigned SpecifierLen,
8611                        const Expr *E);
8612 
8613   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8614                     const char *startSpecifier, unsigned specifierLen);
8615   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8616                            const analyze_printf::OptionalAmount &Amt,
8617                            unsigned type,
8618                            const char *startSpecifier, unsigned specifierLen);
8619   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8620                   const analyze_printf::OptionalFlag &flag,
8621                   const char *startSpecifier, unsigned specifierLen);
8622   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8623                          const analyze_printf::OptionalFlag &ignoredFlag,
8624                          const analyze_printf::OptionalFlag &flag,
8625                          const char *startSpecifier, unsigned specifierLen);
8626   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8627                            const Expr *E);
8628 
8629   void HandleEmptyObjCModifierFlag(const char *startFlag,
8630                                    unsigned flagLen) override;
8631 
8632   void HandleInvalidObjCModifierFlag(const char *startFlag,
8633                                             unsigned flagLen) override;
8634 
8635   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8636                                            const char *flagsEnd,
8637                                            const char *conversionPosition)
8638                                              override;
8639 };
8640 
8641 } // namespace
8642 
8643 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8644                                       const analyze_printf::PrintfSpecifier &FS,
8645                                       const char *startSpecifier,
8646                                       unsigned specifierLen) {
8647   const analyze_printf::PrintfConversionSpecifier &CS =
8648     FS.getConversionSpecifier();
8649 
8650   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8651                                           getLocationOfByte(CS.getStart()),
8652                                           startSpecifier, specifierLen,
8653                                           CS.getStart(), CS.getLength());
8654 }
8655 
8656 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8657   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8658 }
8659 
8660 bool CheckPrintfHandler::HandleAmount(
8661                                const analyze_format_string::OptionalAmount &Amt,
8662                                unsigned k, const char *startSpecifier,
8663                                unsigned specifierLen) {
8664   if (Amt.hasDataArgument()) {
8665     if (!HasVAListArg) {
8666       unsigned argIndex = Amt.getArgIndex();
8667       if (argIndex >= NumDataArgs) {
8668         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8669                                << k,
8670                              getLocationOfByte(Amt.getStart()),
8671                              /*IsStringLocation*/true,
8672                              getSpecifierRange(startSpecifier, specifierLen));
8673         // Don't do any more checking.  We will just emit
8674         // spurious errors.
8675         return false;
8676       }
8677 
8678       // Type check the data argument.  It should be an 'int'.
8679       // Although not in conformance with C99, we also allow the argument to be
8680       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8681       // doesn't emit a warning for that case.
8682       CoveredArgs.set(argIndex);
8683       const Expr *Arg = getDataArg(argIndex);
8684       if (!Arg)
8685         return false;
8686 
8687       QualType T = Arg->getType();
8688 
8689       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8690       assert(AT.isValid());
8691 
8692       if (!AT.matchesType(S.Context, T)) {
8693         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8694                                << k << AT.getRepresentativeTypeName(S.Context)
8695                                << T << Arg->getSourceRange(),
8696                              getLocationOfByte(Amt.getStart()),
8697                              /*IsStringLocation*/true,
8698                              getSpecifierRange(startSpecifier, specifierLen));
8699         // Don't do any more checking.  We will just emit
8700         // spurious errors.
8701         return false;
8702       }
8703     }
8704   }
8705   return true;
8706 }
8707 
8708 void CheckPrintfHandler::HandleInvalidAmount(
8709                                       const analyze_printf::PrintfSpecifier &FS,
8710                                       const analyze_printf::OptionalAmount &Amt,
8711                                       unsigned type,
8712                                       const char *startSpecifier,
8713                                       unsigned specifierLen) {
8714   const analyze_printf::PrintfConversionSpecifier &CS =
8715     FS.getConversionSpecifier();
8716 
8717   FixItHint fixit =
8718     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8719       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8720                                  Amt.getConstantLength()))
8721       : FixItHint();
8722 
8723   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8724                          << type << CS.toString(),
8725                        getLocationOfByte(Amt.getStart()),
8726                        /*IsStringLocation*/true,
8727                        getSpecifierRange(startSpecifier, specifierLen),
8728                        fixit);
8729 }
8730 
8731 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8732                                     const analyze_printf::OptionalFlag &flag,
8733                                     const char *startSpecifier,
8734                                     unsigned specifierLen) {
8735   // Warn about pointless flag with a fixit removal.
8736   const analyze_printf::PrintfConversionSpecifier &CS =
8737     FS.getConversionSpecifier();
8738   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8739                          << flag.toString() << CS.toString(),
8740                        getLocationOfByte(flag.getPosition()),
8741                        /*IsStringLocation*/true,
8742                        getSpecifierRange(startSpecifier, specifierLen),
8743                        FixItHint::CreateRemoval(
8744                          getSpecifierRange(flag.getPosition(), 1)));
8745 }
8746 
8747 void CheckPrintfHandler::HandleIgnoredFlag(
8748                                 const analyze_printf::PrintfSpecifier &FS,
8749                                 const analyze_printf::OptionalFlag &ignoredFlag,
8750                                 const analyze_printf::OptionalFlag &flag,
8751                                 const char *startSpecifier,
8752                                 unsigned specifierLen) {
8753   // Warn about ignored flag with a fixit removal.
8754   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8755                          << ignoredFlag.toString() << flag.toString(),
8756                        getLocationOfByte(ignoredFlag.getPosition()),
8757                        /*IsStringLocation*/true,
8758                        getSpecifierRange(startSpecifier, specifierLen),
8759                        FixItHint::CreateRemoval(
8760                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8761 }
8762 
8763 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8764                                                      unsigned flagLen) {
8765   // Warn about an empty flag.
8766   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8767                        getLocationOfByte(startFlag),
8768                        /*IsStringLocation*/true,
8769                        getSpecifierRange(startFlag, flagLen));
8770 }
8771 
8772 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8773                                                        unsigned flagLen) {
8774   // Warn about an invalid flag.
8775   auto Range = getSpecifierRange(startFlag, flagLen);
8776   StringRef flag(startFlag, flagLen);
8777   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8778                       getLocationOfByte(startFlag),
8779                       /*IsStringLocation*/true,
8780                       Range, FixItHint::CreateRemoval(Range));
8781 }
8782 
8783 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8784     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8785     // Warn about using '[...]' without a '@' conversion.
8786     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8787     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8788     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8789                          getLocationOfByte(conversionPosition),
8790                          /*IsStringLocation*/true,
8791                          Range, FixItHint::CreateRemoval(Range));
8792 }
8793 
8794 // Determines if the specified is a C++ class or struct containing
8795 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8796 // "c_str()").
8797 template<typename MemberKind>
8798 static llvm::SmallPtrSet<MemberKind*, 1>
8799 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8800   const RecordType *RT = Ty->getAs<RecordType>();
8801   llvm::SmallPtrSet<MemberKind*, 1> Results;
8802 
8803   if (!RT)
8804     return Results;
8805   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8806   if (!RD || !RD->getDefinition())
8807     return Results;
8808 
8809   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8810                  Sema::LookupMemberName);
8811   R.suppressDiagnostics();
8812 
8813   // We just need to include all members of the right kind turned up by the
8814   // filter, at this point.
8815   if (S.LookupQualifiedName(R, RT->getDecl()))
8816     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8817       NamedDecl *decl = (*I)->getUnderlyingDecl();
8818       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8819         Results.insert(FK);
8820     }
8821   return Results;
8822 }
8823 
8824 /// Check if we could call '.c_str()' on an object.
8825 ///
8826 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8827 /// allow the call, or if it would be ambiguous).
8828 bool Sema::hasCStrMethod(const Expr *E) {
8829   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8830 
8831   MethodSet Results =
8832       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8833   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8834        MI != ME; ++MI)
8835     if ((*MI)->getMinRequiredArguments() == 0)
8836       return true;
8837   return false;
8838 }
8839 
8840 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8841 // better diagnostic if so. AT is assumed to be valid.
8842 // Returns true when a c_str() conversion method is found.
8843 bool CheckPrintfHandler::checkForCStrMembers(
8844     const analyze_printf::ArgType &AT, const Expr *E) {
8845   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8846 
8847   MethodSet Results =
8848       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8849 
8850   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8851        MI != ME; ++MI) {
8852     const CXXMethodDecl *Method = *MI;
8853     if (Method->getMinRequiredArguments() == 0 &&
8854         AT.matchesType(S.Context, Method->getReturnType())) {
8855       // FIXME: Suggest parens if the expression needs them.
8856       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8857       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8858           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8859       return true;
8860     }
8861   }
8862 
8863   return false;
8864 }
8865 
8866 bool
8867 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8868                                             &FS,
8869                                           const char *startSpecifier,
8870                                           unsigned specifierLen) {
8871   using namespace analyze_format_string;
8872   using namespace analyze_printf;
8873 
8874   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8875 
8876   if (FS.consumesDataArgument()) {
8877     if (atFirstArg) {
8878         atFirstArg = false;
8879         usesPositionalArgs = FS.usesPositionalArg();
8880     }
8881     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8882       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8883                                         startSpecifier, specifierLen);
8884       return false;
8885     }
8886   }
8887 
8888   // First check if the field width, precision, and conversion specifier
8889   // have matching data arguments.
8890   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8891                     startSpecifier, specifierLen)) {
8892     return false;
8893   }
8894 
8895   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8896                     startSpecifier, specifierLen)) {
8897     return false;
8898   }
8899 
8900   if (!CS.consumesDataArgument()) {
8901     // FIXME: Technically specifying a precision or field width here
8902     // makes no sense.  Worth issuing a warning at some point.
8903     return true;
8904   }
8905 
8906   // Consume the argument.
8907   unsigned argIndex = FS.getArgIndex();
8908   if (argIndex < NumDataArgs) {
8909     // The check to see if the argIndex is valid will come later.
8910     // We set the bit here because we may exit early from this
8911     // function if we encounter some other error.
8912     CoveredArgs.set(argIndex);
8913   }
8914 
8915   // FreeBSD kernel extensions.
8916   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8917       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8918     // We need at least two arguments.
8919     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8920       return false;
8921 
8922     // Claim the second argument.
8923     CoveredArgs.set(argIndex + 1);
8924 
8925     // Type check the first argument (int for %b, pointer for %D)
8926     const Expr *Ex = getDataArg(argIndex);
8927     const analyze_printf::ArgType &AT =
8928       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8929         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8930     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8931       EmitFormatDiagnostic(
8932           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8933               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8934               << false << Ex->getSourceRange(),
8935           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8936           getSpecifierRange(startSpecifier, specifierLen));
8937 
8938     // Type check the second argument (char * for both %b and %D)
8939     Ex = getDataArg(argIndex + 1);
8940     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8941     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8942       EmitFormatDiagnostic(
8943           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8944               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8945               << false << Ex->getSourceRange(),
8946           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8947           getSpecifierRange(startSpecifier, specifierLen));
8948 
8949      return true;
8950   }
8951 
8952   // Check for using an Objective-C specific conversion specifier
8953   // in a non-ObjC literal.
8954   if (!allowsObjCArg() && CS.isObjCArg()) {
8955     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8956                                                   specifierLen);
8957   }
8958 
8959   // %P can only be used with os_log.
8960   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8961     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8962                                                   specifierLen);
8963   }
8964 
8965   // %n is not allowed with os_log.
8966   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8967     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8968                          getLocationOfByte(CS.getStart()),
8969                          /*IsStringLocation*/ false,
8970                          getSpecifierRange(startSpecifier, specifierLen));
8971 
8972     return true;
8973   }
8974 
8975   // Only scalars are allowed for os_trace.
8976   if (FSType == Sema::FST_OSTrace &&
8977       (CS.getKind() == ConversionSpecifier::PArg ||
8978        CS.getKind() == ConversionSpecifier::sArg ||
8979        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8980     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8981                                                   specifierLen);
8982   }
8983 
8984   // Check for use of public/private annotation outside of os_log().
8985   if (FSType != Sema::FST_OSLog) {
8986     if (FS.isPublic().isSet()) {
8987       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8988                                << "public",
8989                            getLocationOfByte(FS.isPublic().getPosition()),
8990                            /*IsStringLocation*/ false,
8991                            getSpecifierRange(startSpecifier, specifierLen));
8992     }
8993     if (FS.isPrivate().isSet()) {
8994       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8995                                << "private",
8996                            getLocationOfByte(FS.isPrivate().getPosition()),
8997                            /*IsStringLocation*/ false,
8998                            getSpecifierRange(startSpecifier, specifierLen));
8999     }
9000   }
9001 
9002   // Check for invalid use of field width
9003   if (!FS.hasValidFieldWidth()) {
9004     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
9005         startSpecifier, specifierLen);
9006   }
9007 
9008   // Check for invalid use of precision
9009   if (!FS.hasValidPrecision()) {
9010     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
9011         startSpecifier, specifierLen);
9012   }
9013 
9014   // Precision is mandatory for %P specifier.
9015   if (CS.getKind() == ConversionSpecifier::PArg &&
9016       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
9017     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
9018                          getLocationOfByte(startSpecifier),
9019                          /*IsStringLocation*/ false,
9020                          getSpecifierRange(startSpecifier, specifierLen));
9021   }
9022 
9023   // Check each flag does not conflict with any other component.
9024   if (!FS.hasValidThousandsGroupingPrefix())
9025     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
9026   if (!FS.hasValidLeadingZeros())
9027     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
9028   if (!FS.hasValidPlusPrefix())
9029     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9030   if (!FS.hasValidSpacePrefix())
9031     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9032   if (!FS.hasValidAlternativeForm())
9033     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9034   if (!FS.hasValidLeftJustified())
9035     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9036 
9037   // Check that flags are not ignored by another flag
9038   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9039     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9040         startSpecifier, specifierLen);
9041   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9042     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9043             startSpecifier, specifierLen);
9044 
9045   // Check the length modifier is valid with the given conversion specifier.
9046   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9047                                  S.getLangOpts()))
9048     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9049                                 diag::warn_format_nonsensical_length);
9050   else if (!FS.hasStandardLengthModifier())
9051     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9052   else if (!FS.hasStandardLengthConversionCombination())
9053     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9054                                 diag::warn_format_non_standard_conversion_spec);
9055 
9056   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9057     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9058 
9059   // The remaining checks depend on the data arguments.
9060   if (HasVAListArg)
9061     return true;
9062 
9063   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9064     return false;
9065 
9066   const Expr *Arg = getDataArg(argIndex);
9067   if (!Arg)
9068     return true;
9069 
9070   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9071 }
9072 
9073 static bool requiresParensToAddCast(const Expr *E) {
9074   // FIXME: We should have a general way to reason about operator
9075   // precedence and whether parens are actually needed here.
9076   // Take care of a few common cases where they aren't.
9077   const Expr *Inside = E->IgnoreImpCasts();
9078   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9079     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9080 
9081   switch (Inside->getStmtClass()) {
9082   case Stmt::ArraySubscriptExprClass:
9083   case Stmt::CallExprClass:
9084   case Stmt::CharacterLiteralClass:
9085   case Stmt::CXXBoolLiteralExprClass:
9086   case Stmt::DeclRefExprClass:
9087   case Stmt::FloatingLiteralClass:
9088   case Stmt::IntegerLiteralClass:
9089   case Stmt::MemberExprClass:
9090   case Stmt::ObjCArrayLiteralClass:
9091   case Stmt::ObjCBoolLiteralExprClass:
9092   case Stmt::ObjCBoxedExprClass:
9093   case Stmt::ObjCDictionaryLiteralClass:
9094   case Stmt::ObjCEncodeExprClass:
9095   case Stmt::ObjCIvarRefExprClass:
9096   case Stmt::ObjCMessageExprClass:
9097   case Stmt::ObjCPropertyRefExprClass:
9098   case Stmt::ObjCStringLiteralClass:
9099   case Stmt::ObjCSubscriptRefExprClass:
9100   case Stmt::ParenExprClass:
9101   case Stmt::StringLiteralClass:
9102   case Stmt::UnaryOperatorClass:
9103     return false;
9104   default:
9105     return true;
9106   }
9107 }
9108 
9109 static std::pair<QualType, StringRef>
9110 shouldNotPrintDirectly(const ASTContext &Context,
9111                        QualType IntendedTy,
9112                        const Expr *E) {
9113   // Use a 'while' to peel off layers of typedefs.
9114   QualType TyTy = IntendedTy;
9115   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9116     StringRef Name = UserTy->getDecl()->getName();
9117     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9118       .Case("CFIndex", Context.getNSIntegerType())
9119       .Case("NSInteger", Context.getNSIntegerType())
9120       .Case("NSUInteger", Context.getNSUIntegerType())
9121       .Case("SInt32", Context.IntTy)
9122       .Case("UInt32", Context.UnsignedIntTy)
9123       .Default(QualType());
9124 
9125     if (!CastTy.isNull())
9126       return std::make_pair(CastTy, Name);
9127 
9128     TyTy = UserTy->desugar();
9129   }
9130 
9131   // Strip parens if necessary.
9132   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9133     return shouldNotPrintDirectly(Context,
9134                                   PE->getSubExpr()->getType(),
9135                                   PE->getSubExpr());
9136 
9137   // If this is a conditional expression, then its result type is constructed
9138   // via usual arithmetic conversions and thus there might be no necessary
9139   // typedef sugar there.  Recurse to operands to check for NSInteger &
9140   // Co. usage condition.
9141   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9142     QualType TrueTy, FalseTy;
9143     StringRef TrueName, FalseName;
9144 
9145     std::tie(TrueTy, TrueName) =
9146       shouldNotPrintDirectly(Context,
9147                              CO->getTrueExpr()->getType(),
9148                              CO->getTrueExpr());
9149     std::tie(FalseTy, FalseName) =
9150       shouldNotPrintDirectly(Context,
9151                              CO->getFalseExpr()->getType(),
9152                              CO->getFalseExpr());
9153 
9154     if (TrueTy == FalseTy)
9155       return std::make_pair(TrueTy, TrueName);
9156     else if (TrueTy.isNull())
9157       return std::make_pair(FalseTy, FalseName);
9158     else if (FalseTy.isNull())
9159       return std::make_pair(TrueTy, TrueName);
9160   }
9161 
9162   return std::make_pair(QualType(), StringRef());
9163 }
9164 
9165 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9166 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9167 /// type do not count.
9168 static bool
9169 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9170   QualType From = ICE->getSubExpr()->getType();
9171   QualType To = ICE->getType();
9172   // It's an integer promotion if the destination type is the promoted
9173   // source type.
9174   if (ICE->getCastKind() == CK_IntegralCast &&
9175       From->isPromotableIntegerType() &&
9176       S.Context.getPromotedIntegerType(From) == To)
9177     return true;
9178   // Look through vector types, since we do default argument promotion for
9179   // those in OpenCL.
9180   if (const auto *VecTy = From->getAs<ExtVectorType>())
9181     From = VecTy->getElementType();
9182   if (const auto *VecTy = To->getAs<ExtVectorType>())
9183     To = VecTy->getElementType();
9184   // It's a floating promotion if the source type is a lower rank.
9185   return ICE->getCastKind() == CK_FloatingCast &&
9186          S.Context.getFloatingTypeOrder(From, To) < 0;
9187 }
9188 
9189 bool
9190 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9191                                     const char *StartSpecifier,
9192                                     unsigned SpecifierLen,
9193                                     const Expr *E) {
9194   using namespace analyze_format_string;
9195   using namespace analyze_printf;
9196 
9197   // Now type check the data expression that matches the
9198   // format specifier.
9199   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9200   if (!AT.isValid())
9201     return true;
9202 
9203   QualType ExprTy = E->getType();
9204   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9205     ExprTy = TET->getUnderlyingExpr()->getType();
9206   }
9207 
9208   // Diagnose attempts to print a boolean value as a character. Unlike other
9209   // -Wformat diagnostics, this is fine from a type perspective, but it still
9210   // doesn't make sense.
9211   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9212       E->isKnownToHaveBooleanValue()) {
9213     const CharSourceRange &CSR =
9214         getSpecifierRange(StartSpecifier, SpecifierLen);
9215     SmallString<4> FSString;
9216     llvm::raw_svector_ostream os(FSString);
9217     FS.toString(os);
9218     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9219                              << FSString,
9220                          E->getExprLoc(), false, CSR);
9221     return true;
9222   }
9223 
9224   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9225   if (Match == analyze_printf::ArgType::Match)
9226     return true;
9227 
9228   // Look through argument promotions for our error message's reported type.
9229   // This includes the integral and floating promotions, but excludes array
9230   // and function pointer decay (seeing that an argument intended to be a
9231   // string has type 'char [6]' is probably more confusing than 'char *') and
9232   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9233   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9234     if (isArithmeticArgumentPromotion(S, ICE)) {
9235       E = ICE->getSubExpr();
9236       ExprTy = E->getType();
9237 
9238       // Check if we didn't match because of an implicit cast from a 'char'
9239       // or 'short' to an 'int'.  This is done because printf is a varargs
9240       // function.
9241       if (ICE->getType() == S.Context.IntTy ||
9242           ICE->getType() == S.Context.UnsignedIntTy) {
9243         // All further checking is done on the subexpression
9244         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9245             AT.matchesType(S.Context, ExprTy);
9246         if (ImplicitMatch == analyze_printf::ArgType::Match)
9247           return true;
9248         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9249             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9250           Match = ImplicitMatch;
9251       }
9252     }
9253   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9254     // Special case for 'a', which has type 'int' in C.
9255     // Note, however, that we do /not/ want to treat multibyte constants like
9256     // 'MooV' as characters! This form is deprecated but still exists. In
9257     // addition, don't treat expressions as of type 'char' if one byte length
9258     // modifier is provided.
9259     if (ExprTy == S.Context.IntTy &&
9260         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9261       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9262         ExprTy = S.Context.CharTy;
9263   }
9264 
9265   // Look through enums to their underlying type.
9266   bool IsEnum = false;
9267   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9268     ExprTy = EnumTy->getDecl()->getIntegerType();
9269     IsEnum = true;
9270   }
9271 
9272   // %C in an Objective-C context prints a unichar, not a wchar_t.
9273   // If the argument is an integer of some kind, believe the %C and suggest
9274   // a cast instead of changing the conversion specifier.
9275   QualType IntendedTy = ExprTy;
9276   if (isObjCContext() &&
9277       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9278     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9279         !ExprTy->isCharType()) {
9280       // 'unichar' is defined as a typedef of unsigned short, but we should
9281       // prefer using the typedef if it is visible.
9282       IntendedTy = S.Context.UnsignedShortTy;
9283 
9284       // While we are here, check if the value is an IntegerLiteral that happens
9285       // to be within the valid range.
9286       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9287         const llvm::APInt &V = IL->getValue();
9288         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9289           return true;
9290       }
9291 
9292       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9293                           Sema::LookupOrdinaryName);
9294       if (S.LookupName(Result, S.getCurScope())) {
9295         NamedDecl *ND = Result.getFoundDecl();
9296         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9297           if (TD->getUnderlyingType() == IntendedTy)
9298             IntendedTy = S.Context.getTypedefType(TD);
9299       }
9300     }
9301   }
9302 
9303   // Special-case some of Darwin's platform-independence types by suggesting
9304   // casts to primitive types that are known to be large enough.
9305   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9306   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9307     QualType CastTy;
9308     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9309     if (!CastTy.isNull()) {
9310       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9311       // (long in ASTContext). Only complain to pedants.
9312       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9313           (AT.isSizeT() || AT.isPtrdiffT()) &&
9314           AT.matchesType(S.Context, CastTy))
9315         Match = ArgType::NoMatchPedantic;
9316       IntendedTy = CastTy;
9317       ShouldNotPrintDirectly = true;
9318     }
9319   }
9320 
9321   // We may be able to offer a FixItHint if it is a supported type.
9322   PrintfSpecifier fixedFS = FS;
9323   bool Success =
9324       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9325 
9326   if (Success) {
9327     // Get the fix string from the fixed format specifier
9328     SmallString<16> buf;
9329     llvm::raw_svector_ostream os(buf);
9330     fixedFS.toString(os);
9331 
9332     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9333 
9334     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9335       unsigned Diag;
9336       switch (Match) {
9337       case ArgType::Match: llvm_unreachable("expected non-matching");
9338       case ArgType::NoMatchPedantic:
9339         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9340         break;
9341       case ArgType::NoMatchTypeConfusion:
9342         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9343         break;
9344       case ArgType::NoMatch:
9345         Diag = diag::warn_format_conversion_argument_type_mismatch;
9346         break;
9347       }
9348 
9349       // In this case, the specifier is wrong and should be changed to match
9350       // the argument.
9351       EmitFormatDiagnostic(S.PDiag(Diag)
9352                                << AT.getRepresentativeTypeName(S.Context)
9353                                << IntendedTy << IsEnum << E->getSourceRange(),
9354                            E->getBeginLoc(),
9355                            /*IsStringLocation*/ false, SpecRange,
9356                            FixItHint::CreateReplacement(SpecRange, os.str()));
9357     } else {
9358       // The canonical type for formatting this value is different from the
9359       // actual type of the expression. (This occurs, for example, with Darwin's
9360       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9361       // should be printed as 'long' for 64-bit compatibility.)
9362       // Rather than emitting a normal format/argument mismatch, we want to
9363       // add a cast to the recommended type (and correct the format string
9364       // if necessary).
9365       SmallString<16> CastBuf;
9366       llvm::raw_svector_ostream CastFix(CastBuf);
9367       CastFix << "(";
9368       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9369       CastFix << ")";
9370 
9371       SmallVector<FixItHint,4> Hints;
9372       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9373         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9374 
9375       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9376         // If there's already a cast present, just replace it.
9377         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9378         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9379 
9380       } else if (!requiresParensToAddCast(E)) {
9381         // If the expression has high enough precedence,
9382         // just write the C-style cast.
9383         Hints.push_back(
9384             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9385       } else {
9386         // Otherwise, add parens around the expression as well as the cast.
9387         CastFix << "(";
9388         Hints.push_back(
9389             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9390 
9391         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9392         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9393       }
9394 
9395       if (ShouldNotPrintDirectly) {
9396         // The expression has a type that should not be printed directly.
9397         // We extract the name from the typedef because we don't want to show
9398         // the underlying type in the diagnostic.
9399         StringRef Name;
9400         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9401           Name = TypedefTy->getDecl()->getName();
9402         else
9403           Name = CastTyName;
9404         unsigned Diag = Match == ArgType::NoMatchPedantic
9405                             ? diag::warn_format_argument_needs_cast_pedantic
9406                             : diag::warn_format_argument_needs_cast;
9407         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9408                                            << E->getSourceRange(),
9409                              E->getBeginLoc(), /*IsStringLocation=*/false,
9410                              SpecRange, Hints);
9411       } else {
9412         // In this case, the expression could be printed using a different
9413         // specifier, but we've decided that the specifier is probably correct
9414         // and we should cast instead. Just use the normal warning message.
9415         EmitFormatDiagnostic(
9416             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9417                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9418                 << E->getSourceRange(),
9419             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9420       }
9421     }
9422   } else {
9423     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9424                                                    SpecifierLen);
9425     // Since the warning for passing non-POD types to variadic functions
9426     // was deferred until now, we emit a warning for non-POD
9427     // arguments here.
9428     switch (S.isValidVarArgType(ExprTy)) {
9429     case Sema::VAK_Valid:
9430     case Sema::VAK_ValidInCXX11: {
9431       unsigned Diag;
9432       switch (Match) {
9433       case ArgType::Match: llvm_unreachable("expected non-matching");
9434       case ArgType::NoMatchPedantic:
9435         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9436         break;
9437       case ArgType::NoMatchTypeConfusion:
9438         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9439         break;
9440       case ArgType::NoMatch:
9441         Diag = diag::warn_format_conversion_argument_type_mismatch;
9442         break;
9443       }
9444 
9445       EmitFormatDiagnostic(
9446           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9447                         << IsEnum << CSR << E->getSourceRange(),
9448           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9449       break;
9450     }
9451     case Sema::VAK_Undefined:
9452     case Sema::VAK_MSVCUndefined:
9453       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9454                                << S.getLangOpts().CPlusPlus11 << ExprTy
9455                                << CallType
9456                                << AT.getRepresentativeTypeName(S.Context) << CSR
9457                                << E->getSourceRange(),
9458                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9459       checkForCStrMembers(AT, E);
9460       break;
9461 
9462     case Sema::VAK_Invalid:
9463       if (ExprTy->isObjCObjectType())
9464         EmitFormatDiagnostic(
9465             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9466                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9467                 << AT.getRepresentativeTypeName(S.Context) << CSR
9468                 << E->getSourceRange(),
9469             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9470       else
9471         // FIXME: If this is an initializer list, suggest removing the braces
9472         // or inserting a cast to the target type.
9473         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9474             << isa<InitListExpr>(E) << ExprTy << CallType
9475             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9476       break;
9477     }
9478 
9479     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9480            "format string specifier index out of range");
9481     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9482   }
9483 
9484   return true;
9485 }
9486 
9487 //===--- CHECK: Scanf format string checking ------------------------------===//
9488 
9489 namespace {
9490 
9491 class CheckScanfHandler : public CheckFormatHandler {
9492 public:
9493   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9494                     const Expr *origFormatExpr, Sema::FormatStringType type,
9495                     unsigned firstDataArg, unsigned numDataArgs,
9496                     const char *beg, bool hasVAListArg,
9497                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9498                     bool inFunctionCall, Sema::VariadicCallType CallType,
9499                     llvm::SmallBitVector &CheckedVarArgs,
9500                     UncoveredArgHandler &UncoveredArg)
9501       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9502                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9503                            inFunctionCall, CallType, CheckedVarArgs,
9504                            UncoveredArg) {}
9505 
9506   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9507                             const char *startSpecifier,
9508                             unsigned specifierLen) override;
9509 
9510   bool HandleInvalidScanfConversionSpecifier(
9511           const analyze_scanf::ScanfSpecifier &FS,
9512           const char *startSpecifier,
9513           unsigned specifierLen) override;
9514 
9515   void HandleIncompleteScanList(const char *start, const char *end) override;
9516 };
9517 
9518 } // namespace
9519 
9520 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9521                                                  const char *end) {
9522   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9523                        getLocationOfByte(end), /*IsStringLocation*/true,
9524                        getSpecifierRange(start, end - start));
9525 }
9526 
9527 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9528                                         const analyze_scanf::ScanfSpecifier &FS,
9529                                         const char *startSpecifier,
9530                                         unsigned specifierLen) {
9531   const analyze_scanf::ScanfConversionSpecifier &CS =
9532     FS.getConversionSpecifier();
9533 
9534   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9535                                           getLocationOfByte(CS.getStart()),
9536                                           startSpecifier, specifierLen,
9537                                           CS.getStart(), CS.getLength());
9538 }
9539 
9540 bool CheckScanfHandler::HandleScanfSpecifier(
9541                                        const analyze_scanf::ScanfSpecifier &FS,
9542                                        const char *startSpecifier,
9543                                        unsigned specifierLen) {
9544   using namespace analyze_scanf;
9545   using namespace analyze_format_string;
9546 
9547   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9548 
9549   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9550   // be used to decide if we are using positional arguments consistently.
9551   if (FS.consumesDataArgument()) {
9552     if (atFirstArg) {
9553       atFirstArg = false;
9554       usesPositionalArgs = FS.usesPositionalArg();
9555     }
9556     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9557       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9558                                         startSpecifier, specifierLen);
9559       return false;
9560     }
9561   }
9562 
9563   // Check if the field with is non-zero.
9564   const OptionalAmount &Amt = FS.getFieldWidth();
9565   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9566     if (Amt.getConstantAmount() == 0) {
9567       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9568                                                    Amt.getConstantLength());
9569       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9570                            getLocationOfByte(Amt.getStart()),
9571                            /*IsStringLocation*/true, R,
9572                            FixItHint::CreateRemoval(R));
9573     }
9574   }
9575 
9576   if (!FS.consumesDataArgument()) {
9577     // FIXME: Technically specifying a precision or field width here
9578     // makes no sense.  Worth issuing a warning at some point.
9579     return true;
9580   }
9581 
9582   // Consume the argument.
9583   unsigned argIndex = FS.getArgIndex();
9584   if (argIndex < NumDataArgs) {
9585       // The check to see if the argIndex is valid will come later.
9586       // We set the bit here because we may exit early from this
9587       // function if we encounter some other error.
9588     CoveredArgs.set(argIndex);
9589   }
9590 
9591   // Check the length modifier is valid with the given conversion specifier.
9592   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9593                                  S.getLangOpts()))
9594     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9595                                 diag::warn_format_nonsensical_length);
9596   else if (!FS.hasStandardLengthModifier())
9597     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9598   else if (!FS.hasStandardLengthConversionCombination())
9599     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9600                                 diag::warn_format_non_standard_conversion_spec);
9601 
9602   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9603     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9604 
9605   // The remaining checks depend on the data arguments.
9606   if (HasVAListArg)
9607     return true;
9608 
9609   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9610     return false;
9611 
9612   // Check that the argument type matches the format specifier.
9613   const Expr *Ex = getDataArg(argIndex);
9614   if (!Ex)
9615     return true;
9616 
9617   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9618 
9619   if (!AT.isValid()) {
9620     return true;
9621   }
9622 
9623   analyze_format_string::ArgType::MatchKind Match =
9624       AT.matchesType(S.Context, Ex->getType());
9625   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9626   if (Match == analyze_format_string::ArgType::Match)
9627     return true;
9628 
9629   ScanfSpecifier fixedFS = FS;
9630   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9631                                  S.getLangOpts(), S.Context);
9632 
9633   unsigned Diag =
9634       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9635                : diag::warn_format_conversion_argument_type_mismatch;
9636 
9637   if (Success) {
9638     // Get the fix string from the fixed format specifier.
9639     SmallString<128> buf;
9640     llvm::raw_svector_ostream os(buf);
9641     fixedFS.toString(os);
9642 
9643     EmitFormatDiagnostic(
9644         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9645                       << Ex->getType() << false << Ex->getSourceRange(),
9646         Ex->getBeginLoc(),
9647         /*IsStringLocation*/ false,
9648         getSpecifierRange(startSpecifier, specifierLen),
9649         FixItHint::CreateReplacement(
9650             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9651   } else {
9652     EmitFormatDiagnostic(S.PDiag(Diag)
9653                              << AT.getRepresentativeTypeName(S.Context)
9654                              << Ex->getType() << false << Ex->getSourceRange(),
9655                          Ex->getBeginLoc(),
9656                          /*IsStringLocation*/ false,
9657                          getSpecifierRange(startSpecifier, specifierLen));
9658   }
9659 
9660   return true;
9661 }
9662 
9663 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9664                               const Expr *OrigFormatExpr,
9665                               ArrayRef<const Expr *> Args,
9666                               bool HasVAListArg, unsigned format_idx,
9667                               unsigned firstDataArg,
9668                               Sema::FormatStringType Type,
9669                               bool inFunctionCall,
9670                               Sema::VariadicCallType CallType,
9671                               llvm::SmallBitVector &CheckedVarArgs,
9672                               UncoveredArgHandler &UncoveredArg,
9673                               bool IgnoreStringsWithoutSpecifiers) {
9674   // CHECK: is the format string a wide literal?
9675   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9676     CheckFormatHandler::EmitFormatDiagnostic(
9677         S, inFunctionCall, Args[format_idx],
9678         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9679         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9680     return;
9681   }
9682 
9683   // Str - The format string.  NOTE: this is NOT null-terminated!
9684   StringRef StrRef = FExpr->getString();
9685   const char *Str = StrRef.data();
9686   // Account for cases where the string literal is truncated in a declaration.
9687   const ConstantArrayType *T =
9688     S.Context.getAsConstantArrayType(FExpr->getType());
9689   assert(T && "String literal not of constant array type!");
9690   size_t TypeSize = T->getSize().getZExtValue();
9691   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9692   const unsigned numDataArgs = Args.size() - firstDataArg;
9693 
9694   if (IgnoreStringsWithoutSpecifiers &&
9695       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9696           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9697     return;
9698 
9699   // Emit a warning if the string literal is truncated and does not contain an
9700   // embedded null character.
9701   if (TypeSize <= StrRef.size() &&
9702       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9703     CheckFormatHandler::EmitFormatDiagnostic(
9704         S, inFunctionCall, Args[format_idx],
9705         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9706         FExpr->getBeginLoc(),
9707         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9708     return;
9709   }
9710 
9711   // CHECK: empty format string?
9712   if (StrLen == 0 && numDataArgs > 0) {
9713     CheckFormatHandler::EmitFormatDiagnostic(
9714         S, inFunctionCall, Args[format_idx],
9715         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9716         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9717     return;
9718   }
9719 
9720   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9721       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9722       Type == Sema::FST_OSTrace) {
9723     CheckPrintfHandler H(
9724         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9725         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9726         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9727         CheckedVarArgs, UncoveredArg);
9728 
9729     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9730                                                   S.getLangOpts(),
9731                                                   S.Context.getTargetInfo(),
9732                                             Type == Sema::FST_FreeBSDKPrintf))
9733       H.DoneProcessing();
9734   } else if (Type == Sema::FST_Scanf) {
9735     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9736                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9737                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9738 
9739     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9740                                                  S.getLangOpts(),
9741                                                  S.Context.getTargetInfo()))
9742       H.DoneProcessing();
9743   } // TODO: handle other formats
9744 }
9745 
9746 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9747   // Str - The format string.  NOTE: this is NOT null-terminated!
9748   StringRef StrRef = FExpr->getString();
9749   const char *Str = StrRef.data();
9750   // Account for cases where the string literal is truncated in a declaration.
9751   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9752   assert(T && "String literal not of constant array type!");
9753   size_t TypeSize = T->getSize().getZExtValue();
9754   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9755   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9756                                                          getLangOpts(),
9757                                                          Context.getTargetInfo());
9758 }
9759 
9760 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9761 
9762 // Returns the related absolute value function that is larger, of 0 if one
9763 // does not exist.
9764 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9765   switch (AbsFunction) {
9766   default:
9767     return 0;
9768 
9769   case Builtin::BI__builtin_abs:
9770     return Builtin::BI__builtin_labs;
9771   case Builtin::BI__builtin_labs:
9772     return Builtin::BI__builtin_llabs;
9773   case Builtin::BI__builtin_llabs:
9774     return 0;
9775 
9776   case Builtin::BI__builtin_fabsf:
9777     return Builtin::BI__builtin_fabs;
9778   case Builtin::BI__builtin_fabs:
9779     return Builtin::BI__builtin_fabsl;
9780   case Builtin::BI__builtin_fabsl:
9781     return 0;
9782 
9783   case Builtin::BI__builtin_cabsf:
9784     return Builtin::BI__builtin_cabs;
9785   case Builtin::BI__builtin_cabs:
9786     return Builtin::BI__builtin_cabsl;
9787   case Builtin::BI__builtin_cabsl:
9788     return 0;
9789 
9790   case Builtin::BIabs:
9791     return Builtin::BIlabs;
9792   case Builtin::BIlabs:
9793     return Builtin::BIllabs;
9794   case Builtin::BIllabs:
9795     return 0;
9796 
9797   case Builtin::BIfabsf:
9798     return Builtin::BIfabs;
9799   case Builtin::BIfabs:
9800     return Builtin::BIfabsl;
9801   case Builtin::BIfabsl:
9802     return 0;
9803 
9804   case Builtin::BIcabsf:
9805    return Builtin::BIcabs;
9806   case Builtin::BIcabs:
9807     return Builtin::BIcabsl;
9808   case Builtin::BIcabsl:
9809     return 0;
9810   }
9811 }
9812 
9813 // Returns the argument type of the absolute value function.
9814 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9815                                              unsigned AbsType) {
9816   if (AbsType == 0)
9817     return QualType();
9818 
9819   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9820   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9821   if (Error != ASTContext::GE_None)
9822     return QualType();
9823 
9824   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9825   if (!FT)
9826     return QualType();
9827 
9828   if (FT->getNumParams() != 1)
9829     return QualType();
9830 
9831   return FT->getParamType(0);
9832 }
9833 
9834 // Returns the best absolute value function, or zero, based on type and
9835 // current absolute value function.
9836 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9837                                    unsigned AbsFunctionKind) {
9838   unsigned BestKind = 0;
9839   uint64_t ArgSize = Context.getTypeSize(ArgType);
9840   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9841        Kind = getLargerAbsoluteValueFunction(Kind)) {
9842     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9843     if (Context.getTypeSize(ParamType) >= ArgSize) {
9844       if (BestKind == 0)
9845         BestKind = Kind;
9846       else if (Context.hasSameType(ParamType, ArgType)) {
9847         BestKind = Kind;
9848         break;
9849       }
9850     }
9851   }
9852   return BestKind;
9853 }
9854 
9855 enum AbsoluteValueKind {
9856   AVK_Integer,
9857   AVK_Floating,
9858   AVK_Complex
9859 };
9860 
9861 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9862   if (T->isIntegralOrEnumerationType())
9863     return AVK_Integer;
9864   if (T->isRealFloatingType())
9865     return AVK_Floating;
9866   if (T->isAnyComplexType())
9867     return AVK_Complex;
9868 
9869   llvm_unreachable("Type not integer, floating, or complex");
9870 }
9871 
9872 // Changes the absolute value function to a different type.  Preserves whether
9873 // the function is a builtin.
9874 static unsigned changeAbsFunction(unsigned AbsKind,
9875                                   AbsoluteValueKind ValueKind) {
9876   switch (ValueKind) {
9877   case AVK_Integer:
9878     switch (AbsKind) {
9879     default:
9880       return 0;
9881     case Builtin::BI__builtin_fabsf:
9882     case Builtin::BI__builtin_fabs:
9883     case Builtin::BI__builtin_fabsl:
9884     case Builtin::BI__builtin_cabsf:
9885     case Builtin::BI__builtin_cabs:
9886     case Builtin::BI__builtin_cabsl:
9887       return Builtin::BI__builtin_abs;
9888     case Builtin::BIfabsf:
9889     case Builtin::BIfabs:
9890     case Builtin::BIfabsl:
9891     case Builtin::BIcabsf:
9892     case Builtin::BIcabs:
9893     case Builtin::BIcabsl:
9894       return Builtin::BIabs;
9895     }
9896   case AVK_Floating:
9897     switch (AbsKind) {
9898     default:
9899       return 0;
9900     case Builtin::BI__builtin_abs:
9901     case Builtin::BI__builtin_labs:
9902     case Builtin::BI__builtin_llabs:
9903     case Builtin::BI__builtin_cabsf:
9904     case Builtin::BI__builtin_cabs:
9905     case Builtin::BI__builtin_cabsl:
9906       return Builtin::BI__builtin_fabsf;
9907     case Builtin::BIabs:
9908     case Builtin::BIlabs:
9909     case Builtin::BIllabs:
9910     case Builtin::BIcabsf:
9911     case Builtin::BIcabs:
9912     case Builtin::BIcabsl:
9913       return Builtin::BIfabsf;
9914     }
9915   case AVK_Complex:
9916     switch (AbsKind) {
9917     default:
9918       return 0;
9919     case Builtin::BI__builtin_abs:
9920     case Builtin::BI__builtin_labs:
9921     case Builtin::BI__builtin_llabs:
9922     case Builtin::BI__builtin_fabsf:
9923     case Builtin::BI__builtin_fabs:
9924     case Builtin::BI__builtin_fabsl:
9925       return Builtin::BI__builtin_cabsf;
9926     case Builtin::BIabs:
9927     case Builtin::BIlabs:
9928     case Builtin::BIllabs:
9929     case Builtin::BIfabsf:
9930     case Builtin::BIfabs:
9931     case Builtin::BIfabsl:
9932       return Builtin::BIcabsf;
9933     }
9934   }
9935   llvm_unreachable("Unable to convert function");
9936 }
9937 
9938 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9939   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9940   if (!FnInfo)
9941     return 0;
9942 
9943   switch (FDecl->getBuiltinID()) {
9944   default:
9945     return 0;
9946   case Builtin::BI__builtin_abs:
9947   case Builtin::BI__builtin_fabs:
9948   case Builtin::BI__builtin_fabsf:
9949   case Builtin::BI__builtin_fabsl:
9950   case Builtin::BI__builtin_labs:
9951   case Builtin::BI__builtin_llabs:
9952   case Builtin::BI__builtin_cabs:
9953   case Builtin::BI__builtin_cabsf:
9954   case Builtin::BI__builtin_cabsl:
9955   case Builtin::BIabs:
9956   case Builtin::BIlabs:
9957   case Builtin::BIllabs:
9958   case Builtin::BIfabs:
9959   case Builtin::BIfabsf:
9960   case Builtin::BIfabsl:
9961   case Builtin::BIcabs:
9962   case Builtin::BIcabsf:
9963   case Builtin::BIcabsl:
9964     return FDecl->getBuiltinID();
9965   }
9966   llvm_unreachable("Unknown Builtin type");
9967 }
9968 
9969 // If the replacement is valid, emit a note with replacement function.
9970 // Additionally, suggest including the proper header if not already included.
9971 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9972                             unsigned AbsKind, QualType ArgType) {
9973   bool EmitHeaderHint = true;
9974   const char *HeaderName = nullptr;
9975   const char *FunctionName = nullptr;
9976   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9977     FunctionName = "std::abs";
9978     if (ArgType->isIntegralOrEnumerationType()) {
9979       HeaderName = "cstdlib";
9980     } else if (ArgType->isRealFloatingType()) {
9981       HeaderName = "cmath";
9982     } else {
9983       llvm_unreachable("Invalid Type");
9984     }
9985 
9986     // Lookup all std::abs
9987     if (NamespaceDecl *Std = S.getStdNamespace()) {
9988       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9989       R.suppressDiagnostics();
9990       S.LookupQualifiedName(R, Std);
9991 
9992       for (const auto *I : R) {
9993         const FunctionDecl *FDecl = nullptr;
9994         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9995           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9996         } else {
9997           FDecl = dyn_cast<FunctionDecl>(I);
9998         }
9999         if (!FDecl)
10000           continue;
10001 
10002         // Found std::abs(), check that they are the right ones.
10003         if (FDecl->getNumParams() != 1)
10004           continue;
10005 
10006         // Check that the parameter type can handle the argument.
10007         QualType ParamType = FDecl->getParamDecl(0)->getType();
10008         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
10009             S.Context.getTypeSize(ArgType) <=
10010                 S.Context.getTypeSize(ParamType)) {
10011           // Found a function, don't need the header hint.
10012           EmitHeaderHint = false;
10013           break;
10014         }
10015       }
10016     }
10017   } else {
10018     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
10019     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
10020 
10021     if (HeaderName) {
10022       DeclarationName DN(&S.Context.Idents.get(FunctionName));
10023       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
10024       R.suppressDiagnostics();
10025       S.LookupName(R, S.getCurScope());
10026 
10027       if (R.isSingleResult()) {
10028         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
10029         if (FD && FD->getBuiltinID() == AbsKind) {
10030           EmitHeaderHint = false;
10031         } else {
10032           return;
10033         }
10034       } else if (!R.empty()) {
10035         return;
10036       }
10037     }
10038   }
10039 
10040   S.Diag(Loc, diag::note_replace_abs_function)
10041       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10042 
10043   if (!HeaderName)
10044     return;
10045 
10046   if (!EmitHeaderHint)
10047     return;
10048 
10049   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10050                                                     << FunctionName;
10051 }
10052 
10053 template <std::size_t StrLen>
10054 static bool IsStdFunction(const FunctionDecl *FDecl,
10055                           const char (&Str)[StrLen]) {
10056   if (!FDecl)
10057     return false;
10058   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10059     return false;
10060   if (!FDecl->isInStdNamespace())
10061     return false;
10062 
10063   return true;
10064 }
10065 
10066 // Warn when using the wrong abs() function.
10067 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10068                                       const FunctionDecl *FDecl) {
10069   if (Call->getNumArgs() != 1)
10070     return;
10071 
10072   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10073   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10074   if (AbsKind == 0 && !IsStdAbs)
10075     return;
10076 
10077   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10078   QualType ParamType = Call->getArg(0)->getType();
10079 
10080   // Unsigned types cannot be negative.  Suggest removing the absolute value
10081   // function call.
10082   if (ArgType->isUnsignedIntegerType()) {
10083     const char *FunctionName =
10084         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10085     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10086     Diag(Call->getExprLoc(), diag::note_remove_abs)
10087         << FunctionName
10088         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10089     return;
10090   }
10091 
10092   // Taking the absolute value of a pointer is very suspicious, they probably
10093   // wanted to index into an array, dereference a pointer, call a function, etc.
10094   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10095     unsigned DiagType = 0;
10096     if (ArgType->isFunctionType())
10097       DiagType = 1;
10098     else if (ArgType->isArrayType())
10099       DiagType = 2;
10100 
10101     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10102     return;
10103   }
10104 
10105   // std::abs has overloads which prevent most of the absolute value problems
10106   // from occurring.
10107   if (IsStdAbs)
10108     return;
10109 
10110   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10111   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10112 
10113   // The argument and parameter are the same kind.  Check if they are the right
10114   // size.
10115   if (ArgValueKind == ParamValueKind) {
10116     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10117       return;
10118 
10119     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10120     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10121         << FDecl << ArgType << ParamType;
10122 
10123     if (NewAbsKind == 0)
10124       return;
10125 
10126     emitReplacement(*this, Call->getExprLoc(),
10127                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10128     return;
10129   }
10130 
10131   // ArgValueKind != ParamValueKind
10132   // The wrong type of absolute value function was used.  Attempt to find the
10133   // proper one.
10134   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10135   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10136   if (NewAbsKind == 0)
10137     return;
10138 
10139   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10140       << FDecl << ParamValueKind << ArgValueKind;
10141 
10142   emitReplacement(*this, Call->getExprLoc(),
10143                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10144 }
10145 
10146 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10147 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10148                                 const FunctionDecl *FDecl) {
10149   if (!Call || !FDecl) return;
10150 
10151   // Ignore template specializations and macros.
10152   if (inTemplateInstantiation()) return;
10153   if (Call->getExprLoc().isMacroID()) return;
10154 
10155   // Only care about the one template argument, two function parameter std::max
10156   if (Call->getNumArgs() != 2) return;
10157   if (!IsStdFunction(FDecl, "max")) return;
10158   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10159   if (!ArgList) return;
10160   if (ArgList->size() != 1) return;
10161 
10162   // Check that template type argument is unsigned integer.
10163   const auto& TA = ArgList->get(0);
10164   if (TA.getKind() != TemplateArgument::Type) return;
10165   QualType ArgType = TA.getAsType();
10166   if (!ArgType->isUnsignedIntegerType()) return;
10167 
10168   // See if either argument is a literal zero.
10169   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10170     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10171     if (!MTE) return false;
10172     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10173     if (!Num) return false;
10174     if (Num->getValue() != 0) return false;
10175     return true;
10176   };
10177 
10178   const Expr *FirstArg = Call->getArg(0);
10179   const Expr *SecondArg = Call->getArg(1);
10180   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10181   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10182 
10183   // Only warn when exactly one argument is zero.
10184   if (IsFirstArgZero == IsSecondArgZero) return;
10185 
10186   SourceRange FirstRange = FirstArg->getSourceRange();
10187   SourceRange SecondRange = SecondArg->getSourceRange();
10188 
10189   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10190 
10191   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10192       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10193 
10194   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10195   SourceRange RemovalRange;
10196   if (IsFirstArgZero) {
10197     RemovalRange = SourceRange(FirstRange.getBegin(),
10198                                SecondRange.getBegin().getLocWithOffset(-1));
10199   } else {
10200     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10201                                SecondRange.getEnd());
10202   }
10203 
10204   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10205         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10206         << FixItHint::CreateRemoval(RemovalRange);
10207 }
10208 
10209 //===--- CHECK: Standard memory functions ---------------------------------===//
10210 
10211 /// Takes the expression passed to the size_t parameter of functions
10212 /// such as memcmp, strncat, etc and warns if it's a comparison.
10213 ///
10214 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10215 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10216                                            IdentifierInfo *FnName,
10217                                            SourceLocation FnLoc,
10218                                            SourceLocation RParenLoc) {
10219   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10220   if (!Size)
10221     return false;
10222 
10223   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10224   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10225     return false;
10226 
10227   SourceRange SizeRange = Size->getSourceRange();
10228   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10229       << SizeRange << FnName;
10230   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10231       << FnName
10232       << FixItHint::CreateInsertion(
10233              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10234       << FixItHint::CreateRemoval(RParenLoc);
10235   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10236       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10237       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10238                                     ")");
10239 
10240   return true;
10241 }
10242 
10243 /// Determine whether the given type is or contains a dynamic class type
10244 /// (e.g., whether it has a vtable).
10245 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10246                                                      bool &IsContained) {
10247   // Look through array types while ignoring qualifiers.
10248   const Type *Ty = T->getBaseElementTypeUnsafe();
10249   IsContained = false;
10250 
10251   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10252   RD = RD ? RD->getDefinition() : nullptr;
10253   if (!RD || RD->isInvalidDecl())
10254     return nullptr;
10255 
10256   if (RD->isDynamicClass())
10257     return RD;
10258 
10259   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10260   // It's impossible for a class to transitively contain itself by value, so
10261   // infinite recursion is impossible.
10262   for (auto *FD : RD->fields()) {
10263     bool SubContained;
10264     if (const CXXRecordDecl *ContainedRD =
10265             getContainedDynamicClass(FD->getType(), SubContained)) {
10266       IsContained = true;
10267       return ContainedRD;
10268     }
10269   }
10270 
10271   return nullptr;
10272 }
10273 
10274 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10275   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10276     if (Unary->getKind() == UETT_SizeOf)
10277       return Unary;
10278   return nullptr;
10279 }
10280 
10281 /// If E is a sizeof expression, returns its argument expression,
10282 /// otherwise returns NULL.
10283 static const Expr *getSizeOfExprArg(const Expr *E) {
10284   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10285     if (!SizeOf->isArgumentType())
10286       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10287   return nullptr;
10288 }
10289 
10290 /// If E is a sizeof expression, returns its argument type.
10291 static QualType getSizeOfArgType(const Expr *E) {
10292   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10293     return SizeOf->getTypeOfArgument();
10294   return QualType();
10295 }
10296 
10297 namespace {
10298 
10299 struct SearchNonTrivialToInitializeField
10300     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10301   using Super =
10302       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10303 
10304   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10305 
10306   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10307                      SourceLocation SL) {
10308     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10309       asDerived().visitArray(PDIK, AT, SL);
10310       return;
10311     }
10312 
10313     Super::visitWithKind(PDIK, FT, SL);
10314   }
10315 
10316   void visitARCStrong(QualType FT, SourceLocation SL) {
10317     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10318   }
10319   void visitARCWeak(QualType FT, SourceLocation SL) {
10320     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10321   }
10322   void visitStruct(QualType FT, SourceLocation SL) {
10323     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10324       visit(FD->getType(), FD->getLocation());
10325   }
10326   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10327                   const ArrayType *AT, SourceLocation SL) {
10328     visit(getContext().getBaseElementType(AT), SL);
10329   }
10330   void visitTrivial(QualType FT, SourceLocation SL) {}
10331 
10332   static void diag(QualType RT, const Expr *E, Sema &S) {
10333     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10334   }
10335 
10336   ASTContext &getContext() { return S.getASTContext(); }
10337 
10338   const Expr *E;
10339   Sema &S;
10340 };
10341 
10342 struct SearchNonTrivialToCopyField
10343     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10344   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10345 
10346   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10347 
10348   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10349                      SourceLocation SL) {
10350     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10351       asDerived().visitArray(PCK, AT, SL);
10352       return;
10353     }
10354 
10355     Super::visitWithKind(PCK, FT, SL);
10356   }
10357 
10358   void visitARCStrong(QualType FT, SourceLocation SL) {
10359     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10360   }
10361   void visitARCWeak(QualType FT, SourceLocation SL) {
10362     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10363   }
10364   void visitStruct(QualType FT, SourceLocation SL) {
10365     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10366       visit(FD->getType(), FD->getLocation());
10367   }
10368   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10369                   SourceLocation SL) {
10370     visit(getContext().getBaseElementType(AT), SL);
10371   }
10372   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10373                 SourceLocation SL) {}
10374   void visitTrivial(QualType FT, SourceLocation SL) {}
10375   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10376 
10377   static void diag(QualType RT, const Expr *E, Sema &S) {
10378     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10379   }
10380 
10381   ASTContext &getContext() { return S.getASTContext(); }
10382 
10383   const Expr *E;
10384   Sema &S;
10385 };
10386 
10387 }
10388 
10389 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10390 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10391   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10392 
10393   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10394     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10395       return false;
10396 
10397     return doesExprLikelyComputeSize(BO->getLHS()) ||
10398            doesExprLikelyComputeSize(BO->getRHS());
10399   }
10400 
10401   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10402 }
10403 
10404 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10405 ///
10406 /// \code
10407 ///   #define MACRO 0
10408 ///   foo(MACRO);
10409 ///   foo(0);
10410 /// \endcode
10411 ///
10412 /// This should return true for the first call to foo, but not for the second
10413 /// (regardless of whether foo is a macro or function).
10414 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10415                                         SourceLocation CallLoc,
10416                                         SourceLocation ArgLoc) {
10417   if (!CallLoc.isMacroID())
10418     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10419 
10420   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10421          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10422 }
10423 
10424 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10425 /// last two arguments transposed.
10426 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10427   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10428     return;
10429 
10430   const Expr *SizeArg =
10431     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10432 
10433   auto isLiteralZero = [](const Expr *E) {
10434     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10435   };
10436 
10437   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10438   SourceLocation CallLoc = Call->getRParenLoc();
10439   SourceManager &SM = S.getSourceManager();
10440   if (isLiteralZero(SizeArg) &&
10441       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10442 
10443     SourceLocation DiagLoc = SizeArg->getExprLoc();
10444 
10445     // Some platforms #define bzero to __builtin_memset. See if this is the
10446     // case, and if so, emit a better diagnostic.
10447     if (BId == Builtin::BIbzero ||
10448         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10449                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10450       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10451       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10452     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10453       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10454       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10455     }
10456     return;
10457   }
10458 
10459   // If the second argument to a memset is a sizeof expression and the third
10460   // isn't, this is also likely an error. This should catch
10461   // 'memset(buf, sizeof(buf), 0xff)'.
10462   if (BId == Builtin::BImemset &&
10463       doesExprLikelyComputeSize(Call->getArg(1)) &&
10464       !doesExprLikelyComputeSize(Call->getArg(2))) {
10465     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10466     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10467     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10468     return;
10469   }
10470 }
10471 
10472 /// Check for dangerous or invalid arguments to memset().
10473 ///
10474 /// This issues warnings on known problematic, dangerous or unspecified
10475 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10476 /// function calls.
10477 ///
10478 /// \param Call The call expression to diagnose.
10479 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10480                                    unsigned BId,
10481                                    IdentifierInfo *FnName) {
10482   assert(BId != 0);
10483 
10484   // It is possible to have a non-standard definition of memset.  Validate
10485   // we have enough arguments, and if not, abort further checking.
10486   unsigned ExpectedNumArgs =
10487       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10488   if (Call->getNumArgs() < ExpectedNumArgs)
10489     return;
10490 
10491   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10492                       BId == Builtin::BIstrndup ? 1 : 2);
10493   unsigned LenArg =
10494       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10495   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10496 
10497   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10498                                      Call->getBeginLoc(), Call->getRParenLoc()))
10499     return;
10500 
10501   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10502   CheckMemaccessSize(*this, BId, Call);
10503 
10504   // We have special checking when the length is a sizeof expression.
10505   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10506   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10507   llvm::FoldingSetNodeID SizeOfArgID;
10508 
10509   // Although widely used, 'bzero' is not a standard function. Be more strict
10510   // with the argument types before allowing diagnostics and only allow the
10511   // form bzero(ptr, sizeof(...)).
10512   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10513   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10514     return;
10515 
10516   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10517     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10518     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10519 
10520     QualType DestTy = Dest->getType();
10521     QualType PointeeTy;
10522     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10523       PointeeTy = DestPtrTy->getPointeeType();
10524 
10525       // Never warn about void type pointers. This can be used to suppress
10526       // false positives.
10527       if (PointeeTy->isVoidType())
10528         continue;
10529 
10530       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10531       // actually comparing the expressions for equality. Because computing the
10532       // expression IDs can be expensive, we only do this if the diagnostic is
10533       // enabled.
10534       if (SizeOfArg &&
10535           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10536                            SizeOfArg->getExprLoc())) {
10537         // We only compute IDs for expressions if the warning is enabled, and
10538         // cache the sizeof arg's ID.
10539         if (SizeOfArgID == llvm::FoldingSetNodeID())
10540           SizeOfArg->Profile(SizeOfArgID, Context, true);
10541         llvm::FoldingSetNodeID DestID;
10542         Dest->Profile(DestID, Context, true);
10543         if (DestID == SizeOfArgID) {
10544           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10545           //       over sizeof(src) as well.
10546           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10547           StringRef ReadableName = FnName->getName();
10548 
10549           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10550             if (UnaryOp->getOpcode() == UO_AddrOf)
10551               ActionIdx = 1; // If its an address-of operator, just remove it.
10552           if (!PointeeTy->isIncompleteType() &&
10553               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10554             ActionIdx = 2; // If the pointee's size is sizeof(char),
10555                            // suggest an explicit length.
10556 
10557           // If the function is defined as a builtin macro, do not show macro
10558           // expansion.
10559           SourceLocation SL = SizeOfArg->getExprLoc();
10560           SourceRange DSR = Dest->getSourceRange();
10561           SourceRange SSR = SizeOfArg->getSourceRange();
10562           SourceManager &SM = getSourceManager();
10563 
10564           if (SM.isMacroArgExpansion(SL)) {
10565             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10566             SL = SM.getSpellingLoc(SL);
10567             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10568                              SM.getSpellingLoc(DSR.getEnd()));
10569             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10570                              SM.getSpellingLoc(SSR.getEnd()));
10571           }
10572 
10573           DiagRuntimeBehavior(SL, SizeOfArg,
10574                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10575                                 << ReadableName
10576                                 << PointeeTy
10577                                 << DestTy
10578                                 << DSR
10579                                 << SSR);
10580           DiagRuntimeBehavior(SL, SizeOfArg,
10581                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10582                                 << ActionIdx
10583                                 << SSR);
10584 
10585           break;
10586         }
10587       }
10588 
10589       // Also check for cases where the sizeof argument is the exact same
10590       // type as the memory argument, and where it points to a user-defined
10591       // record type.
10592       if (SizeOfArgTy != QualType()) {
10593         if (PointeeTy->isRecordType() &&
10594             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10595           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10596                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10597                                 << FnName << SizeOfArgTy << ArgIdx
10598                                 << PointeeTy << Dest->getSourceRange()
10599                                 << LenExpr->getSourceRange());
10600           break;
10601         }
10602       }
10603     } else if (DestTy->isArrayType()) {
10604       PointeeTy = DestTy;
10605     }
10606 
10607     if (PointeeTy == QualType())
10608       continue;
10609 
10610     // Always complain about dynamic classes.
10611     bool IsContained;
10612     if (const CXXRecordDecl *ContainedRD =
10613             getContainedDynamicClass(PointeeTy, IsContained)) {
10614 
10615       unsigned OperationType = 0;
10616       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10617       // "overwritten" if we're warning about the destination for any call
10618       // but memcmp; otherwise a verb appropriate to the call.
10619       if (ArgIdx != 0 || IsCmp) {
10620         if (BId == Builtin::BImemcpy)
10621           OperationType = 1;
10622         else if(BId == Builtin::BImemmove)
10623           OperationType = 2;
10624         else if (IsCmp)
10625           OperationType = 3;
10626       }
10627 
10628       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10629                           PDiag(diag::warn_dyn_class_memaccess)
10630                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10631                               << IsContained << ContainedRD << OperationType
10632                               << Call->getCallee()->getSourceRange());
10633     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10634              BId != Builtin::BImemset)
10635       DiagRuntimeBehavior(
10636         Dest->getExprLoc(), Dest,
10637         PDiag(diag::warn_arc_object_memaccess)
10638           << ArgIdx << FnName << PointeeTy
10639           << Call->getCallee()->getSourceRange());
10640     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10641       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10642           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10643         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10644                             PDiag(diag::warn_cstruct_memaccess)
10645                                 << ArgIdx << FnName << PointeeTy << 0);
10646         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10647       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10648                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10649         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10650                             PDiag(diag::warn_cstruct_memaccess)
10651                                 << ArgIdx << FnName << PointeeTy << 1);
10652         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10653       } else {
10654         continue;
10655       }
10656     } else
10657       continue;
10658 
10659     DiagRuntimeBehavior(
10660       Dest->getExprLoc(), Dest,
10661       PDiag(diag::note_bad_memaccess_silence)
10662         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10663     break;
10664   }
10665 }
10666 
10667 // A little helper routine: ignore addition and subtraction of integer literals.
10668 // This intentionally does not ignore all integer constant expressions because
10669 // we don't want to remove sizeof().
10670 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10671   Ex = Ex->IgnoreParenCasts();
10672 
10673   while (true) {
10674     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10675     if (!BO || !BO->isAdditiveOp())
10676       break;
10677 
10678     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10679     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10680 
10681     if (isa<IntegerLiteral>(RHS))
10682       Ex = LHS;
10683     else if (isa<IntegerLiteral>(LHS))
10684       Ex = RHS;
10685     else
10686       break;
10687   }
10688 
10689   return Ex;
10690 }
10691 
10692 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10693                                                       ASTContext &Context) {
10694   // Only handle constant-sized or VLAs, but not flexible members.
10695   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10696     // Only issue the FIXIT for arrays of size > 1.
10697     if (CAT->getSize().getSExtValue() <= 1)
10698       return false;
10699   } else if (!Ty->isVariableArrayType()) {
10700     return false;
10701   }
10702   return true;
10703 }
10704 
10705 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10706 // be the size of the source, instead of the destination.
10707 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10708                                     IdentifierInfo *FnName) {
10709 
10710   // Don't crash if the user has the wrong number of arguments
10711   unsigned NumArgs = Call->getNumArgs();
10712   if ((NumArgs != 3) && (NumArgs != 4))
10713     return;
10714 
10715   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10716   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10717   const Expr *CompareWithSrc = nullptr;
10718 
10719   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10720                                      Call->getBeginLoc(), Call->getRParenLoc()))
10721     return;
10722 
10723   // Look for 'strlcpy(dst, x, sizeof(x))'
10724   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10725     CompareWithSrc = Ex;
10726   else {
10727     // Look for 'strlcpy(dst, x, strlen(x))'
10728     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10729       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10730           SizeCall->getNumArgs() == 1)
10731         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10732     }
10733   }
10734 
10735   if (!CompareWithSrc)
10736     return;
10737 
10738   // Determine if the argument to sizeof/strlen is equal to the source
10739   // argument.  In principle there's all kinds of things you could do
10740   // here, for instance creating an == expression and evaluating it with
10741   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10742   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10743   if (!SrcArgDRE)
10744     return;
10745 
10746   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10747   if (!CompareWithSrcDRE ||
10748       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10749     return;
10750 
10751   const Expr *OriginalSizeArg = Call->getArg(2);
10752   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10753       << OriginalSizeArg->getSourceRange() << FnName;
10754 
10755   // Output a FIXIT hint if the destination is an array (rather than a
10756   // pointer to an array).  This could be enhanced to handle some
10757   // pointers if we know the actual size, like if DstArg is 'array+2'
10758   // we could say 'sizeof(array)-2'.
10759   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10760   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10761     return;
10762 
10763   SmallString<128> sizeString;
10764   llvm::raw_svector_ostream OS(sizeString);
10765   OS << "sizeof(";
10766   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10767   OS << ")";
10768 
10769   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10770       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10771                                       OS.str());
10772 }
10773 
10774 /// Check if two expressions refer to the same declaration.
10775 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10776   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10777     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10778       return D1->getDecl() == D2->getDecl();
10779   return false;
10780 }
10781 
10782 static const Expr *getStrlenExprArg(const Expr *E) {
10783   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10784     const FunctionDecl *FD = CE->getDirectCallee();
10785     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10786       return nullptr;
10787     return CE->getArg(0)->IgnoreParenCasts();
10788   }
10789   return nullptr;
10790 }
10791 
10792 // Warn on anti-patterns as the 'size' argument to strncat.
10793 // The correct size argument should look like following:
10794 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10795 void Sema::CheckStrncatArguments(const CallExpr *CE,
10796                                  IdentifierInfo *FnName) {
10797   // Don't crash if the user has the wrong number of arguments.
10798   if (CE->getNumArgs() < 3)
10799     return;
10800   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10801   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10802   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10803 
10804   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10805                                      CE->getRParenLoc()))
10806     return;
10807 
10808   // Identify common expressions, which are wrongly used as the size argument
10809   // to strncat and may lead to buffer overflows.
10810   unsigned PatternType = 0;
10811   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10812     // - sizeof(dst)
10813     if (referToTheSameDecl(SizeOfArg, DstArg))
10814       PatternType = 1;
10815     // - sizeof(src)
10816     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10817       PatternType = 2;
10818   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10819     if (BE->getOpcode() == BO_Sub) {
10820       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10821       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10822       // - sizeof(dst) - strlen(dst)
10823       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10824           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10825         PatternType = 1;
10826       // - sizeof(src) - (anything)
10827       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10828         PatternType = 2;
10829     }
10830   }
10831 
10832   if (PatternType == 0)
10833     return;
10834 
10835   // Generate the diagnostic.
10836   SourceLocation SL = LenArg->getBeginLoc();
10837   SourceRange SR = LenArg->getSourceRange();
10838   SourceManager &SM = getSourceManager();
10839 
10840   // If the function is defined as a builtin macro, do not show macro expansion.
10841   if (SM.isMacroArgExpansion(SL)) {
10842     SL = SM.getSpellingLoc(SL);
10843     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10844                      SM.getSpellingLoc(SR.getEnd()));
10845   }
10846 
10847   // Check if the destination is an array (rather than a pointer to an array).
10848   QualType DstTy = DstArg->getType();
10849   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10850                                                                     Context);
10851   if (!isKnownSizeArray) {
10852     if (PatternType == 1)
10853       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10854     else
10855       Diag(SL, diag::warn_strncat_src_size) << SR;
10856     return;
10857   }
10858 
10859   if (PatternType == 1)
10860     Diag(SL, diag::warn_strncat_large_size) << SR;
10861   else
10862     Diag(SL, diag::warn_strncat_src_size) << SR;
10863 
10864   SmallString<128> sizeString;
10865   llvm::raw_svector_ostream OS(sizeString);
10866   OS << "sizeof(";
10867   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10868   OS << ") - ";
10869   OS << "strlen(";
10870   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10871   OS << ") - 1";
10872 
10873   Diag(SL, diag::note_strncat_wrong_size)
10874     << FixItHint::CreateReplacement(SR, OS.str());
10875 }
10876 
10877 namespace {
10878 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10879                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10880   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10881     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10882         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10883     return;
10884   }
10885 }
10886 
10887 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10888                                  const UnaryOperator *UnaryExpr) {
10889   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10890     const Decl *D = Lvalue->getDecl();
10891     if (isa<DeclaratorDecl>(D))
10892       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10893         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10894   }
10895 
10896   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10897     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10898                                       Lvalue->getMemberDecl());
10899 }
10900 
10901 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10902                             const UnaryOperator *UnaryExpr) {
10903   const auto *Lambda = dyn_cast<LambdaExpr>(
10904       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10905   if (!Lambda)
10906     return;
10907 
10908   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10909       << CalleeName << 2 /*object: lambda expression*/;
10910 }
10911 
10912 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10913                                   const DeclRefExpr *Lvalue) {
10914   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10915   if (Var == nullptr)
10916     return;
10917 
10918   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10919       << CalleeName << 0 /*object: */ << Var;
10920 }
10921 
10922 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10923                             const CastExpr *Cast) {
10924   SmallString<128> SizeString;
10925   llvm::raw_svector_ostream OS(SizeString);
10926 
10927   clang::CastKind Kind = Cast->getCastKind();
10928   if (Kind == clang::CK_BitCast &&
10929       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10930     return;
10931   if (Kind == clang::CK_IntegralToPointer &&
10932       !isa<IntegerLiteral>(
10933           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10934     return;
10935 
10936   switch (Cast->getCastKind()) {
10937   case clang::CK_BitCast:
10938   case clang::CK_IntegralToPointer:
10939   case clang::CK_FunctionToPointerDecay:
10940     OS << '\'';
10941     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10942     OS << '\'';
10943     break;
10944   default:
10945     return;
10946   }
10947 
10948   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10949       << CalleeName << 0 /*object: */ << OS.str();
10950 }
10951 } // namespace
10952 
10953 /// Alerts the user that they are attempting to free a non-malloc'd object.
10954 void Sema::CheckFreeArguments(const CallExpr *E) {
10955   const std::string CalleeName =
10956       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10957 
10958   { // Prefer something that doesn't involve a cast to make things simpler.
10959     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10960     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10961       switch (UnaryExpr->getOpcode()) {
10962       case UnaryOperator::Opcode::UO_AddrOf:
10963         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10964       case UnaryOperator::Opcode::UO_Plus:
10965         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10966       default:
10967         break;
10968       }
10969 
10970     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10971       if (Lvalue->getType()->isArrayType())
10972         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10973 
10974     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10975       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10976           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10977       return;
10978     }
10979 
10980     if (isa<BlockExpr>(Arg)) {
10981       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10982           << CalleeName << 1 /*object: block*/;
10983       return;
10984     }
10985   }
10986   // Maybe the cast was important, check after the other cases.
10987   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10988     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10989 }
10990 
10991 void
10992 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10993                          SourceLocation ReturnLoc,
10994                          bool isObjCMethod,
10995                          const AttrVec *Attrs,
10996                          const FunctionDecl *FD) {
10997   // Check if the return value is null but should not be.
10998   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10999        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
11000       CheckNonNullExpr(*this, RetValExp))
11001     Diag(ReturnLoc, diag::warn_null_ret)
11002       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
11003 
11004   // C++11 [basic.stc.dynamic.allocation]p4:
11005   //   If an allocation function declared with a non-throwing
11006   //   exception-specification fails to allocate storage, it shall return
11007   //   a null pointer. Any other allocation function that fails to allocate
11008   //   storage shall indicate failure only by throwing an exception [...]
11009   if (FD) {
11010     OverloadedOperatorKind Op = FD->getOverloadedOperator();
11011     if (Op == OO_New || Op == OO_Array_New) {
11012       const FunctionProtoType *Proto
11013         = FD->getType()->castAs<FunctionProtoType>();
11014       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
11015           CheckNonNullExpr(*this, RetValExp))
11016         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
11017           << FD << getLangOpts().CPlusPlus11;
11018     }
11019   }
11020 
11021   // PPC MMA non-pointer types are not allowed as return type. Checking the type
11022   // here prevent the user from using a PPC MMA type as trailing return type.
11023   if (Context.getTargetInfo().getTriple().isPPC64())
11024     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
11025 }
11026 
11027 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
11028 
11029 /// Check for comparisons of floating point operands using != and ==.
11030 /// Issue a warning if these are no self-comparisons, as they are not likely
11031 /// to do what the programmer intended.
11032 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11033   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11034   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11035 
11036   // Special case: check for x == x (which is OK).
11037   // Do not emit warnings for such cases.
11038   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11039     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11040       if (DRL->getDecl() == DRR->getDecl())
11041         return;
11042 
11043   // Special case: check for comparisons against literals that can be exactly
11044   //  represented by APFloat.  In such cases, do not emit a warning.  This
11045   //  is a heuristic: often comparison against such literals are used to
11046   //  detect if a value in a variable has not changed.  This clearly can
11047   //  lead to false negatives.
11048   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11049     if (FLL->isExact())
11050       return;
11051   } else
11052     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11053       if (FLR->isExact())
11054         return;
11055 
11056   // Check for comparisons with builtin types.
11057   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11058     if (CL->getBuiltinCallee())
11059       return;
11060 
11061   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11062     if (CR->getBuiltinCallee())
11063       return;
11064 
11065   // Emit the diagnostic.
11066   Diag(Loc, diag::warn_floatingpoint_eq)
11067     << LHS->getSourceRange() << RHS->getSourceRange();
11068 }
11069 
11070 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11071 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11072 
11073 namespace {
11074 
11075 /// Structure recording the 'active' range of an integer-valued
11076 /// expression.
11077 struct IntRange {
11078   /// The number of bits active in the int. Note that this includes exactly one
11079   /// sign bit if !NonNegative.
11080   unsigned Width;
11081 
11082   /// True if the int is known not to have negative values. If so, all leading
11083   /// bits before Width are known zero, otherwise they are known to be the
11084   /// same as the MSB within Width.
11085   bool NonNegative;
11086 
11087   IntRange(unsigned Width, bool NonNegative)
11088       : Width(Width), NonNegative(NonNegative) {}
11089 
11090   /// Number of bits excluding the sign bit.
11091   unsigned valueBits() const {
11092     return NonNegative ? Width : Width - 1;
11093   }
11094 
11095   /// Returns the range of the bool type.
11096   static IntRange forBoolType() {
11097     return IntRange(1, true);
11098   }
11099 
11100   /// Returns the range of an opaque value of the given integral type.
11101   static IntRange forValueOfType(ASTContext &C, QualType T) {
11102     return forValueOfCanonicalType(C,
11103                           T->getCanonicalTypeInternal().getTypePtr());
11104   }
11105 
11106   /// Returns the range of an opaque value of a canonical integral type.
11107   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11108     assert(T->isCanonicalUnqualified());
11109 
11110     if (const VectorType *VT = dyn_cast<VectorType>(T))
11111       T = VT->getElementType().getTypePtr();
11112     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11113       T = CT->getElementType().getTypePtr();
11114     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11115       T = AT->getValueType().getTypePtr();
11116 
11117     if (!C.getLangOpts().CPlusPlus) {
11118       // For enum types in C code, use the underlying datatype.
11119       if (const EnumType *ET = dyn_cast<EnumType>(T))
11120         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11121     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11122       // For enum types in C++, use the known bit width of the enumerators.
11123       EnumDecl *Enum = ET->getDecl();
11124       // In C++11, enums can have a fixed underlying type. Use this type to
11125       // compute the range.
11126       if (Enum->isFixed()) {
11127         return IntRange(C.getIntWidth(QualType(T, 0)),
11128                         !ET->isSignedIntegerOrEnumerationType());
11129       }
11130 
11131       unsigned NumPositive = Enum->getNumPositiveBits();
11132       unsigned NumNegative = Enum->getNumNegativeBits();
11133 
11134       if (NumNegative == 0)
11135         return IntRange(NumPositive, true/*NonNegative*/);
11136       else
11137         return IntRange(std::max(NumPositive + 1, NumNegative),
11138                         false/*NonNegative*/);
11139     }
11140 
11141     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11142       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11143 
11144     const BuiltinType *BT = cast<BuiltinType>(T);
11145     assert(BT->isInteger());
11146 
11147     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11148   }
11149 
11150   /// Returns the "target" range of a canonical integral type, i.e.
11151   /// the range of values expressible in the type.
11152   ///
11153   /// This matches forValueOfCanonicalType except that enums have the
11154   /// full range of their type, not the range of their enumerators.
11155   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11156     assert(T->isCanonicalUnqualified());
11157 
11158     if (const VectorType *VT = dyn_cast<VectorType>(T))
11159       T = VT->getElementType().getTypePtr();
11160     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11161       T = CT->getElementType().getTypePtr();
11162     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11163       T = AT->getValueType().getTypePtr();
11164     if (const EnumType *ET = dyn_cast<EnumType>(T))
11165       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11166 
11167     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11168       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11169 
11170     const BuiltinType *BT = cast<BuiltinType>(T);
11171     assert(BT->isInteger());
11172 
11173     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11174   }
11175 
11176   /// Returns the supremum of two ranges: i.e. their conservative merge.
11177   static IntRange join(IntRange L, IntRange R) {
11178     bool Unsigned = L.NonNegative && R.NonNegative;
11179     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11180                     L.NonNegative && R.NonNegative);
11181   }
11182 
11183   /// Return the range of a bitwise-AND of the two ranges.
11184   static IntRange bit_and(IntRange L, IntRange R) {
11185     unsigned Bits = std::max(L.Width, R.Width);
11186     bool NonNegative = false;
11187     if (L.NonNegative) {
11188       Bits = std::min(Bits, L.Width);
11189       NonNegative = true;
11190     }
11191     if (R.NonNegative) {
11192       Bits = std::min(Bits, R.Width);
11193       NonNegative = true;
11194     }
11195     return IntRange(Bits, NonNegative);
11196   }
11197 
11198   /// Return the range of a sum of the two ranges.
11199   static IntRange sum(IntRange L, IntRange R) {
11200     bool Unsigned = L.NonNegative && R.NonNegative;
11201     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11202                     Unsigned);
11203   }
11204 
11205   /// Return the range of a difference of the two ranges.
11206   static IntRange difference(IntRange L, IntRange R) {
11207     // We need a 1-bit-wider range if:
11208     //   1) LHS can be negative: least value can be reduced.
11209     //   2) RHS can be negative: greatest value can be increased.
11210     bool CanWiden = !L.NonNegative || !R.NonNegative;
11211     bool Unsigned = L.NonNegative && R.Width == 0;
11212     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11213                         !Unsigned,
11214                     Unsigned);
11215   }
11216 
11217   /// Return the range of a product of the two ranges.
11218   static IntRange product(IntRange L, IntRange R) {
11219     // If both LHS and RHS can be negative, we can form
11220     //   -2^L * -2^R = 2^(L + R)
11221     // which requires L + R + 1 value bits to represent.
11222     bool CanWiden = !L.NonNegative && !R.NonNegative;
11223     bool Unsigned = L.NonNegative && R.NonNegative;
11224     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11225                     Unsigned);
11226   }
11227 
11228   /// Return the range of a remainder operation between the two ranges.
11229   static IntRange rem(IntRange L, IntRange R) {
11230     // The result of a remainder can't be larger than the result of
11231     // either side. The sign of the result is the sign of the LHS.
11232     bool Unsigned = L.NonNegative;
11233     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11234                     Unsigned);
11235   }
11236 };
11237 
11238 } // namespace
11239 
11240 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11241                               unsigned MaxWidth) {
11242   if (value.isSigned() && value.isNegative())
11243     return IntRange(value.getMinSignedBits(), false);
11244 
11245   if (value.getBitWidth() > MaxWidth)
11246     value = value.trunc(MaxWidth);
11247 
11248   // isNonNegative() just checks the sign bit without considering
11249   // signedness.
11250   return IntRange(value.getActiveBits(), true);
11251 }
11252 
11253 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11254                               unsigned MaxWidth) {
11255   if (result.isInt())
11256     return GetValueRange(C, result.getInt(), MaxWidth);
11257 
11258   if (result.isVector()) {
11259     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11260     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11261       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11262       R = IntRange::join(R, El);
11263     }
11264     return R;
11265   }
11266 
11267   if (result.isComplexInt()) {
11268     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11269     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11270     return IntRange::join(R, I);
11271   }
11272 
11273   // This can happen with lossless casts to intptr_t of "based" lvalues.
11274   // Assume it might use arbitrary bits.
11275   // FIXME: The only reason we need to pass the type in here is to get
11276   // the sign right on this one case.  It would be nice if APValue
11277   // preserved this.
11278   assert(result.isLValue() || result.isAddrLabelDiff());
11279   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11280 }
11281 
11282 static QualType GetExprType(const Expr *E) {
11283   QualType Ty = E->getType();
11284   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11285     Ty = AtomicRHS->getValueType();
11286   return Ty;
11287 }
11288 
11289 /// Pseudo-evaluate the given integer expression, estimating the
11290 /// range of values it might take.
11291 ///
11292 /// \param MaxWidth The width to which the value will be truncated.
11293 /// \param Approximate If \c true, return a likely range for the result: in
11294 ///        particular, assume that arithmetic on narrower types doesn't leave
11295 ///        those types. If \c false, return a range including all possible
11296 ///        result values.
11297 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11298                              bool InConstantContext, bool Approximate) {
11299   E = E->IgnoreParens();
11300 
11301   // Try a full evaluation first.
11302   Expr::EvalResult result;
11303   if (E->EvaluateAsRValue(result, C, InConstantContext))
11304     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11305 
11306   // I think we only want to look through implicit casts here; if the
11307   // user has an explicit widening cast, we should treat the value as
11308   // being of the new, wider type.
11309   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11310     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11311       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11312                           Approximate);
11313 
11314     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11315 
11316     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11317                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11318 
11319     // Assume that non-integer casts can span the full range of the type.
11320     if (!isIntegerCast)
11321       return OutputTypeRange;
11322 
11323     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11324                                      std::min(MaxWidth, OutputTypeRange.Width),
11325                                      InConstantContext, Approximate);
11326 
11327     // Bail out if the subexpr's range is as wide as the cast type.
11328     if (SubRange.Width >= OutputTypeRange.Width)
11329       return OutputTypeRange;
11330 
11331     // Otherwise, we take the smaller width, and we're non-negative if
11332     // either the output type or the subexpr is.
11333     return IntRange(SubRange.Width,
11334                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11335   }
11336 
11337   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11338     // If we can fold the condition, just take that operand.
11339     bool CondResult;
11340     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11341       return GetExprRange(C,
11342                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11343                           MaxWidth, InConstantContext, Approximate);
11344 
11345     // Otherwise, conservatively merge.
11346     // GetExprRange requires an integer expression, but a throw expression
11347     // results in a void type.
11348     Expr *E = CO->getTrueExpr();
11349     IntRange L = E->getType()->isVoidType()
11350                      ? IntRange{0, true}
11351                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11352     E = CO->getFalseExpr();
11353     IntRange R = E->getType()->isVoidType()
11354                      ? IntRange{0, true}
11355                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11356     return IntRange::join(L, R);
11357   }
11358 
11359   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11360     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11361 
11362     switch (BO->getOpcode()) {
11363     case BO_Cmp:
11364       llvm_unreachable("builtin <=> should have class type");
11365 
11366     // Boolean-valued operations are single-bit and positive.
11367     case BO_LAnd:
11368     case BO_LOr:
11369     case BO_LT:
11370     case BO_GT:
11371     case BO_LE:
11372     case BO_GE:
11373     case BO_EQ:
11374     case BO_NE:
11375       return IntRange::forBoolType();
11376 
11377     // The type of the assignments is the type of the LHS, so the RHS
11378     // is not necessarily the same type.
11379     case BO_MulAssign:
11380     case BO_DivAssign:
11381     case BO_RemAssign:
11382     case BO_AddAssign:
11383     case BO_SubAssign:
11384     case BO_XorAssign:
11385     case BO_OrAssign:
11386       // TODO: bitfields?
11387       return IntRange::forValueOfType(C, GetExprType(E));
11388 
11389     // Simple assignments just pass through the RHS, which will have
11390     // been coerced to the LHS type.
11391     case BO_Assign:
11392       // TODO: bitfields?
11393       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11394                           Approximate);
11395 
11396     // Operations with opaque sources are black-listed.
11397     case BO_PtrMemD:
11398     case BO_PtrMemI:
11399       return IntRange::forValueOfType(C, GetExprType(E));
11400 
11401     // Bitwise-and uses the *infinum* of the two source ranges.
11402     case BO_And:
11403     case BO_AndAssign:
11404       Combine = IntRange::bit_and;
11405       break;
11406 
11407     // Left shift gets black-listed based on a judgement call.
11408     case BO_Shl:
11409       // ...except that we want to treat '1 << (blah)' as logically
11410       // positive.  It's an important idiom.
11411       if (IntegerLiteral *I
11412             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11413         if (I->getValue() == 1) {
11414           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11415           return IntRange(R.Width, /*NonNegative*/ true);
11416         }
11417       }
11418       LLVM_FALLTHROUGH;
11419 
11420     case BO_ShlAssign:
11421       return IntRange::forValueOfType(C, GetExprType(E));
11422 
11423     // Right shift by a constant can narrow its left argument.
11424     case BO_Shr:
11425     case BO_ShrAssign: {
11426       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11427                                 Approximate);
11428 
11429       // If the shift amount is a positive constant, drop the width by
11430       // that much.
11431       if (Optional<llvm::APSInt> shift =
11432               BO->getRHS()->getIntegerConstantExpr(C)) {
11433         if (shift->isNonNegative()) {
11434           unsigned zext = shift->getZExtValue();
11435           if (zext >= L.Width)
11436             L.Width = (L.NonNegative ? 0 : 1);
11437           else
11438             L.Width -= zext;
11439         }
11440       }
11441 
11442       return L;
11443     }
11444 
11445     // Comma acts as its right operand.
11446     case BO_Comma:
11447       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11448                           Approximate);
11449 
11450     case BO_Add:
11451       if (!Approximate)
11452         Combine = IntRange::sum;
11453       break;
11454 
11455     case BO_Sub:
11456       if (BO->getLHS()->getType()->isPointerType())
11457         return IntRange::forValueOfType(C, GetExprType(E));
11458       if (!Approximate)
11459         Combine = IntRange::difference;
11460       break;
11461 
11462     case BO_Mul:
11463       if (!Approximate)
11464         Combine = IntRange::product;
11465       break;
11466 
11467     // The width of a division result is mostly determined by the size
11468     // of the LHS.
11469     case BO_Div: {
11470       // Don't 'pre-truncate' the operands.
11471       unsigned opWidth = C.getIntWidth(GetExprType(E));
11472       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11473                                 Approximate);
11474 
11475       // If the divisor is constant, use that.
11476       if (Optional<llvm::APSInt> divisor =
11477               BO->getRHS()->getIntegerConstantExpr(C)) {
11478         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11479         if (log2 >= L.Width)
11480           L.Width = (L.NonNegative ? 0 : 1);
11481         else
11482           L.Width = std::min(L.Width - log2, MaxWidth);
11483         return L;
11484       }
11485 
11486       // Otherwise, just use the LHS's width.
11487       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11488       // could be -1.
11489       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11490                                 Approximate);
11491       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11492     }
11493 
11494     case BO_Rem:
11495       Combine = IntRange::rem;
11496       break;
11497 
11498     // The default behavior is okay for these.
11499     case BO_Xor:
11500     case BO_Or:
11501       break;
11502     }
11503 
11504     // Combine the two ranges, but limit the result to the type in which we
11505     // performed the computation.
11506     QualType T = GetExprType(E);
11507     unsigned opWidth = C.getIntWidth(T);
11508     IntRange L =
11509         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11510     IntRange R =
11511         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11512     IntRange C = Combine(L, R);
11513     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11514     C.Width = std::min(C.Width, MaxWidth);
11515     return C;
11516   }
11517 
11518   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11519     switch (UO->getOpcode()) {
11520     // Boolean-valued operations are white-listed.
11521     case UO_LNot:
11522       return IntRange::forBoolType();
11523 
11524     // Operations with opaque sources are black-listed.
11525     case UO_Deref:
11526     case UO_AddrOf: // should be impossible
11527       return IntRange::forValueOfType(C, GetExprType(E));
11528 
11529     default:
11530       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11531                           Approximate);
11532     }
11533   }
11534 
11535   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11536     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11537                         Approximate);
11538 
11539   if (const auto *BitField = E->getSourceBitField())
11540     return IntRange(BitField->getBitWidthValue(C),
11541                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11542 
11543   return IntRange::forValueOfType(C, GetExprType(E));
11544 }
11545 
11546 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11547                              bool InConstantContext, bool Approximate) {
11548   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11549                       Approximate);
11550 }
11551 
11552 /// Checks whether the given value, which currently has the given
11553 /// source semantics, has the same value when coerced through the
11554 /// target semantics.
11555 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11556                                  const llvm::fltSemantics &Src,
11557                                  const llvm::fltSemantics &Tgt) {
11558   llvm::APFloat truncated = value;
11559 
11560   bool ignored;
11561   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11562   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11563 
11564   return truncated.bitwiseIsEqual(value);
11565 }
11566 
11567 /// Checks whether the given value, which currently has the given
11568 /// source semantics, has the same value when coerced through the
11569 /// target semantics.
11570 ///
11571 /// The value might be a vector of floats (or a complex number).
11572 static bool IsSameFloatAfterCast(const APValue &value,
11573                                  const llvm::fltSemantics &Src,
11574                                  const llvm::fltSemantics &Tgt) {
11575   if (value.isFloat())
11576     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11577 
11578   if (value.isVector()) {
11579     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11580       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11581         return false;
11582     return true;
11583   }
11584 
11585   assert(value.isComplexFloat());
11586   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11587           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11588 }
11589 
11590 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11591                                        bool IsListInit = false);
11592 
11593 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11594   // Suppress cases where we are comparing against an enum constant.
11595   if (const DeclRefExpr *DR =
11596       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11597     if (isa<EnumConstantDecl>(DR->getDecl()))
11598       return true;
11599 
11600   // Suppress cases where the value is expanded from a macro, unless that macro
11601   // is how a language represents a boolean literal. This is the case in both C
11602   // and Objective-C.
11603   SourceLocation BeginLoc = E->getBeginLoc();
11604   if (BeginLoc.isMacroID()) {
11605     StringRef MacroName = Lexer::getImmediateMacroName(
11606         BeginLoc, S.getSourceManager(), S.getLangOpts());
11607     return MacroName != "YES" && MacroName != "NO" &&
11608            MacroName != "true" && MacroName != "false";
11609   }
11610 
11611   return false;
11612 }
11613 
11614 static bool isKnownToHaveUnsignedValue(Expr *E) {
11615   return E->getType()->isIntegerType() &&
11616          (!E->getType()->isSignedIntegerType() ||
11617           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11618 }
11619 
11620 namespace {
11621 /// The promoted range of values of a type. In general this has the
11622 /// following structure:
11623 ///
11624 ///     |-----------| . . . |-----------|
11625 ///     ^           ^       ^           ^
11626 ///    Min       HoleMin  HoleMax      Max
11627 ///
11628 /// ... where there is only a hole if a signed type is promoted to unsigned
11629 /// (in which case Min and Max are the smallest and largest representable
11630 /// values).
11631 struct PromotedRange {
11632   // Min, or HoleMax if there is a hole.
11633   llvm::APSInt PromotedMin;
11634   // Max, or HoleMin if there is a hole.
11635   llvm::APSInt PromotedMax;
11636 
11637   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11638     if (R.Width == 0)
11639       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11640     else if (R.Width >= BitWidth && !Unsigned) {
11641       // Promotion made the type *narrower*. This happens when promoting
11642       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11643       // Treat all values of 'signed int' as being in range for now.
11644       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11645       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11646     } else {
11647       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11648                         .extOrTrunc(BitWidth);
11649       PromotedMin.setIsUnsigned(Unsigned);
11650 
11651       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11652                         .extOrTrunc(BitWidth);
11653       PromotedMax.setIsUnsigned(Unsigned);
11654     }
11655   }
11656 
11657   // Determine whether this range is contiguous (has no hole).
11658   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11659 
11660   // Where a constant value is within the range.
11661   enum ComparisonResult {
11662     LT = 0x1,
11663     LE = 0x2,
11664     GT = 0x4,
11665     GE = 0x8,
11666     EQ = 0x10,
11667     NE = 0x20,
11668     InRangeFlag = 0x40,
11669 
11670     Less = LE | LT | NE,
11671     Min = LE | InRangeFlag,
11672     InRange = InRangeFlag,
11673     Max = GE | InRangeFlag,
11674     Greater = GE | GT | NE,
11675 
11676     OnlyValue = LE | GE | EQ | InRangeFlag,
11677     InHole = NE
11678   };
11679 
11680   ComparisonResult compare(const llvm::APSInt &Value) const {
11681     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11682            Value.isUnsigned() == PromotedMin.isUnsigned());
11683     if (!isContiguous()) {
11684       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11685       if (Value.isMinValue()) return Min;
11686       if (Value.isMaxValue()) return Max;
11687       if (Value >= PromotedMin) return InRange;
11688       if (Value <= PromotedMax) return InRange;
11689       return InHole;
11690     }
11691 
11692     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11693     case -1: return Less;
11694     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11695     case 1:
11696       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11697       case -1: return InRange;
11698       case 0: return Max;
11699       case 1: return Greater;
11700       }
11701     }
11702 
11703     llvm_unreachable("impossible compare result");
11704   }
11705 
11706   static llvm::Optional<StringRef>
11707   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11708     if (Op == BO_Cmp) {
11709       ComparisonResult LTFlag = LT, GTFlag = GT;
11710       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11711 
11712       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11713       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11714       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11715       return llvm::None;
11716     }
11717 
11718     ComparisonResult TrueFlag, FalseFlag;
11719     if (Op == BO_EQ) {
11720       TrueFlag = EQ;
11721       FalseFlag = NE;
11722     } else if (Op == BO_NE) {
11723       TrueFlag = NE;
11724       FalseFlag = EQ;
11725     } else {
11726       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11727         TrueFlag = LT;
11728         FalseFlag = GE;
11729       } else {
11730         TrueFlag = GT;
11731         FalseFlag = LE;
11732       }
11733       if (Op == BO_GE || Op == BO_LE)
11734         std::swap(TrueFlag, FalseFlag);
11735     }
11736     if (R & TrueFlag)
11737       return StringRef("true");
11738     if (R & FalseFlag)
11739       return StringRef("false");
11740     return llvm::None;
11741   }
11742 };
11743 }
11744 
11745 static bool HasEnumType(Expr *E) {
11746   // Strip off implicit integral promotions.
11747   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11748     if (ICE->getCastKind() != CK_IntegralCast &&
11749         ICE->getCastKind() != CK_NoOp)
11750       break;
11751     E = ICE->getSubExpr();
11752   }
11753 
11754   return E->getType()->isEnumeralType();
11755 }
11756 
11757 static int classifyConstantValue(Expr *Constant) {
11758   // The values of this enumeration are used in the diagnostics
11759   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11760   enum ConstantValueKind {
11761     Miscellaneous = 0,
11762     LiteralTrue,
11763     LiteralFalse
11764   };
11765   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11766     return BL->getValue() ? ConstantValueKind::LiteralTrue
11767                           : ConstantValueKind::LiteralFalse;
11768   return ConstantValueKind::Miscellaneous;
11769 }
11770 
11771 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11772                                         Expr *Constant, Expr *Other,
11773                                         const llvm::APSInt &Value,
11774                                         bool RhsConstant) {
11775   if (S.inTemplateInstantiation())
11776     return false;
11777 
11778   Expr *OriginalOther = Other;
11779 
11780   Constant = Constant->IgnoreParenImpCasts();
11781   Other = Other->IgnoreParenImpCasts();
11782 
11783   // Suppress warnings on tautological comparisons between values of the same
11784   // enumeration type. There are only two ways we could warn on this:
11785   //  - If the constant is outside the range of representable values of
11786   //    the enumeration. In such a case, we should warn about the cast
11787   //    to enumeration type, not about the comparison.
11788   //  - If the constant is the maximum / minimum in-range value. For an
11789   //    enumeratin type, such comparisons can be meaningful and useful.
11790   if (Constant->getType()->isEnumeralType() &&
11791       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11792     return false;
11793 
11794   IntRange OtherValueRange = GetExprRange(
11795       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11796 
11797   QualType OtherT = Other->getType();
11798   if (const auto *AT = OtherT->getAs<AtomicType>())
11799     OtherT = AT->getValueType();
11800   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11801 
11802   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11803   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11804   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11805                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11806                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11807 
11808   // Whether we're treating Other as being a bool because of the form of
11809   // expression despite it having another type (typically 'int' in C).
11810   bool OtherIsBooleanDespiteType =
11811       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11812   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11813     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11814 
11815   // Check if all values in the range of possible values of this expression
11816   // lead to the same comparison outcome.
11817   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11818                                         Value.isUnsigned());
11819   auto Cmp = OtherPromotedValueRange.compare(Value);
11820   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11821   if (!Result)
11822     return false;
11823 
11824   // Also consider the range determined by the type alone. This allows us to
11825   // classify the warning under the proper diagnostic group.
11826   bool TautologicalTypeCompare = false;
11827   {
11828     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11829                                          Value.isUnsigned());
11830     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11831     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11832                                                        RhsConstant)) {
11833       TautologicalTypeCompare = true;
11834       Cmp = TypeCmp;
11835       Result = TypeResult;
11836     }
11837   }
11838 
11839   // Don't warn if the non-constant operand actually always evaluates to the
11840   // same value.
11841   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11842     return false;
11843 
11844   // Suppress the diagnostic for an in-range comparison if the constant comes
11845   // from a macro or enumerator. We don't want to diagnose
11846   //
11847   //   some_long_value <= INT_MAX
11848   //
11849   // when sizeof(int) == sizeof(long).
11850   bool InRange = Cmp & PromotedRange::InRangeFlag;
11851   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11852     return false;
11853 
11854   // A comparison of an unsigned bit-field against 0 is really a type problem,
11855   // even though at the type level the bit-field might promote to 'signed int'.
11856   if (Other->refersToBitField() && InRange && Value == 0 &&
11857       Other->getType()->isUnsignedIntegerOrEnumerationType())
11858     TautologicalTypeCompare = true;
11859 
11860   // If this is a comparison to an enum constant, include that
11861   // constant in the diagnostic.
11862   const EnumConstantDecl *ED = nullptr;
11863   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11864     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11865 
11866   // Should be enough for uint128 (39 decimal digits)
11867   SmallString<64> PrettySourceValue;
11868   llvm::raw_svector_ostream OS(PrettySourceValue);
11869   if (ED) {
11870     OS << '\'' << *ED << "' (" << Value << ")";
11871   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11872                Constant->IgnoreParenImpCasts())) {
11873     OS << (BL->getValue() ? "YES" : "NO");
11874   } else {
11875     OS << Value;
11876   }
11877 
11878   if (!TautologicalTypeCompare) {
11879     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11880         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11881         << E->getOpcodeStr() << OS.str() << *Result
11882         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11883     return true;
11884   }
11885 
11886   if (IsObjCSignedCharBool) {
11887     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11888                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11889                               << OS.str() << *Result);
11890     return true;
11891   }
11892 
11893   // FIXME: We use a somewhat different formatting for the in-range cases and
11894   // cases involving boolean values for historical reasons. We should pick a
11895   // consistent way of presenting these diagnostics.
11896   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11897 
11898     S.DiagRuntimeBehavior(
11899         E->getOperatorLoc(), E,
11900         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11901                          : diag::warn_tautological_bool_compare)
11902             << OS.str() << classifyConstantValue(Constant) << OtherT
11903             << OtherIsBooleanDespiteType << *Result
11904             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11905   } else {
11906     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11907     unsigned Diag =
11908         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11909             ? (HasEnumType(OriginalOther)
11910                    ? diag::warn_unsigned_enum_always_true_comparison
11911                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11912                               : diag::warn_unsigned_always_true_comparison)
11913             : diag::warn_tautological_constant_compare;
11914 
11915     S.Diag(E->getOperatorLoc(), Diag)
11916         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11917         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11918   }
11919 
11920   return true;
11921 }
11922 
11923 /// Analyze the operands of the given comparison.  Implements the
11924 /// fallback case from AnalyzeComparison.
11925 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11926   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11927   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11928 }
11929 
11930 /// Implements -Wsign-compare.
11931 ///
11932 /// \param E the binary operator to check for warnings
11933 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11934   // The type the comparison is being performed in.
11935   QualType T = E->getLHS()->getType();
11936 
11937   // Only analyze comparison operators where both sides have been converted to
11938   // the same type.
11939   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11940     return AnalyzeImpConvsInComparison(S, E);
11941 
11942   // Don't analyze value-dependent comparisons directly.
11943   if (E->isValueDependent())
11944     return AnalyzeImpConvsInComparison(S, E);
11945 
11946   Expr *LHS = E->getLHS();
11947   Expr *RHS = E->getRHS();
11948 
11949   if (T->isIntegralType(S.Context)) {
11950     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11951     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11952 
11953     // We don't care about expressions whose result is a constant.
11954     if (RHSValue && LHSValue)
11955       return AnalyzeImpConvsInComparison(S, E);
11956 
11957     // We only care about expressions where just one side is literal
11958     if ((bool)RHSValue ^ (bool)LHSValue) {
11959       // Is the constant on the RHS or LHS?
11960       const bool RhsConstant = (bool)RHSValue;
11961       Expr *Const = RhsConstant ? RHS : LHS;
11962       Expr *Other = RhsConstant ? LHS : RHS;
11963       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11964 
11965       // Check whether an integer constant comparison results in a value
11966       // of 'true' or 'false'.
11967       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11968         return AnalyzeImpConvsInComparison(S, E);
11969     }
11970   }
11971 
11972   if (!T->hasUnsignedIntegerRepresentation()) {
11973     // We don't do anything special if this isn't an unsigned integral
11974     // comparison:  we're only interested in integral comparisons, and
11975     // signed comparisons only happen in cases we don't care to warn about.
11976     return AnalyzeImpConvsInComparison(S, E);
11977   }
11978 
11979   LHS = LHS->IgnoreParenImpCasts();
11980   RHS = RHS->IgnoreParenImpCasts();
11981 
11982   if (!S.getLangOpts().CPlusPlus) {
11983     // Avoid warning about comparison of integers with different signs when
11984     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11985     // the type of `E`.
11986     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11987       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11988     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11989       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11990   }
11991 
11992   // Check to see if one of the (unmodified) operands is of different
11993   // signedness.
11994   Expr *signedOperand, *unsignedOperand;
11995   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11996     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11997            "unsigned comparison between two signed integer expressions?");
11998     signedOperand = LHS;
11999     unsignedOperand = RHS;
12000   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
12001     signedOperand = RHS;
12002     unsignedOperand = LHS;
12003   } else {
12004     return AnalyzeImpConvsInComparison(S, E);
12005   }
12006 
12007   // Otherwise, calculate the effective range of the signed operand.
12008   IntRange signedRange = GetExprRange(
12009       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
12010 
12011   // Go ahead and analyze implicit conversions in the operands.  Note
12012   // that we skip the implicit conversions on both sides.
12013   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
12014   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
12015 
12016   // If the signed range is non-negative, -Wsign-compare won't fire.
12017   if (signedRange.NonNegative)
12018     return;
12019 
12020   // For (in)equality comparisons, if the unsigned operand is a
12021   // constant which cannot collide with a overflowed signed operand,
12022   // then reinterpreting the signed operand as unsigned will not
12023   // change the result of the comparison.
12024   if (E->isEqualityOp()) {
12025     unsigned comparisonWidth = S.Context.getIntWidth(T);
12026     IntRange unsignedRange =
12027         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
12028                      /*Approximate*/ true);
12029 
12030     // We should never be unable to prove that the unsigned operand is
12031     // non-negative.
12032     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12033 
12034     if (unsignedRange.Width < comparisonWidth)
12035       return;
12036   }
12037 
12038   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12039                         S.PDiag(diag::warn_mixed_sign_comparison)
12040                             << LHS->getType() << RHS->getType()
12041                             << LHS->getSourceRange() << RHS->getSourceRange());
12042 }
12043 
12044 /// Analyzes an attempt to assign the given value to a bitfield.
12045 ///
12046 /// Returns true if there was something fishy about the attempt.
12047 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12048                                       SourceLocation InitLoc) {
12049   assert(Bitfield->isBitField());
12050   if (Bitfield->isInvalidDecl())
12051     return false;
12052 
12053   // White-list bool bitfields.
12054   QualType BitfieldType = Bitfield->getType();
12055   if (BitfieldType->isBooleanType())
12056      return false;
12057 
12058   if (BitfieldType->isEnumeralType()) {
12059     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12060     // If the underlying enum type was not explicitly specified as an unsigned
12061     // type and the enum contain only positive values, MSVC++ will cause an
12062     // inconsistency by storing this as a signed type.
12063     if (S.getLangOpts().CPlusPlus11 &&
12064         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12065         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12066         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12067       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12068           << BitfieldEnumDecl;
12069     }
12070   }
12071 
12072   if (Bitfield->getType()->isBooleanType())
12073     return false;
12074 
12075   // Ignore value- or type-dependent expressions.
12076   if (Bitfield->getBitWidth()->isValueDependent() ||
12077       Bitfield->getBitWidth()->isTypeDependent() ||
12078       Init->isValueDependent() ||
12079       Init->isTypeDependent())
12080     return false;
12081 
12082   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12083   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12084 
12085   Expr::EvalResult Result;
12086   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12087                                    Expr::SE_AllowSideEffects)) {
12088     // The RHS is not constant.  If the RHS has an enum type, make sure the
12089     // bitfield is wide enough to hold all the values of the enum without
12090     // truncation.
12091     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12092       EnumDecl *ED = EnumTy->getDecl();
12093       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12094 
12095       // Enum types are implicitly signed on Windows, so check if there are any
12096       // negative enumerators to see if the enum was intended to be signed or
12097       // not.
12098       bool SignedEnum = ED->getNumNegativeBits() > 0;
12099 
12100       // Check for surprising sign changes when assigning enum values to a
12101       // bitfield of different signedness.  If the bitfield is signed and we
12102       // have exactly the right number of bits to store this unsigned enum,
12103       // suggest changing the enum to an unsigned type. This typically happens
12104       // on Windows where unfixed enums always use an underlying type of 'int'.
12105       unsigned DiagID = 0;
12106       if (SignedEnum && !SignedBitfield) {
12107         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12108       } else if (SignedBitfield && !SignedEnum &&
12109                  ED->getNumPositiveBits() == FieldWidth) {
12110         DiagID = diag::warn_signed_bitfield_enum_conversion;
12111       }
12112 
12113       if (DiagID) {
12114         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12115         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12116         SourceRange TypeRange =
12117             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12118         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12119             << SignedEnum << TypeRange;
12120       }
12121 
12122       // Compute the required bitwidth. If the enum has negative values, we need
12123       // one more bit than the normal number of positive bits to represent the
12124       // sign bit.
12125       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12126                                                   ED->getNumNegativeBits())
12127                                        : ED->getNumPositiveBits();
12128 
12129       // Check the bitwidth.
12130       if (BitsNeeded > FieldWidth) {
12131         Expr *WidthExpr = Bitfield->getBitWidth();
12132         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12133             << Bitfield << ED;
12134         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12135             << BitsNeeded << ED << WidthExpr->getSourceRange();
12136       }
12137     }
12138 
12139     return false;
12140   }
12141 
12142   llvm::APSInt Value = Result.Val.getInt();
12143 
12144   unsigned OriginalWidth = Value.getBitWidth();
12145 
12146   if (!Value.isSigned() || Value.isNegative())
12147     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12148       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12149         OriginalWidth = Value.getMinSignedBits();
12150 
12151   if (OriginalWidth <= FieldWidth)
12152     return false;
12153 
12154   // Compute the value which the bitfield will contain.
12155   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12156   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12157 
12158   // Check whether the stored value is equal to the original value.
12159   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12160   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12161     return false;
12162 
12163   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12164   // therefore don't strictly fit into a signed bitfield of width 1.
12165   if (FieldWidth == 1 && Value == 1)
12166     return false;
12167 
12168   std::string PrettyValue = toString(Value, 10);
12169   std::string PrettyTrunc = toString(TruncatedValue, 10);
12170 
12171   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12172     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12173     << Init->getSourceRange();
12174 
12175   return true;
12176 }
12177 
12178 /// Analyze the given simple or compound assignment for warning-worthy
12179 /// operations.
12180 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12181   // Just recurse on the LHS.
12182   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12183 
12184   // We want to recurse on the RHS as normal unless we're assigning to
12185   // a bitfield.
12186   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12187     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12188                                   E->getOperatorLoc())) {
12189       // Recurse, ignoring any implicit conversions on the RHS.
12190       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12191                                         E->getOperatorLoc());
12192     }
12193   }
12194 
12195   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12196 
12197   // Diagnose implicitly sequentially-consistent atomic assignment.
12198   if (E->getLHS()->getType()->isAtomicType())
12199     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12200 }
12201 
12202 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12203 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12204                             SourceLocation CContext, unsigned diag,
12205                             bool pruneControlFlow = false) {
12206   if (pruneControlFlow) {
12207     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12208                           S.PDiag(diag)
12209                               << SourceType << T << E->getSourceRange()
12210                               << SourceRange(CContext));
12211     return;
12212   }
12213   S.Diag(E->getExprLoc(), diag)
12214     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12215 }
12216 
12217 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12218 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12219                             SourceLocation CContext,
12220                             unsigned diag, bool pruneControlFlow = false) {
12221   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12222 }
12223 
12224 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12225   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12226       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12227 }
12228 
12229 static void adornObjCBoolConversionDiagWithTernaryFixit(
12230     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12231   Expr *Ignored = SourceExpr->IgnoreImplicit();
12232   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12233     Ignored = OVE->getSourceExpr();
12234   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12235                      isa<BinaryOperator>(Ignored) ||
12236                      isa<CXXOperatorCallExpr>(Ignored);
12237   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12238   if (NeedsParens)
12239     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12240             << FixItHint::CreateInsertion(EndLoc, ")");
12241   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12242 }
12243 
12244 /// Diagnose an implicit cast from a floating point value to an integer value.
12245 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12246                                     SourceLocation CContext) {
12247   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12248   const bool PruneWarnings = S.inTemplateInstantiation();
12249 
12250   Expr *InnerE = E->IgnoreParenImpCasts();
12251   // We also want to warn on, e.g., "int i = -1.234"
12252   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12253     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12254       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12255 
12256   const bool IsLiteral =
12257       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12258 
12259   llvm::APFloat Value(0.0);
12260   bool IsConstant =
12261     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12262   if (!IsConstant) {
12263     if (isObjCSignedCharBool(S, T)) {
12264       return adornObjCBoolConversionDiagWithTernaryFixit(
12265           S, E,
12266           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12267               << E->getType());
12268     }
12269 
12270     return DiagnoseImpCast(S, E, T, CContext,
12271                            diag::warn_impcast_float_integer, PruneWarnings);
12272   }
12273 
12274   bool isExact = false;
12275 
12276   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12277                             T->hasUnsignedIntegerRepresentation());
12278   llvm::APFloat::opStatus Result = Value.convertToInteger(
12279       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12280 
12281   // FIXME: Force the precision of the source value down so we don't print
12282   // digits which are usually useless (we don't really care here if we
12283   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12284   // would automatically print the shortest representation, but it's a bit
12285   // tricky to implement.
12286   SmallString<16> PrettySourceValue;
12287   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12288   precision = (precision * 59 + 195) / 196;
12289   Value.toString(PrettySourceValue, precision);
12290 
12291   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12292     return adornObjCBoolConversionDiagWithTernaryFixit(
12293         S, E,
12294         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12295             << PrettySourceValue);
12296   }
12297 
12298   if (Result == llvm::APFloat::opOK && isExact) {
12299     if (IsLiteral) return;
12300     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12301                            PruneWarnings);
12302   }
12303 
12304   // Conversion of a floating-point value to a non-bool integer where the
12305   // integral part cannot be represented by the integer type is undefined.
12306   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12307     return DiagnoseImpCast(
12308         S, E, T, CContext,
12309         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12310                   : diag::warn_impcast_float_to_integer_out_of_range,
12311         PruneWarnings);
12312 
12313   unsigned DiagID = 0;
12314   if (IsLiteral) {
12315     // Warn on floating point literal to integer.
12316     DiagID = diag::warn_impcast_literal_float_to_integer;
12317   } else if (IntegerValue == 0) {
12318     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12319       return DiagnoseImpCast(S, E, T, CContext,
12320                              diag::warn_impcast_float_integer, PruneWarnings);
12321     }
12322     // Warn on non-zero to zero conversion.
12323     DiagID = diag::warn_impcast_float_to_integer_zero;
12324   } else {
12325     if (IntegerValue.isUnsigned()) {
12326       if (!IntegerValue.isMaxValue()) {
12327         return DiagnoseImpCast(S, E, T, CContext,
12328                                diag::warn_impcast_float_integer, PruneWarnings);
12329       }
12330     } else {  // IntegerValue.isSigned()
12331       if (!IntegerValue.isMaxSignedValue() &&
12332           !IntegerValue.isMinSignedValue()) {
12333         return DiagnoseImpCast(S, E, T, CContext,
12334                                diag::warn_impcast_float_integer, PruneWarnings);
12335       }
12336     }
12337     // Warn on evaluatable floating point expression to integer conversion.
12338     DiagID = diag::warn_impcast_float_to_integer;
12339   }
12340 
12341   SmallString<16> PrettyTargetValue;
12342   if (IsBool)
12343     PrettyTargetValue = Value.isZero() ? "false" : "true";
12344   else
12345     IntegerValue.toString(PrettyTargetValue);
12346 
12347   if (PruneWarnings) {
12348     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12349                           S.PDiag(DiagID)
12350                               << E->getType() << T.getUnqualifiedType()
12351                               << PrettySourceValue << PrettyTargetValue
12352                               << E->getSourceRange() << SourceRange(CContext));
12353   } else {
12354     S.Diag(E->getExprLoc(), DiagID)
12355         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12356         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12357   }
12358 }
12359 
12360 /// Analyze the given compound assignment for the possible losing of
12361 /// floating-point precision.
12362 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12363   assert(isa<CompoundAssignOperator>(E) &&
12364          "Must be compound assignment operation");
12365   // Recurse on the LHS and RHS in here
12366   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12367   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12368 
12369   if (E->getLHS()->getType()->isAtomicType())
12370     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12371 
12372   // Now check the outermost expression
12373   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12374   const auto *RBT = cast<CompoundAssignOperator>(E)
12375                         ->getComputationResultType()
12376                         ->getAs<BuiltinType>();
12377 
12378   // The below checks assume source is floating point.
12379   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12380 
12381   // If source is floating point but target is an integer.
12382   if (ResultBT->isInteger())
12383     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12384                            E->getExprLoc(), diag::warn_impcast_float_integer);
12385 
12386   if (!ResultBT->isFloatingPoint())
12387     return;
12388 
12389   // If both source and target are floating points, warn about losing precision.
12390   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12391       QualType(ResultBT, 0), QualType(RBT, 0));
12392   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12393     // warn about dropping FP rank.
12394     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12395                     diag::warn_impcast_float_result_precision);
12396 }
12397 
12398 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12399                                       IntRange Range) {
12400   if (!Range.Width) return "0";
12401 
12402   llvm::APSInt ValueInRange = Value;
12403   ValueInRange.setIsSigned(!Range.NonNegative);
12404   ValueInRange = ValueInRange.trunc(Range.Width);
12405   return toString(ValueInRange, 10);
12406 }
12407 
12408 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12409   if (!isa<ImplicitCastExpr>(Ex))
12410     return false;
12411 
12412   Expr *InnerE = Ex->IgnoreParenImpCasts();
12413   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12414   const Type *Source =
12415     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12416   if (Target->isDependentType())
12417     return false;
12418 
12419   const BuiltinType *FloatCandidateBT =
12420     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12421   const Type *BoolCandidateType = ToBool ? Target : Source;
12422 
12423   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12424           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12425 }
12426 
12427 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12428                                              SourceLocation CC) {
12429   unsigned NumArgs = TheCall->getNumArgs();
12430   for (unsigned i = 0; i < NumArgs; ++i) {
12431     Expr *CurrA = TheCall->getArg(i);
12432     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12433       continue;
12434 
12435     bool IsSwapped = ((i > 0) &&
12436         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12437     IsSwapped |= ((i < (NumArgs - 1)) &&
12438         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12439     if (IsSwapped) {
12440       // Warn on this floating-point to bool conversion.
12441       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12442                       CurrA->getType(), CC,
12443                       diag::warn_impcast_floating_point_to_bool);
12444     }
12445   }
12446 }
12447 
12448 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12449                                    SourceLocation CC) {
12450   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12451                         E->getExprLoc()))
12452     return;
12453 
12454   // Don't warn on functions which have return type nullptr_t.
12455   if (isa<CallExpr>(E))
12456     return;
12457 
12458   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12459   const Expr::NullPointerConstantKind NullKind =
12460       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12461   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12462     return;
12463 
12464   // Return if target type is a safe conversion.
12465   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12466       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12467     return;
12468 
12469   SourceLocation Loc = E->getSourceRange().getBegin();
12470 
12471   // Venture through the macro stacks to get to the source of macro arguments.
12472   // The new location is a better location than the complete location that was
12473   // passed in.
12474   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12475   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12476 
12477   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12478   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12479     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12480         Loc, S.SourceMgr, S.getLangOpts());
12481     if (MacroName == "NULL")
12482       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12483   }
12484 
12485   // Only warn if the null and context location are in the same macro expansion.
12486   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12487     return;
12488 
12489   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12490       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12491       << FixItHint::CreateReplacement(Loc,
12492                                       S.getFixItZeroLiteralForType(T, Loc));
12493 }
12494 
12495 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12496                                   ObjCArrayLiteral *ArrayLiteral);
12497 
12498 static void
12499 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12500                            ObjCDictionaryLiteral *DictionaryLiteral);
12501 
12502 /// Check a single element within a collection literal against the
12503 /// target element type.
12504 static void checkObjCCollectionLiteralElement(Sema &S,
12505                                               QualType TargetElementType,
12506                                               Expr *Element,
12507                                               unsigned ElementKind) {
12508   // Skip a bitcast to 'id' or qualified 'id'.
12509   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12510     if (ICE->getCastKind() == CK_BitCast &&
12511         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12512       Element = ICE->getSubExpr();
12513   }
12514 
12515   QualType ElementType = Element->getType();
12516   ExprResult ElementResult(Element);
12517   if (ElementType->getAs<ObjCObjectPointerType>() &&
12518       S.CheckSingleAssignmentConstraints(TargetElementType,
12519                                          ElementResult,
12520                                          false, false)
12521         != Sema::Compatible) {
12522     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12523         << ElementType << ElementKind << TargetElementType
12524         << Element->getSourceRange();
12525   }
12526 
12527   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12528     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12529   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12530     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12531 }
12532 
12533 /// Check an Objective-C array literal being converted to the given
12534 /// target type.
12535 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12536                                   ObjCArrayLiteral *ArrayLiteral) {
12537   if (!S.NSArrayDecl)
12538     return;
12539 
12540   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12541   if (!TargetObjCPtr)
12542     return;
12543 
12544   if (TargetObjCPtr->isUnspecialized() ||
12545       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12546         != S.NSArrayDecl->getCanonicalDecl())
12547     return;
12548 
12549   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12550   if (TypeArgs.size() != 1)
12551     return;
12552 
12553   QualType TargetElementType = TypeArgs[0];
12554   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12555     checkObjCCollectionLiteralElement(S, TargetElementType,
12556                                       ArrayLiteral->getElement(I),
12557                                       0);
12558   }
12559 }
12560 
12561 /// Check an Objective-C dictionary literal being converted to the given
12562 /// target type.
12563 static void
12564 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12565                            ObjCDictionaryLiteral *DictionaryLiteral) {
12566   if (!S.NSDictionaryDecl)
12567     return;
12568 
12569   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12570   if (!TargetObjCPtr)
12571     return;
12572 
12573   if (TargetObjCPtr->isUnspecialized() ||
12574       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12575         != S.NSDictionaryDecl->getCanonicalDecl())
12576     return;
12577 
12578   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12579   if (TypeArgs.size() != 2)
12580     return;
12581 
12582   QualType TargetKeyType = TypeArgs[0];
12583   QualType TargetObjectType = TypeArgs[1];
12584   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12585     auto Element = DictionaryLiteral->getKeyValueElement(I);
12586     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12587     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12588   }
12589 }
12590 
12591 // Helper function to filter out cases for constant width constant conversion.
12592 // Don't warn on char array initialization or for non-decimal values.
12593 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12594                                           SourceLocation CC) {
12595   // If initializing from a constant, and the constant starts with '0',
12596   // then it is a binary, octal, or hexadecimal.  Allow these constants
12597   // to fill all the bits, even if there is a sign change.
12598   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12599     const char FirstLiteralCharacter =
12600         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12601     if (FirstLiteralCharacter == '0')
12602       return false;
12603   }
12604 
12605   // If the CC location points to a '{', and the type is char, then assume
12606   // assume it is an array initialization.
12607   if (CC.isValid() && T->isCharType()) {
12608     const char FirstContextCharacter =
12609         S.getSourceManager().getCharacterData(CC)[0];
12610     if (FirstContextCharacter == '{')
12611       return false;
12612   }
12613 
12614   return true;
12615 }
12616 
12617 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12618   const auto *IL = dyn_cast<IntegerLiteral>(E);
12619   if (!IL) {
12620     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12621       if (UO->getOpcode() == UO_Minus)
12622         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12623     }
12624   }
12625 
12626   return IL;
12627 }
12628 
12629 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12630   E = E->IgnoreParenImpCasts();
12631   SourceLocation ExprLoc = E->getExprLoc();
12632 
12633   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12634     BinaryOperator::Opcode Opc = BO->getOpcode();
12635     Expr::EvalResult Result;
12636     // Do not diagnose unsigned shifts.
12637     if (Opc == BO_Shl) {
12638       const auto *LHS = getIntegerLiteral(BO->getLHS());
12639       const auto *RHS = getIntegerLiteral(BO->getRHS());
12640       if (LHS && LHS->getValue() == 0)
12641         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12642       else if (!E->isValueDependent() && LHS && RHS &&
12643                RHS->getValue().isNonNegative() &&
12644                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12645         S.Diag(ExprLoc, diag::warn_left_shift_always)
12646             << (Result.Val.getInt() != 0);
12647       else if (E->getType()->isSignedIntegerType())
12648         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12649     }
12650   }
12651 
12652   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12653     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12654     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12655     if (!LHS || !RHS)
12656       return;
12657     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12658         (RHS->getValue() == 0 || RHS->getValue() == 1))
12659       // Do not diagnose common idioms.
12660       return;
12661     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12662       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12663   }
12664 }
12665 
12666 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12667                                     SourceLocation CC,
12668                                     bool *ICContext = nullptr,
12669                                     bool IsListInit = false) {
12670   if (E->isTypeDependent() || E->isValueDependent()) return;
12671 
12672   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12673   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12674   if (Source == Target) return;
12675   if (Target->isDependentType()) return;
12676 
12677   // If the conversion context location is invalid don't complain. We also
12678   // don't want to emit a warning if the issue occurs from the expansion of
12679   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12680   // delay this check as long as possible. Once we detect we are in that
12681   // scenario, we just return.
12682   if (CC.isInvalid())
12683     return;
12684 
12685   if (Source->isAtomicType())
12686     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12687 
12688   // Diagnose implicit casts to bool.
12689   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12690     if (isa<StringLiteral>(E))
12691       // Warn on string literal to bool.  Checks for string literals in logical
12692       // and expressions, for instance, assert(0 && "error here"), are
12693       // prevented by a check in AnalyzeImplicitConversions().
12694       return DiagnoseImpCast(S, E, T, CC,
12695                              diag::warn_impcast_string_literal_to_bool);
12696     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12697         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12698       // This covers the literal expressions that evaluate to Objective-C
12699       // objects.
12700       return DiagnoseImpCast(S, E, T, CC,
12701                              diag::warn_impcast_objective_c_literal_to_bool);
12702     }
12703     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12704       // Warn on pointer to bool conversion that is always true.
12705       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12706                                      SourceRange(CC));
12707     }
12708   }
12709 
12710   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12711   // is a typedef for signed char (macOS), then that constant value has to be 1
12712   // or 0.
12713   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12714     Expr::EvalResult Result;
12715     if (E->EvaluateAsInt(Result, S.getASTContext(),
12716                          Expr::SE_AllowSideEffects)) {
12717       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12718         adornObjCBoolConversionDiagWithTernaryFixit(
12719             S, E,
12720             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12721                 << toString(Result.Val.getInt(), 10));
12722       }
12723       return;
12724     }
12725   }
12726 
12727   // Check implicit casts from Objective-C collection literals to specialized
12728   // collection types, e.g., NSArray<NSString *> *.
12729   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12730     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12731   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12732     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12733 
12734   // Strip vector types.
12735   if (isa<VectorType>(Source)) {
12736     if (Target->isVLSTBuiltinType() &&
12737         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12738                                          QualType(Source, 0)) ||
12739          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12740                                             QualType(Source, 0))))
12741       return;
12742 
12743     if (!isa<VectorType>(Target)) {
12744       if (S.SourceMgr.isInSystemMacro(CC))
12745         return;
12746       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12747     }
12748 
12749     // If the vector cast is cast between two vectors of the same size, it is
12750     // a bitcast, not a conversion.
12751     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12752       return;
12753 
12754     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12755     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12756   }
12757   if (auto VecTy = dyn_cast<VectorType>(Target))
12758     Target = VecTy->getElementType().getTypePtr();
12759 
12760   // Strip complex types.
12761   if (isa<ComplexType>(Source)) {
12762     if (!isa<ComplexType>(Target)) {
12763       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12764         return;
12765 
12766       return DiagnoseImpCast(S, E, T, CC,
12767                              S.getLangOpts().CPlusPlus
12768                                  ? diag::err_impcast_complex_scalar
12769                                  : diag::warn_impcast_complex_scalar);
12770     }
12771 
12772     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12773     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12774   }
12775 
12776   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12777   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12778 
12779   // If the source is floating point...
12780   if (SourceBT && SourceBT->isFloatingPoint()) {
12781     // ...and the target is floating point...
12782     if (TargetBT && TargetBT->isFloatingPoint()) {
12783       // ...then warn if we're dropping FP rank.
12784 
12785       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12786           QualType(SourceBT, 0), QualType(TargetBT, 0));
12787       if (Order > 0) {
12788         // Don't warn about float constants that are precisely
12789         // representable in the target type.
12790         Expr::EvalResult result;
12791         if (E->EvaluateAsRValue(result, S.Context)) {
12792           // Value might be a float, a float vector, or a float complex.
12793           if (IsSameFloatAfterCast(result.Val,
12794                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12795                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12796             return;
12797         }
12798 
12799         if (S.SourceMgr.isInSystemMacro(CC))
12800           return;
12801 
12802         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12803       }
12804       // ... or possibly if we're increasing rank, too
12805       else if (Order < 0) {
12806         if (S.SourceMgr.isInSystemMacro(CC))
12807           return;
12808 
12809         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12810       }
12811       return;
12812     }
12813 
12814     // If the target is integral, always warn.
12815     if (TargetBT && TargetBT->isInteger()) {
12816       if (S.SourceMgr.isInSystemMacro(CC))
12817         return;
12818 
12819       DiagnoseFloatingImpCast(S, E, T, CC);
12820     }
12821 
12822     // Detect the case where a call result is converted from floating-point to
12823     // to bool, and the final argument to the call is converted from bool, to
12824     // discover this typo:
12825     //
12826     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12827     //
12828     // FIXME: This is an incredibly special case; is there some more general
12829     // way to detect this class of misplaced-parentheses bug?
12830     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12831       // Check last argument of function call to see if it is an
12832       // implicit cast from a type matching the type the result
12833       // is being cast to.
12834       CallExpr *CEx = cast<CallExpr>(E);
12835       if (unsigned NumArgs = CEx->getNumArgs()) {
12836         Expr *LastA = CEx->getArg(NumArgs - 1);
12837         Expr *InnerE = LastA->IgnoreParenImpCasts();
12838         if (isa<ImplicitCastExpr>(LastA) &&
12839             InnerE->getType()->isBooleanType()) {
12840           // Warn on this floating-point to bool conversion
12841           DiagnoseImpCast(S, E, T, CC,
12842                           diag::warn_impcast_floating_point_to_bool);
12843         }
12844       }
12845     }
12846     return;
12847   }
12848 
12849   // Valid casts involving fixed point types should be accounted for here.
12850   if (Source->isFixedPointType()) {
12851     if (Target->isUnsaturatedFixedPointType()) {
12852       Expr::EvalResult Result;
12853       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12854                                   S.isConstantEvaluated())) {
12855         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12856         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12857         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12858         if (Value > MaxVal || Value < MinVal) {
12859           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12860                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12861                                     << Value.toString() << T
12862                                     << E->getSourceRange()
12863                                     << clang::SourceRange(CC));
12864           return;
12865         }
12866       }
12867     } else if (Target->isIntegerType()) {
12868       Expr::EvalResult Result;
12869       if (!S.isConstantEvaluated() &&
12870           E->EvaluateAsFixedPoint(Result, S.Context,
12871                                   Expr::SE_AllowSideEffects)) {
12872         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12873 
12874         bool Overflowed;
12875         llvm::APSInt IntResult = FXResult.convertToInt(
12876             S.Context.getIntWidth(T),
12877             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12878 
12879         if (Overflowed) {
12880           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12881                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12882                                     << FXResult.toString() << T
12883                                     << E->getSourceRange()
12884                                     << clang::SourceRange(CC));
12885           return;
12886         }
12887       }
12888     }
12889   } else if (Target->isUnsaturatedFixedPointType()) {
12890     if (Source->isIntegerType()) {
12891       Expr::EvalResult Result;
12892       if (!S.isConstantEvaluated() &&
12893           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12894         llvm::APSInt Value = Result.Val.getInt();
12895 
12896         bool Overflowed;
12897         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12898             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12899 
12900         if (Overflowed) {
12901           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12902                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12903                                     << toString(Value, /*Radix=*/10) << T
12904                                     << E->getSourceRange()
12905                                     << clang::SourceRange(CC));
12906           return;
12907         }
12908       }
12909     }
12910   }
12911 
12912   // If we are casting an integer type to a floating point type without
12913   // initialization-list syntax, we might lose accuracy if the floating
12914   // point type has a narrower significand than the integer type.
12915   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12916       TargetBT->isFloatingType() && !IsListInit) {
12917     // Determine the number of precision bits in the source integer type.
12918     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12919                                         /*Approximate*/ true);
12920     unsigned int SourcePrecision = SourceRange.Width;
12921 
12922     // Determine the number of precision bits in the
12923     // target floating point type.
12924     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12925         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12926 
12927     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12928         SourcePrecision > TargetPrecision) {
12929 
12930       if (Optional<llvm::APSInt> SourceInt =
12931               E->getIntegerConstantExpr(S.Context)) {
12932         // If the source integer is a constant, convert it to the target
12933         // floating point type. Issue a warning if the value changes
12934         // during the whole conversion.
12935         llvm::APFloat TargetFloatValue(
12936             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12937         llvm::APFloat::opStatus ConversionStatus =
12938             TargetFloatValue.convertFromAPInt(
12939                 *SourceInt, SourceBT->isSignedInteger(),
12940                 llvm::APFloat::rmNearestTiesToEven);
12941 
12942         if (ConversionStatus != llvm::APFloat::opOK) {
12943           SmallString<32> PrettySourceValue;
12944           SourceInt->toString(PrettySourceValue, 10);
12945           SmallString<32> PrettyTargetValue;
12946           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12947 
12948           S.DiagRuntimeBehavior(
12949               E->getExprLoc(), E,
12950               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12951                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12952                   << E->getSourceRange() << clang::SourceRange(CC));
12953         }
12954       } else {
12955         // Otherwise, the implicit conversion may lose precision.
12956         DiagnoseImpCast(S, E, T, CC,
12957                         diag::warn_impcast_integer_float_precision);
12958       }
12959     }
12960   }
12961 
12962   DiagnoseNullConversion(S, E, T, CC);
12963 
12964   S.DiscardMisalignedMemberAddress(Target, E);
12965 
12966   if (Target->isBooleanType())
12967     DiagnoseIntInBoolContext(S, E);
12968 
12969   if (!Source->isIntegerType() || !Target->isIntegerType())
12970     return;
12971 
12972   // TODO: remove this early return once the false positives for constant->bool
12973   // in templates, macros, etc, are reduced or removed.
12974   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12975     return;
12976 
12977   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12978       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12979     return adornObjCBoolConversionDiagWithTernaryFixit(
12980         S, E,
12981         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12982             << E->getType());
12983   }
12984 
12985   IntRange SourceTypeRange =
12986       IntRange::forTargetOfCanonicalType(S.Context, Source);
12987   IntRange LikelySourceRange =
12988       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12989   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12990 
12991   if (LikelySourceRange.Width > TargetRange.Width) {
12992     // If the source is a constant, use a default-on diagnostic.
12993     // TODO: this should happen for bitfield stores, too.
12994     Expr::EvalResult Result;
12995     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12996                          S.isConstantEvaluated())) {
12997       llvm::APSInt Value(32);
12998       Value = Result.Val.getInt();
12999 
13000       if (S.SourceMgr.isInSystemMacro(CC))
13001         return;
13002 
13003       std::string PrettySourceValue = toString(Value, 10);
13004       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13005 
13006       S.DiagRuntimeBehavior(
13007           E->getExprLoc(), E,
13008           S.PDiag(diag::warn_impcast_integer_precision_constant)
13009               << PrettySourceValue << PrettyTargetValue << E->getType() << T
13010               << E->getSourceRange() << SourceRange(CC));
13011       return;
13012     }
13013 
13014     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
13015     if (S.SourceMgr.isInSystemMacro(CC))
13016       return;
13017 
13018     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
13019       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
13020                              /* pruneControlFlow */ true);
13021     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
13022   }
13023 
13024   if (TargetRange.Width > SourceTypeRange.Width) {
13025     if (auto *UO = dyn_cast<UnaryOperator>(E))
13026       if (UO->getOpcode() == UO_Minus)
13027         if (Source->isUnsignedIntegerType()) {
13028           if (Target->isUnsignedIntegerType())
13029             return DiagnoseImpCast(S, E, T, CC,
13030                                    diag::warn_impcast_high_order_zero_bits);
13031           if (Target->isSignedIntegerType())
13032             return DiagnoseImpCast(S, E, T, CC,
13033                                    diag::warn_impcast_nonnegative_result);
13034         }
13035   }
13036 
13037   if (TargetRange.Width == LikelySourceRange.Width &&
13038       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13039       Source->isSignedIntegerType()) {
13040     // Warn when doing a signed to signed conversion, warn if the positive
13041     // source value is exactly the width of the target type, which will
13042     // cause a negative value to be stored.
13043 
13044     Expr::EvalResult Result;
13045     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13046         !S.SourceMgr.isInSystemMacro(CC)) {
13047       llvm::APSInt Value = Result.Val.getInt();
13048       if (isSameWidthConstantConversion(S, E, T, CC)) {
13049         std::string PrettySourceValue = toString(Value, 10);
13050         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13051 
13052         S.DiagRuntimeBehavior(
13053             E->getExprLoc(), E,
13054             S.PDiag(diag::warn_impcast_integer_precision_constant)
13055                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13056                 << E->getSourceRange() << SourceRange(CC));
13057         return;
13058       }
13059     }
13060 
13061     // Fall through for non-constants to give a sign conversion warning.
13062   }
13063 
13064   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13065       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13066        LikelySourceRange.Width == TargetRange.Width)) {
13067     if (S.SourceMgr.isInSystemMacro(CC))
13068       return;
13069 
13070     unsigned DiagID = diag::warn_impcast_integer_sign;
13071 
13072     // Traditionally, gcc has warned about this under -Wsign-compare.
13073     // We also want to warn about it in -Wconversion.
13074     // So if -Wconversion is off, use a completely identical diagnostic
13075     // in the sign-compare group.
13076     // The conditional-checking code will
13077     if (ICContext) {
13078       DiagID = diag::warn_impcast_integer_sign_conditional;
13079       *ICContext = true;
13080     }
13081 
13082     return DiagnoseImpCast(S, E, T, CC, DiagID);
13083   }
13084 
13085   // Diagnose conversions between different enumeration types.
13086   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13087   // type, to give us better diagnostics.
13088   QualType SourceType = E->getType();
13089   if (!S.getLangOpts().CPlusPlus) {
13090     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13091       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13092         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13093         SourceType = S.Context.getTypeDeclType(Enum);
13094         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13095       }
13096   }
13097 
13098   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13099     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13100       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13101           TargetEnum->getDecl()->hasNameForLinkage() &&
13102           SourceEnum != TargetEnum) {
13103         if (S.SourceMgr.isInSystemMacro(CC))
13104           return;
13105 
13106         return DiagnoseImpCast(S, E, SourceType, T, CC,
13107                                diag::warn_impcast_different_enum_types);
13108       }
13109 }
13110 
13111 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13112                                      SourceLocation CC, QualType T);
13113 
13114 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13115                                     SourceLocation CC, bool &ICContext) {
13116   E = E->IgnoreParenImpCasts();
13117 
13118   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13119     return CheckConditionalOperator(S, CO, CC, T);
13120 
13121   AnalyzeImplicitConversions(S, E, CC);
13122   if (E->getType() != T)
13123     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13124 }
13125 
13126 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13127                                      SourceLocation CC, QualType T) {
13128   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13129 
13130   Expr *TrueExpr = E->getTrueExpr();
13131   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13132     TrueExpr = BCO->getCommon();
13133 
13134   bool Suspicious = false;
13135   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13136   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13137 
13138   if (T->isBooleanType())
13139     DiagnoseIntInBoolContext(S, E);
13140 
13141   // If -Wconversion would have warned about either of the candidates
13142   // for a signedness conversion to the context type...
13143   if (!Suspicious) return;
13144 
13145   // ...but it's currently ignored...
13146   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13147     return;
13148 
13149   // ...then check whether it would have warned about either of the
13150   // candidates for a signedness conversion to the condition type.
13151   if (E->getType() == T) return;
13152 
13153   Suspicious = false;
13154   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13155                           E->getType(), CC, &Suspicious);
13156   if (!Suspicious)
13157     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13158                             E->getType(), CC, &Suspicious);
13159 }
13160 
13161 /// Check conversion of given expression to boolean.
13162 /// Input argument E is a logical expression.
13163 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13164   if (S.getLangOpts().Bool)
13165     return;
13166   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13167     return;
13168   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13169 }
13170 
13171 namespace {
13172 struct AnalyzeImplicitConversionsWorkItem {
13173   Expr *E;
13174   SourceLocation CC;
13175   bool IsListInit;
13176 };
13177 }
13178 
13179 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13180 /// that should be visited are added to WorkList.
13181 static void AnalyzeImplicitConversions(
13182     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13183     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13184   Expr *OrigE = Item.E;
13185   SourceLocation CC = Item.CC;
13186 
13187   QualType T = OrigE->getType();
13188   Expr *E = OrigE->IgnoreParenImpCasts();
13189 
13190   // Propagate whether we are in a C++ list initialization expression.
13191   // If so, we do not issue warnings for implicit int-float conversion
13192   // precision loss, because C++11 narrowing already handles it.
13193   bool IsListInit = Item.IsListInit ||
13194                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13195 
13196   if (E->isTypeDependent() || E->isValueDependent())
13197     return;
13198 
13199   Expr *SourceExpr = E;
13200   // Examine, but don't traverse into the source expression of an
13201   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13202   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13203   // evaluate it in the context of checking the specific conversion to T though.
13204   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13205     if (auto *Src = OVE->getSourceExpr())
13206       SourceExpr = Src;
13207 
13208   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13209     if (UO->getOpcode() == UO_Not &&
13210         UO->getSubExpr()->isKnownToHaveBooleanValue())
13211       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13212           << OrigE->getSourceRange() << T->isBooleanType()
13213           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13214 
13215   // For conditional operators, we analyze the arguments as if they
13216   // were being fed directly into the output.
13217   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13218     CheckConditionalOperator(S, CO, CC, T);
13219     return;
13220   }
13221 
13222   // Check implicit argument conversions for function calls.
13223   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13224     CheckImplicitArgumentConversions(S, Call, CC);
13225 
13226   // Go ahead and check any implicit conversions we might have skipped.
13227   // The non-canonical typecheck is just an optimization;
13228   // CheckImplicitConversion will filter out dead implicit conversions.
13229   if (SourceExpr->getType() != T)
13230     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13231 
13232   // Now continue drilling into this expression.
13233 
13234   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13235     // The bound subexpressions in a PseudoObjectExpr are not reachable
13236     // as transitive children.
13237     // FIXME: Use a more uniform representation for this.
13238     for (auto *SE : POE->semantics())
13239       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13240         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13241   }
13242 
13243   // Skip past explicit casts.
13244   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13245     E = CE->getSubExpr()->IgnoreParenImpCasts();
13246     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13247       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13248     WorkList.push_back({E, CC, IsListInit});
13249     return;
13250   }
13251 
13252   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13253     // Do a somewhat different check with comparison operators.
13254     if (BO->isComparisonOp())
13255       return AnalyzeComparison(S, BO);
13256 
13257     // And with simple assignments.
13258     if (BO->getOpcode() == BO_Assign)
13259       return AnalyzeAssignment(S, BO);
13260     // And with compound assignments.
13261     if (BO->isAssignmentOp())
13262       return AnalyzeCompoundAssignment(S, BO);
13263   }
13264 
13265   // These break the otherwise-useful invariant below.  Fortunately,
13266   // we don't really need to recurse into them, because any internal
13267   // expressions should have been analyzed already when they were
13268   // built into statements.
13269   if (isa<StmtExpr>(E)) return;
13270 
13271   // Don't descend into unevaluated contexts.
13272   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13273 
13274   // Now just recurse over the expression's children.
13275   CC = E->getExprLoc();
13276   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13277   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13278   for (Stmt *SubStmt : E->children()) {
13279     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13280     if (!ChildExpr)
13281       continue;
13282 
13283     if (IsLogicalAndOperator &&
13284         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13285       // Ignore checking string literals that are in logical and operators.
13286       // This is a common pattern for asserts.
13287       continue;
13288     WorkList.push_back({ChildExpr, CC, IsListInit});
13289   }
13290 
13291   if (BO && BO->isLogicalOp()) {
13292     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13293     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13294       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13295 
13296     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13297     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13298       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13299   }
13300 
13301   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13302     if (U->getOpcode() == UO_LNot) {
13303       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13304     } else if (U->getOpcode() != UO_AddrOf) {
13305       if (U->getSubExpr()->getType()->isAtomicType())
13306         S.Diag(U->getSubExpr()->getBeginLoc(),
13307                diag::warn_atomic_implicit_seq_cst);
13308     }
13309   }
13310 }
13311 
13312 /// AnalyzeImplicitConversions - Find and report any interesting
13313 /// implicit conversions in the given expression.  There are a couple
13314 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13315 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13316                                        bool IsListInit/*= false*/) {
13317   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13318   WorkList.push_back({OrigE, CC, IsListInit});
13319   while (!WorkList.empty())
13320     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13321 }
13322 
13323 /// Diagnose integer type and any valid implicit conversion to it.
13324 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13325   // Taking into account implicit conversions,
13326   // allow any integer.
13327   if (!E->getType()->isIntegerType()) {
13328     S.Diag(E->getBeginLoc(),
13329            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13330     return true;
13331   }
13332   // Potentially emit standard warnings for implicit conversions if enabled
13333   // using -Wconversion.
13334   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13335   return false;
13336 }
13337 
13338 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13339 // Returns true when emitting a warning about taking the address of a reference.
13340 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13341                               const PartialDiagnostic &PD) {
13342   E = E->IgnoreParenImpCasts();
13343 
13344   const FunctionDecl *FD = nullptr;
13345 
13346   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13347     if (!DRE->getDecl()->getType()->isReferenceType())
13348       return false;
13349   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13350     if (!M->getMemberDecl()->getType()->isReferenceType())
13351       return false;
13352   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13353     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13354       return false;
13355     FD = Call->getDirectCallee();
13356   } else {
13357     return false;
13358   }
13359 
13360   SemaRef.Diag(E->getExprLoc(), PD);
13361 
13362   // If possible, point to location of function.
13363   if (FD) {
13364     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13365   }
13366 
13367   return true;
13368 }
13369 
13370 // Returns true if the SourceLocation is expanded from any macro body.
13371 // Returns false if the SourceLocation is invalid, is from not in a macro
13372 // expansion, or is from expanded from a top-level macro argument.
13373 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13374   if (Loc.isInvalid())
13375     return false;
13376 
13377   while (Loc.isMacroID()) {
13378     if (SM.isMacroBodyExpansion(Loc))
13379       return true;
13380     Loc = SM.getImmediateMacroCallerLoc(Loc);
13381   }
13382 
13383   return false;
13384 }
13385 
13386 /// Diagnose pointers that are always non-null.
13387 /// \param E the expression containing the pointer
13388 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13389 /// compared to a null pointer
13390 /// \param IsEqual True when the comparison is equal to a null pointer
13391 /// \param Range Extra SourceRange to highlight in the diagnostic
13392 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13393                                         Expr::NullPointerConstantKind NullKind,
13394                                         bool IsEqual, SourceRange Range) {
13395   if (!E)
13396     return;
13397 
13398   // Don't warn inside macros.
13399   if (E->getExprLoc().isMacroID()) {
13400     const SourceManager &SM = getSourceManager();
13401     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13402         IsInAnyMacroBody(SM, Range.getBegin()))
13403       return;
13404   }
13405   E = E->IgnoreImpCasts();
13406 
13407   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13408 
13409   if (isa<CXXThisExpr>(E)) {
13410     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13411                                 : diag::warn_this_bool_conversion;
13412     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13413     return;
13414   }
13415 
13416   bool IsAddressOf = false;
13417 
13418   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13419     if (UO->getOpcode() != UO_AddrOf)
13420       return;
13421     IsAddressOf = true;
13422     E = UO->getSubExpr();
13423   }
13424 
13425   if (IsAddressOf) {
13426     unsigned DiagID = IsCompare
13427                           ? diag::warn_address_of_reference_null_compare
13428                           : diag::warn_address_of_reference_bool_conversion;
13429     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13430                                          << IsEqual;
13431     if (CheckForReference(*this, E, PD)) {
13432       return;
13433     }
13434   }
13435 
13436   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13437     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13438     std::string Str;
13439     llvm::raw_string_ostream S(Str);
13440     E->printPretty(S, nullptr, getPrintingPolicy());
13441     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13442                                 : diag::warn_cast_nonnull_to_bool;
13443     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13444       << E->getSourceRange() << Range << IsEqual;
13445     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13446   };
13447 
13448   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13449   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13450     if (auto *Callee = Call->getDirectCallee()) {
13451       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13452         ComplainAboutNonnullParamOrCall(A);
13453         return;
13454       }
13455     }
13456   }
13457 
13458   // Expect to find a single Decl.  Skip anything more complicated.
13459   ValueDecl *D = nullptr;
13460   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13461     D = R->getDecl();
13462   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13463     D = M->getMemberDecl();
13464   }
13465 
13466   // Weak Decls can be null.
13467   if (!D || D->isWeak())
13468     return;
13469 
13470   // Check for parameter decl with nonnull attribute
13471   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13472     if (getCurFunction() &&
13473         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13474       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13475         ComplainAboutNonnullParamOrCall(A);
13476         return;
13477       }
13478 
13479       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13480         // Skip function template not specialized yet.
13481         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13482           return;
13483         auto ParamIter = llvm::find(FD->parameters(), PV);
13484         assert(ParamIter != FD->param_end());
13485         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13486 
13487         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13488           if (!NonNull->args_size()) {
13489               ComplainAboutNonnullParamOrCall(NonNull);
13490               return;
13491           }
13492 
13493           for (const ParamIdx &ArgNo : NonNull->args()) {
13494             if (ArgNo.getASTIndex() == ParamNo) {
13495               ComplainAboutNonnullParamOrCall(NonNull);
13496               return;
13497             }
13498           }
13499         }
13500       }
13501     }
13502   }
13503 
13504   QualType T = D->getType();
13505   const bool IsArray = T->isArrayType();
13506   const bool IsFunction = T->isFunctionType();
13507 
13508   // Address of function is used to silence the function warning.
13509   if (IsAddressOf && IsFunction) {
13510     return;
13511   }
13512 
13513   // Found nothing.
13514   if (!IsAddressOf && !IsFunction && !IsArray)
13515     return;
13516 
13517   // Pretty print the expression for the diagnostic.
13518   std::string Str;
13519   llvm::raw_string_ostream S(Str);
13520   E->printPretty(S, nullptr, getPrintingPolicy());
13521 
13522   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13523                               : diag::warn_impcast_pointer_to_bool;
13524   enum {
13525     AddressOf,
13526     FunctionPointer,
13527     ArrayPointer
13528   } DiagType;
13529   if (IsAddressOf)
13530     DiagType = AddressOf;
13531   else if (IsFunction)
13532     DiagType = FunctionPointer;
13533   else if (IsArray)
13534     DiagType = ArrayPointer;
13535   else
13536     llvm_unreachable("Could not determine diagnostic.");
13537   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13538                                 << Range << IsEqual;
13539 
13540   if (!IsFunction)
13541     return;
13542 
13543   // Suggest '&' to silence the function warning.
13544   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13545       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13546 
13547   // Check to see if '()' fixit should be emitted.
13548   QualType ReturnType;
13549   UnresolvedSet<4> NonTemplateOverloads;
13550   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13551   if (ReturnType.isNull())
13552     return;
13553 
13554   if (IsCompare) {
13555     // There are two cases here.  If there is null constant, the only suggest
13556     // for a pointer return type.  If the null is 0, then suggest if the return
13557     // type is a pointer or an integer type.
13558     if (!ReturnType->isPointerType()) {
13559       if (NullKind == Expr::NPCK_ZeroExpression ||
13560           NullKind == Expr::NPCK_ZeroLiteral) {
13561         if (!ReturnType->isIntegerType())
13562           return;
13563       } else {
13564         return;
13565       }
13566     }
13567   } else { // !IsCompare
13568     // For function to bool, only suggest if the function pointer has bool
13569     // return type.
13570     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13571       return;
13572   }
13573   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13574       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13575 }
13576 
13577 /// Diagnoses "dangerous" implicit conversions within the given
13578 /// expression (which is a full expression).  Implements -Wconversion
13579 /// and -Wsign-compare.
13580 ///
13581 /// \param CC the "context" location of the implicit conversion, i.e.
13582 ///   the most location of the syntactic entity requiring the implicit
13583 ///   conversion
13584 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13585   // Don't diagnose in unevaluated contexts.
13586   if (isUnevaluatedContext())
13587     return;
13588 
13589   // Don't diagnose for value- or type-dependent expressions.
13590   if (E->isTypeDependent() || E->isValueDependent())
13591     return;
13592 
13593   // Check for array bounds violations in cases where the check isn't triggered
13594   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13595   // ArraySubscriptExpr is on the RHS of a variable initialization.
13596   CheckArrayAccess(E);
13597 
13598   // This is not the right CC for (e.g.) a variable initialization.
13599   AnalyzeImplicitConversions(*this, E, CC);
13600 }
13601 
13602 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13603 /// Input argument E is a logical expression.
13604 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13605   ::CheckBoolLikeConversion(*this, E, CC);
13606 }
13607 
13608 /// Diagnose when expression is an integer constant expression and its evaluation
13609 /// results in integer overflow
13610 void Sema::CheckForIntOverflow (Expr *E) {
13611   // Use a work list to deal with nested struct initializers.
13612   SmallVector<Expr *, 2> Exprs(1, E);
13613 
13614   do {
13615     Expr *OriginalE = Exprs.pop_back_val();
13616     Expr *E = OriginalE->IgnoreParenCasts();
13617 
13618     if (isa<BinaryOperator>(E)) {
13619       E->EvaluateForOverflow(Context);
13620       continue;
13621     }
13622 
13623     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13624       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13625     else if (isa<ObjCBoxedExpr>(OriginalE))
13626       E->EvaluateForOverflow(Context);
13627     else if (auto Call = dyn_cast<CallExpr>(E))
13628       Exprs.append(Call->arg_begin(), Call->arg_end());
13629     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13630       Exprs.append(Message->arg_begin(), Message->arg_end());
13631   } while (!Exprs.empty());
13632 }
13633 
13634 namespace {
13635 
13636 /// Visitor for expressions which looks for unsequenced operations on the
13637 /// same object.
13638 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13639   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13640 
13641   /// A tree of sequenced regions within an expression. Two regions are
13642   /// unsequenced if one is an ancestor or a descendent of the other. When we
13643   /// finish processing an expression with sequencing, such as a comma
13644   /// expression, we fold its tree nodes into its parent, since they are
13645   /// unsequenced with respect to nodes we will visit later.
13646   class SequenceTree {
13647     struct Value {
13648       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13649       unsigned Parent : 31;
13650       unsigned Merged : 1;
13651     };
13652     SmallVector<Value, 8> Values;
13653 
13654   public:
13655     /// A region within an expression which may be sequenced with respect
13656     /// to some other region.
13657     class Seq {
13658       friend class SequenceTree;
13659 
13660       unsigned Index;
13661 
13662       explicit Seq(unsigned N) : Index(N) {}
13663 
13664     public:
13665       Seq() : Index(0) {}
13666     };
13667 
13668     SequenceTree() { Values.push_back(Value(0)); }
13669     Seq root() const { return Seq(0); }
13670 
13671     /// Create a new sequence of operations, which is an unsequenced
13672     /// subset of \p Parent. This sequence of operations is sequenced with
13673     /// respect to other children of \p Parent.
13674     Seq allocate(Seq Parent) {
13675       Values.push_back(Value(Parent.Index));
13676       return Seq(Values.size() - 1);
13677     }
13678 
13679     /// Merge a sequence of operations into its parent.
13680     void merge(Seq S) {
13681       Values[S.Index].Merged = true;
13682     }
13683 
13684     /// Determine whether two operations are unsequenced. This operation
13685     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13686     /// should have been merged into its parent as appropriate.
13687     bool isUnsequenced(Seq Cur, Seq Old) {
13688       unsigned C = representative(Cur.Index);
13689       unsigned Target = representative(Old.Index);
13690       while (C >= Target) {
13691         if (C == Target)
13692           return true;
13693         C = Values[C].Parent;
13694       }
13695       return false;
13696     }
13697 
13698   private:
13699     /// Pick a representative for a sequence.
13700     unsigned representative(unsigned K) {
13701       if (Values[K].Merged)
13702         // Perform path compression as we go.
13703         return Values[K].Parent = representative(Values[K].Parent);
13704       return K;
13705     }
13706   };
13707 
13708   /// An object for which we can track unsequenced uses.
13709   using Object = const NamedDecl *;
13710 
13711   /// Different flavors of object usage which we track. We only track the
13712   /// least-sequenced usage of each kind.
13713   enum UsageKind {
13714     /// A read of an object. Multiple unsequenced reads are OK.
13715     UK_Use,
13716 
13717     /// A modification of an object which is sequenced before the value
13718     /// computation of the expression, such as ++n in C++.
13719     UK_ModAsValue,
13720 
13721     /// A modification of an object which is not sequenced before the value
13722     /// computation of the expression, such as n++.
13723     UK_ModAsSideEffect,
13724 
13725     UK_Count = UK_ModAsSideEffect + 1
13726   };
13727 
13728   /// Bundle together a sequencing region and the expression corresponding
13729   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13730   struct Usage {
13731     const Expr *UsageExpr;
13732     SequenceTree::Seq Seq;
13733 
13734     Usage() : UsageExpr(nullptr), Seq() {}
13735   };
13736 
13737   struct UsageInfo {
13738     Usage Uses[UK_Count];
13739 
13740     /// Have we issued a diagnostic for this object already?
13741     bool Diagnosed;
13742 
13743     UsageInfo() : Uses(), Diagnosed(false) {}
13744   };
13745   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13746 
13747   Sema &SemaRef;
13748 
13749   /// Sequenced regions within the expression.
13750   SequenceTree Tree;
13751 
13752   /// Declaration modifications and references which we have seen.
13753   UsageInfoMap UsageMap;
13754 
13755   /// The region we are currently within.
13756   SequenceTree::Seq Region;
13757 
13758   /// Filled in with declarations which were modified as a side-effect
13759   /// (that is, post-increment operations).
13760   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13761 
13762   /// Expressions to check later. We defer checking these to reduce
13763   /// stack usage.
13764   SmallVectorImpl<const Expr *> &WorkList;
13765 
13766   /// RAII object wrapping the visitation of a sequenced subexpression of an
13767   /// expression. At the end of this process, the side-effects of the evaluation
13768   /// become sequenced with respect to the value computation of the result, so
13769   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13770   /// UK_ModAsValue.
13771   struct SequencedSubexpression {
13772     SequencedSubexpression(SequenceChecker &Self)
13773       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13774       Self.ModAsSideEffect = &ModAsSideEffect;
13775     }
13776 
13777     ~SequencedSubexpression() {
13778       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13779         // Add a new usage with usage kind UK_ModAsValue, and then restore
13780         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13781         // the previous one was empty).
13782         UsageInfo &UI = Self.UsageMap[M.first];
13783         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13784         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13785         SideEffectUsage = M.second;
13786       }
13787       Self.ModAsSideEffect = OldModAsSideEffect;
13788     }
13789 
13790     SequenceChecker &Self;
13791     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13792     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13793   };
13794 
13795   /// RAII object wrapping the visitation of a subexpression which we might
13796   /// choose to evaluate as a constant. If any subexpression is evaluated and
13797   /// found to be non-constant, this allows us to suppress the evaluation of
13798   /// the outer expression.
13799   class EvaluationTracker {
13800   public:
13801     EvaluationTracker(SequenceChecker &Self)
13802         : Self(Self), Prev(Self.EvalTracker) {
13803       Self.EvalTracker = this;
13804     }
13805 
13806     ~EvaluationTracker() {
13807       Self.EvalTracker = Prev;
13808       if (Prev)
13809         Prev->EvalOK &= EvalOK;
13810     }
13811 
13812     bool evaluate(const Expr *E, bool &Result) {
13813       if (!EvalOK || E->isValueDependent())
13814         return false;
13815       EvalOK = E->EvaluateAsBooleanCondition(
13816           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13817       return EvalOK;
13818     }
13819 
13820   private:
13821     SequenceChecker &Self;
13822     EvaluationTracker *Prev;
13823     bool EvalOK = true;
13824   } *EvalTracker = nullptr;
13825 
13826   /// Find the object which is produced by the specified expression,
13827   /// if any.
13828   Object getObject(const Expr *E, bool Mod) const {
13829     E = E->IgnoreParenCasts();
13830     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13831       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13832         return getObject(UO->getSubExpr(), Mod);
13833     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13834       if (BO->getOpcode() == BO_Comma)
13835         return getObject(BO->getRHS(), Mod);
13836       if (Mod && BO->isAssignmentOp())
13837         return getObject(BO->getLHS(), Mod);
13838     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13839       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13840       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13841         return ME->getMemberDecl();
13842     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13843       // FIXME: If this is a reference, map through to its value.
13844       return DRE->getDecl();
13845     return nullptr;
13846   }
13847 
13848   /// Note that an object \p O was modified or used by an expression
13849   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13850   /// the object \p O as obtained via the \p UsageMap.
13851   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13852     // Get the old usage for the given object and usage kind.
13853     Usage &U = UI.Uses[UK];
13854     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13855       // If we have a modification as side effect and are in a sequenced
13856       // subexpression, save the old Usage so that we can restore it later
13857       // in SequencedSubexpression::~SequencedSubexpression.
13858       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13859         ModAsSideEffect->push_back(std::make_pair(O, U));
13860       // Then record the new usage with the current sequencing region.
13861       U.UsageExpr = UsageExpr;
13862       U.Seq = Region;
13863     }
13864   }
13865 
13866   /// Check whether a modification or use of an object \p O in an expression
13867   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13868   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13869   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13870   /// usage and false we are checking for a mod-use unsequenced usage.
13871   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13872                   UsageKind OtherKind, bool IsModMod) {
13873     if (UI.Diagnosed)
13874       return;
13875 
13876     const Usage &U = UI.Uses[OtherKind];
13877     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13878       return;
13879 
13880     const Expr *Mod = U.UsageExpr;
13881     const Expr *ModOrUse = UsageExpr;
13882     if (OtherKind == UK_Use)
13883       std::swap(Mod, ModOrUse);
13884 
13885     SemaRef.DiagRuntimeBehavior(
13886         Mod->getExprLoc(), {Mod, ModOrUse},
13887         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13888                                : diag::warn_unsequenced_mod_use)
13889             << O << SourceRange(ModOrUse->getExprLoc()));
13890     UI.Diagnosed = true;
13891   }
13892 
13893   // A note on note{Pre, Post}{Use, Mod}:
13894   //
13895   // (It helps to follow the algorithm with an expression such as
13896   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13897   //  operations before C++17 and both are well-defined in C++17).
13898   //
13899   // When visiting a node which uses/modify an object we first call notePreUse
13900   // or notePreMod before visiting its sub-expression(s). At this point the
13901   // children of the current node have not yet been visited and so the eventual
13902   // uses/modifications resulting from the children of the current node have not
13903   // been recorded yet.
13904   //
13905   // We then visit the children of the current node. After that notePostUse or
13906   // notePostMod is called. These will 1) detect an unsequenced modification
13907   // as side effect (as in "k++ + k") and 2) add a new usage with the
13908   // appropriate usage kind.
13909   //
13910   // We also have to be careful that some operation sequences modification as
13911   // side effect as well (for example: || or ,). To account for this we wrap
13912   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13913   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13914   // which record usages which are modifications as side effect, and then
13915   // downgrade them (or more accurately restore the previous usage which was a
13916   // modification as side effect) when exiting the scope of the sequenced
13917   // subexpression.
13918 
13919   void notePreUse(Object O, const Expr *UseExpr) {
13920     UsageInfo &UI = UsageMap[O];
13921     // Uses conflict with other modifications.
13922     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13923   }
13924 
13925   void notePostUse(Object O, const Expr *UseExpr) {
13926     UsageInfo &UI = UsageMap[O];
13927     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13928                /*IsModMod=*/false);
13929     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13930   }
13931 
13932   void notePreMod(Object O, const Expr *ModExpr) {
13933     UsageInfo &UI = UsageMap[O];
13934     // Modifications conflict with other modifications and with uses.
13935     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13936     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13937   }
13938 
13939   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13940     UsageInfo &UI = UsageMap[O];
13941     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13942                /*IsModMod=*/true);
13943     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13944   }
13945 
13946 public:
13947   SequenceChecker(Sema &S, const Expr *E,
13948                   SmallVectorImpl<const Expr *> &WorkList)
13949       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13950     Visit(E);
13951     // Silence a -Wunused-private-field since WorkList is now unused.
13952     // TODO: Evaluate if it can be used, and if not remove it.
13953     (void)this->WorkList;
13954   }
13955 
13956   void VisitStmt(const Stmt *S) {
13957     // Skip all statements which aren't expressions for now.
13958   }
13959 
13960   void VisitExpr(const Expr *E) {
13961     // By default, just recurse to evaluated subexpressions.
13962     Base::VisitStmt(E);
13963   }
13964 
13965   void VisitCastExpr(const CastExpr *E) {
13966     Object O = Object();
13967     if (E->getCastKind() == CK_LValueToRValue)
13968       O = getObject(E->getSubExpr(), false);
13969 
13970     if (O)
13971       notePreUse(O, E);
13972     VisitExpr(E);
13973     if (O)
13974       notePostUse(O, E);
13975   }
13976 
13977   void VisitSequencedExpressions(const Expr *SequencedBefore,
13978                                  const Expr *SequencedAfter) {
13979     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13980     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13981     SequenceTree::Seq OldRegion = Region;
13982 
13983     {
13984       SequencedSubexpression SeqBefore(*this);
13985       Region = BeforeRegion;
13986       Visit(SequencedBefore);
13987     }
13988 
13989     Region = AfterRegion;
13990     Visit(SequencedAfter);
13991 
13992     Region = OldRegion;
13993 
13994     Tree.merge(BeforeRegion);
13995     Tree.merge(AfterRegion);
13996   }
13997 
13998   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13999     // C++17 [expr.sub]p1:
14000     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
14001     //   expression E1 is sequenced before the expression E2.
14002     if (SemaRef.getLangOpts().CPlusPlus17)
14003       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
14004     else {
14005       Visit(ASE->getLHS());
14006       Visit(ASE->getRHS());
14007     }
14008   }
14009 
14010   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14011   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
14012   void VisitBinPtrMem(const BinaryOperator *BO) {
14013     // C++17 [expr.mptr.oper]p4:
14014     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
14015     //  the expression E1 is sequenced before the expression E2.
14016     if (SemaRef.getLangOpts().CPlusPlus17)
14017       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14018     else {
14019       Visit(BO->getLHS());
14020       Visit(BO->getRHS());
14021     }
14022   }
14023 
14024   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14025   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14026   void VisitBinShlShr(const BinaryOperator *BO) {
14027     // C++17 [expr.shift]p4:
14028     //  The expression E1 is sequenced before the expression E2.
14029     if (SemaRef.getLangOpts().CPlusPlus17)
14030       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14031     else {
14032       Visit(BO->getLHS());
14033       Visit(BO->getRHS());
14034     }
14035   }
14036 
14037   void VisitBinComma(const BinaryOperator *BO) {
14038     // C++11 [expr.comma]p1:
14039     //   Every value computation and side effect associated with the left
14040     //   expression is sequenced before every value computation and side
14041     //   effect associated with the right expression.
14042     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14043   }
14044 
14045   void VisitBinAssign(const BinaryOperator *BO) {
14046     SequenceTree::Seq RHSRegion;
14047     SequenceTree::Seq LHSRegion;
14048     if (SemaRef.getLangOpts().CPlusPlus17) {
14049       RHSRegion = Tree.allocate(Region);
14050       LHSRegion = Tree.allocate(Region);
14051     } else {
14052       RHSRegion = Region;
14053       LHSRegion = Region;
14054     }
14055     SequenceTree::Seq OldRegion = Region;
14056 
14057     // C++11 [expr.ass]p1:
14058     //  [...] the assignment is sequenced after the value computation
14059     //  of the right and left operands, [...]
14060     //
14061     // so check it before inspecting the operands and update the
14062     // map afterwards.
14063     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14064     if (O)
14065       notePreMod(O, BO);
14066 
14067     if (SemaRef.getLangOpts().CPlusPlus17) {
14068       // C++17 [expr.ass]p1:
14069       //  [...] The right operand is sequenced before the left operand. [...]
14070       {
14071         SequencedSubexpression SeqBefore(*this);
14072         Region = RHSRegion;
14073         Visit(BO->getRHS());
14074       }
14075 
14076       Region = LHSRegion;
14077       Visit(BO->getLHS());
14078 
14079       if (O && isa<CompoundAssignOperator>(BO))
14080         notePostUse(O, BO);
14081 
14082     } else {
14083       // C++11 does not specify any sequencing between the LHS and RHS.
14084       Region = LHSRegion;
14085       Visit(BO->getLHS());
14086 
14087       if (O && isa<CompoundAssignOperator>(BO))
14088         notePostUse(O, BO);
14089 
14090       Region = RHSRegion;
14091       Visit(BO->getRHS());
14092     }
14093 
14094     // C++11 [expr.ass]p1:
14095     //  the assignment is sequenced [...] before the value computation of the
14096     //  assignment expression.
14097     // C11 6.5.16/3 has no such rule.
14098     Region = OldRegion;
14099     if (O)
14100       notePostMod(O, BO,
14101                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14102                                                   : UK_ModAsSideEffect);
14103     if (SemaRef.getLangOpts().CPlusPlus17) {
14104       Tree.merge(RHSRegion);
14105       Tree.merge(LHSRegion);
14106     }
14107   }
14108 
14109   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14110     VisitBinAssign(CAO);
14111   }
14112 
14113   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14114   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14115   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14116     Object O = getObject(UO->getSubExpr(), true);
14117     if (!O)
14118       return VisitExpr(UO);
14119 
14120     notePreMod(O, UO);
14121     Visit(UO->getSubExpr());
14122     // C++11 [expr.pre.incr]p1:
14123     //   the expression ++x is equivalent to x+=1
14124     notePostMod(O, UO,
14125                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14126                                                 : UK_ModAsSideEffect);
14127   }
14128 
14129   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14130   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14131   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14132     Object O = getObject(UO->getSubExpr(), true);
14133     if (!O)
14134       return VisitExpr(UO);
14135 
14136     notePreMod(O, UO);
14137     Visit(UO->getSubExpr());
14138     notePostMod(O, UO, UK_ModAsSideEffect);
14139   }
14140 
14141   void VisitBinLOr(const BinaryOperator *BO) {
14142     // C++11 [expr.log.or]p2:
14143     //  If the second expression is evaluated, every value computation and
14144     //  side effect associated with the first expression is sequenced before
14145     //  every value computation and side effect associated with the
14146     //  second expression.
14147     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14148     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14149     SequenceTree::Seq OldRegion = Region;
14150 
14151     EvaluationTracker Eval(*this);
14152     {
14153       SequencedSubexpression Sequenced(*this);
14154       Region = LHSRegion;
14155       Visit(BO->getLHS());
14156     }
14157 
14158     // C++11 [expr.log.or]p1:
14159     //  [...] the second operand is not evaluated if the first operand
14160     //  evaluates to true.
14161     bool EvalResult = false;
14162     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14163     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14164     if (ShouldVisitRHS) {
14165       Region = RHSRegion;
14166       Visit(BO->getRHS());
14167     }
14168 
14169     Region = OldRegion;
14170     Tree.merge(LHSRegion);
14171     Tree.merge(RHSRegion);
14172   }
14173 
14174   void VisitBinLAnd(const BinaryOperator *BO) {
14175     // C++11 [expr.log.and]p2:
14176     //  If the second expression is evaluated, every value computation and
14177     //  side effect associated with the first expression is sequenced before
14178     //  every value computation and side effect associated with the
14179     //  second expression.
14180     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14181     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14182     SequenceTree::Seq OldRegion = Region;
14183 
14184     EvaluationTracker Eval(*this);
14185     {
14186       SequencedSubexpression Sequenced(*this);
14187       Region = LHSRegion;
14188       Visit(BO->getLHS());
14189     }
14190 
14191     // C++11 [expr.log.and]p1:
14192     //  [...] the second operand is not evaluated if the first operand is false.
14193     bool EvalResult = false;
14194     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14195     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14196     if (ShouldVisitRHS) {
14197       Region = RHSRegion;
14198       Visit(BO->getRHS());
14199     }
14200 
14201     Region = OldRegion;
14202     Tree.merge(LHSRegion);
14203     Tree.merge(RHSRegion);
14204   }
14205 
14206   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14207     // C++11 [expr.cond]p1:
14208     //  [...] Every value computation and side effect associated with the first
14209     //  expression is sequenced before every value computation and side effect
14210     //  associated with the second or third expression.
14211     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14212 
14213     // No sequencing is specified between the true and false expression.
14214     // However since exactly one of both is going to be evaluated we can
14215     // consider them to be sequenced. This is needed to avoid warning on
14216     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14217     // both the true and false expressions because we can't evaluate x.
14218     // This will still allow us to detect an expression like (pre C++17)
14219     // "(x ? y += 1 : y += 2) = y".
14220     //
14221     // We don't wrap the visitation of the true and false expression with
14222     // SequencedSubexpression because we don't want to downgrade modifications
14223     // as side effect in the true and false expressions after the visition
14224     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14225     // not warn between the two "y++", but we should warn between the "y++"
14226     // and the "y".
14227     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14228     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14229     SequenceTree::Seq OldRegion = Region;
14230 
14231     EvaluationTracker Eval(*this);
14232     {
14233       SequencedSubexpression Sequenced(*this);
14234       Region = ConditionRegion;
14235       Visit(CO->getCond());
14236     }
14237 
14238     // C++11 [expr.cond]p1:
14239     // [...] The first expression is contextually converted to bool (Clause 4).
14240     // It is evaluated and if it is true, the result of the conditional
14241     // expression is the value of the second expression, otherwise that of the
14242     // third expression. Only one of the second and third expressions is
14243     // evaluated. [...]
14244     bool EvalResult = false;
14245     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14246     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14247     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14248     if (ShouldVisitTrueExpr) {
14249       Region = TrueRegion;
14250       Visit(CO->getTrueExpr());
14251     }
14252     if (ShouldVisitFalseExpr) {
14253       Region = FalseRegion;
14254       Visit(CO->getFalseExpr());
14255     }
14256 
14257     Region = OldRegion;
14258     Tree.merge(ConditionRegion);
14259     Tree.merge(TrueRegion);
14260     Tree.merge(FalseRegion);
14261   }
14262 
14263   void VisitCallExpr(const CallExpr *CE) {
14264     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14265 
14266     if (CE->isUnevaluatedBuiltinCall(Context))
14267       return;
14268 
14269     // C++11 [intro.execution]p15:
14270     //   When calling a function [...], every value computation and side effect
14271     //   associated with any argument expression, or with the postfix expression
14272     //   designating the called function, is sequenced before execution of every
14273     //   expression or statement in the body of the function [and thus before
14274     //   the value computation of its result].
14275     SequencedSubexpression Sequenced(*this);
14276     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14277       // C++17 [expr.call]p5
14278       //   The postfix-expression is sequenced before each expression in the
14279       //   expression-list and any default argument. [...]
14280       SequenceTree::Seq CalleeRegion;
14281       SequenceTree::Seq OtherRegion;
14282       if (SemaRef.getLangOpts().CPlusPlus17) {
14283         CalleeRegion = Tree.allocate(Region);
14284         OtherRegion = Tree.allocate(Region);
14285       } else {
14286         CalleeRegion = Region;
14287         OtherRegion = Region;
14288       }
14289       SequenceTree::Seq OldRegion = Region;
14290 
14291       // Visit the callee expression first.
14292       Region = CalleeRegion;
14293       if (SemaRef.getLangOpts().CPlusPlus17) {
14294         SequencedSubexpression Sequenced(*this);
14295         Visit(CE->getCallee());
14296       } else {
14297         Visit(CE->getCallee());
14298       }
14299 
14300       // Then visit the argument expressions.
14301       Region = OtherRegion;
14302       for (const Expr *Argument : CE->arguments())
14303         Visit(Argument);
14304 
14305       Region = OldRegion;
14306       if (SemaRef.getLangOpts().CPlusPlus17) {
14307         Tree.merge(CalleeRegion);
14308         Tree.merge(OtherRegion);
14309       }
14310     });
14311   }
14312 
14313   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14314     // C++17 [over.match.oper]p2:
14315     //   [...] the operator notation is first transformed to the equivalent
14316     //   function-call notation as summarized in Table 12 (where @ denotes one
14317     //   of the operators covered in the specified subclause). However, the
14318     //   operands are sequenced in the order prescribed for the built-in
14319     //   operator (Clause 8).
14320     //
14321     // From the above only overloaded binary operators and overloaded call
14322     // operators have sequencing rules in C++17 that we need to handle
14323     // separately.
14324     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14325         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14326       return VisitCallExpr(CXXOCE);
14327 
14328     enum {
14329       NoSequencing,
14330       LHSBeforeRHS,
14331       RHSBeforeLHS,
14332       LHSBeforeRest
14333     } SequencingKind;
14334     switch (CXXOCE->getOperator()) {
14335     case OO_Equal:
14336     case OO_PlusEqual:
14337     case OO_MinusEqual:
14338     case OO_StarEqual:
14339     case OO_SlashEqual:
14340     case OO_PercentEqual:
14341     case OO_CaretEqual:
14342     case OO_AmpEqual:
14343     case OO_PipeEqual:
14344     case OO_LessLessEqual:
14345     case OO_GreaterGreaterEqual:
14346       SequencingKind = RHSBeforeLHS;
14347       break;
14348 
14349     case OO_LessLess:
14350     case OO_GreaterGreater:
14351     case OO_AmpAmp:
14352     case OO_PipePipe:
14353     case OO_Comma:
14354     case OO_ArrowStar:
14355     case OO_Subscript:
14356       SequencingKind = LHSBeforeRHS;
14357       break;
14358 
14359     case OO_Call:
14360       SequencingKind = LHSBeforeRest;
14361       break;
14362 
14363     default:
14364       SequencingKind = NoSequencing;
14365       break;
14366     }
14367 
14368     if (SequencingKind == NoSequencing)
14369       return VisitCallExpr(CXXOCE);
14370 
14371     // This is a call, so all subexpressions are sequenced before the result.
14372     SequencedSubexpression Sequenced(*this);
14373 
14374     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14375       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14376              "Should only get there with C++17 and above!");
14377       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14378              "Should only get there with an overloaded binary operator"
14379              " or an overloaded call operator!");
14380 
14381       if (SequencingKind == LHSBeforeRest) {
14382         assert(CXXOCE->getOperator() == OO_Call &&
14383                "We should only have an overloaded call operator here!");
14384 
14385         // This is very similar to VisitCallExpr, except that we only have the
14386         // C++17 case. The postfix-expression is the first argument of the
14387         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14388         // are in the following arguments.
14389         //
14390         // Note that we intentionally do not visit the callee expression since
14391         // it is just a decayed reference to a function.
14392         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14393         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14394         SequenceTree::Seq OldRegion = Region;
14395 
14396         assert(CXXOCE->getNumArgs() >= 1 &&
14397                "An overloaded call operator must have at least one argument"
14398                " for the postfix-expression!");
14399         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14400         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14401                                           CXXOCE->getNumArgs() - 1);
14402 
14403         // Visit the postfix-expression first.
14404         {
14405           Region = PostfixExprRegion;
14406           SequencedSubexpression Sequenced(*this);
14407           Visit(PostfixExpr);
14408         }
14409 
14410         // Then visit the argument expressions.
14411         Region = ArgsRegion;
14412         for (const Expr *Arg : Args)
14413           Visit(Arg);
14414 
14415         Region = OldRegion;
14416         Tree.merge(PostfixExprRegion);
14417         Tree.merge(ArgsRegion);
14418       } else {
14419         assert(CXXOCE->getNumArgs() == 2 &&
14420                "Should only have two arguments here!");
14421         assert((SequencingKind == LHSBeforeRHS ||
14422                 SequencingKind == RHSBeforeLHS) &&
14423                "Unexpected sequencing kind!");
14424 
14425         // We do not visit the callee expression since it is just a decayed
14426         // reference to a function.
14427         const Expr *E1 = CXXOCE->getArg(0);
14428         const Expr *E2 = CXXOCE->getArg(1);
14429         if (SequencingKind == RHSBeforeLHS)
14430           std::swap(E1, E2);
14431 
14432         return VisitSequencedExpressions(E1, E2);
14433       }
14434     });
14435   }
14436 
14437   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14438     // This is a call, so all subexpressions are sequenced before the result.
14439     SequencedSubexpression Sequenced(*this);
14440 
14441     if (!CCE->isListInitialization())
14442       return VisitExpr(CCE);
14443 
14444     // In C++11, list initializations are sequenced.
14445     SmallVector<SequenceTree::Seq, 32> Elts;
14446     SequenceTree::Seq Parent = Region;
14447     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14448                                               E = CCE->arg_end();
14449          I != E; ++I) {
14450       Region = Tree.allocate(Parent);
14451       Elts.push_back(Region);
14452       Visit(*I);
14453     }
14454 
14455     // Forget that the initializers are sequenced.
14456     Region = Parent;
14457     for (unsigned I = 0; I < Elts.size(); ++I)
14458       Tree.merge(Elts[I]);
14459   }
14460 
14461   void VisitInitListExpr(const InitListExpr *ILE) {
14462     if (!SemaRef.getLangOpts().CPlusPlus11)
14463       return VisitExpr(ILE);
14464 
14465     // In C++11, list initializations are sequenced.
14466     SmallVector<SequenceTree::Seq, 32> Elts;
14467     SequenceTree::Seq Parent = Region;
14468     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14469       const Expr *E = ILE->getInit(I);
14470       if (!E)
14471         continue;
14472       Region = Tree.allocate(Parent);
14473       Elts.push_back(Region);
14474       Visit(E);
14475     }
14476 
14477     // Forget that the initializers are sequenced.
14478     Region = Parent;
14479     for (unsigned I = 0; I < Elts.size(); ++I)
14480       Tree.merge(Elts[I]);
14481   }
14482 };
14483 
14484 } // namespace
14485 
14486 void Sema::CheckUnsequencedOperations(const Expr *E) {
14487   SmallVector<const Expr *, 8> WorkList;
14488   WorkList.push_back(E);
14489   while (!WorkList.empty()) {
14490     const Expr *Item = WorkList.pop_back_val();
14491     SequenceChecker(*this, Item, WorkList);
14492   }
14493 }
14494 
14495 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14496                               bool IsConstexpr) {
14497   llvm::SaveAndRestore<bool> ConstantContext(
14498       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14499   CheckImplicitConversions(E, CheckLoc);
14500   if (!E->isInstantiationDependent())
14501     CheckUnsequencedOperations(E);
14502   if (!IsConstexpr && !E->isValueDependent())
14503     CheckForIntOverflow(E);
14504   DiagnoseMisalignedMembers();
14505 }
14506 
14507 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14508                                        FieldDecl *BitField,
14509                                        Expr *Init) {
14510   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14511 }
14512 
14513 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14514                                          SourceLocation Loc) {
14515   if (!PType->isVariablyModifiedType())
14516     return;
14517   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14518     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14519     return;
14520   }
14521   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14522     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14523     return;
14524   }
14525   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14526     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14527     return;
14528   }
14529 
14530   const ArrayType *AT = S.Context.getAsArrayType(PType);
14531   if (!AT)
14532     return;
14533 
14534   if (AT->getSizeModifier() != ArrayType::Star) {
14535     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14536     return;
14537   }
14538 
14539   S.Diag(Loc, diag::err_array_star_in_function_definition);
14540 }
14541 
14542 /// CheckParmsForFunctionDef - Check that the parameters of the given
14543 /// function are appropriate for the definition of a function. This
14544 /// takes care of any checks that cannot be performed on the
14545 /// declaration itself, e.g., that the types of each of the function
14546 /// parameters are complete.
14547 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14548                                     bool CheckParameterNames) {
14549   bool HasInvalidParm = false;
14550   for (ParmVarDecl *Param : Parameters) {
14551     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14552     // function declarator that is part of a function definition of
14553     // that function shall not have incomplete type.
14554     //
14555     // This is also C++ [dcl.fct]p6.
14556     if (!Param->isInvalidDecl() &&
14557         RequireCompleteType(Param->getLocation(), Param->getType(),
14558                             diag::err_typecheck_decl_incomplete_type)) {
14559       Param->setInvalidDecl();
14560       HasInvalidParm = true;
14561     }
14562 
14563     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14564     // declaration of each parameter shall include an identifier.
14565     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14566         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14567       // Diagnose this as an extension in C17 and earlier.
14568       if (!getLangOpts().C2x)
14569         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14570     }
14571 
14572     // C99 6.7.5.3p12:
14573     //   If the function declarator is not part of a definition of that
14574     //   function, parameters may have incomplete type and may use the [*]
14575     //   notation in their sequences of declarator specifiers to specify
14576     //   variable length array types.
14577     QualType PType = Param->getOriginalType();
14578     // FIXME: This diagnostic should point the '[*]' if source-location
14579     // information is added for it.
14580     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14581 
14582     // If the parameter is a c++ class type and it has to be destructed in the
14583     // callee function, declare the destructor so that it can be called by the
14584     // callee function. Do not perform any direct access check on the dtor here.
14585     if (!Param->isInvalidDecl()) {
14586       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14587         if (!ClassDecl->isInvalidDecl() &&
14588             !ClassDecl->hasIrrelevantDestructor() &&
14589             !ClassDecl->isDependentContext() &&
14590             ClassDecl->isParamDestroyedInCallee()) {
14591           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14592           MarkFunctionReferenced(Param->getLocation(), Destructor);
14593           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14594         }
14595       }
14596     }
14597 
14598     // Parameters with the pass_object_size attribute only need to be marked
14599     // constant at function definitions. Because we lack information about
14600     // whether we're on a declaration or definition when we're instantiating the
14601     // attribute, we need to check for constness here.
14602     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14603       if (!Param->getType().isConstQualified())
14604         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14605             << Attr->getSpelling() << 1;
14606 
14607     // Check for parameter names shadowing fields from the class.
14608     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14609       // The owning context for the parameter should be the function, but we
14610       // want to see if this function's declaration context is a record.
14611       DeclContext *DC = Param->getDeclContext();
14612       if (DC && DC->isFunctionOrMethod()) {
14613         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14614           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14615                                      RD, /*DeclIsField*/ false);
14616       }
14617     }
14618   }
14619 
14620   return HasInvalidParm;
14621 }
14622 
14623 Optional<std::pair<CharUnits, CharUnits>>
14624 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14625 
14626 /// Compute the alignment and offset of the base class object given the
14627 /// derived-to-base cast expression and the alignment and offset of the derived
14628 /// class object.
14629 static std::pair<CharUnits, CharUnits>
14630 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14631                                    CharUnits BaseAlignment, CharUnits Offset,
14632                                    ASTContext &Ctx) {
14633   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14634        ++PathI) {
14635     const CXXBaseSpecifier *Base = *PathI;
14636     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14637     if (Base->isVirtual()) {
14638       // The complete object may have a lower alignment than the non-virtual
14639       // alignment of the base, in which case the base may be misaligned. Choose
14640       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14641       // conservative lower bound of the complete object alignment.
14642       CharUnits NonVirtualAlignment =
14643           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14644       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14645       Offset = CharUnits::Zero();
14646     } else {
14647       const ASTRecordLayout &RL =
14648           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14649       Offset += RL.getBaseClassOffset(BaseDecl);
14650     }
14651     DerivedType = Base->getType();
14652   }
14653 
14654   return std::make_pair(BaseAlignment, Offset);
14655 }
14656 
14657 /// Compute the alignment and offset of a binary additive operator.
14658 static Optional<std::pair<CharUnits, CharUnits>>
14659 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14660                                      bool IsSub, ASTContext &Ctx) {
14661   QualType PointeeType = PtrE->getType()->getPointeeType();
14662 
14663   if (!PointeeType->isConstantSizeType())
14664     return llvm::None;
14665 
14666   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14667 
14668   if (!P)
14669     return llvm::None;
14670 
14671   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14672   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14673     CharUnits Offset = EltSize * IdxRes->getExtValue();
14674     if (IsSub)
14675       Offset = -Offset;
14676     return std::make_pair(P->first, P->second + Offset);
14677   }
14678 
14679   // If the integer expression isn't a constant expression, compute the lower
14680   // bound of the alignment using the alignment and offset of the pointer
14681   // expression and the element size.
14682   return std::make_pair(
14683       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14684       CharUnits::Zero());
14685 }
14686 
14687 /// This helper function takes an lvalue expression and returns the alignment of
14688 /// a VarDecl and a constant offset from the VarDecl.
14689 Optional<std::pair<CharUnits, CharUnits>>
14690 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14691   E = E->IgnoreParens();
14692   switch (E->getStmtClass()) {
14693   default:
14694     break;
14695   case Stmt::CStyleCastExprClass:
14696   case Stmt::CXXStaticCastExprClass:
14697   case Stmt::ImplicitCastExprClass: {
14698     auto *CE = cast<CastExpr>(E);
14699     const Expr *From = CE->getSubExpr();
14700     switch (CE->getCastKind()) {
14701     default:
14702       break;
14703     case CK_NoOp:
14704       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14705     case CK_UncheckedDerivedToBase:
14706     case CK_DerivedToBase: {
14707       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14708       if (!P)
14709         break;
14710       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14711                                                 P->second, Ctx);
14712     }
14713     }
14714     break;
14715   }
14716   case Stmt::ArraySubscriptExprClass: {
14717     auto *ASE = cast<ArraySubscriptExpr>(E);
14718     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14719                                                 false, Ctx);
14720   }
14721   case Stmt::DeclRefExprClass: {
14722     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14723       // FIXME: If VD is captured by copy or is an escaping __block variable,
14724       // use the alignment of VD's type.
14725       if (!VD->getType()->isReferenceType())
14726         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14727       if (VD->hasInit())
14728         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14729     }
14730     break;
14731   }
14732   case Stmt::MemberExprClass: {
14733     auto *ME = cast<MemberExpr>(E);
14734     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14735     if (!FD || FD->getType()->isReferenceType() ||
14736         FD->getParent()->isInvalidDecl())
14737       break;
14738     Optional<std::pair<CharUnits, CharUnits>> P;
14739     if (ME->isArrow())
14740       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14741     else
14742       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14743     if (!P)
14744       break;
14745     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14746     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14747     return std::make_pair(P->first,
14748                           P->second + CharUnits::fromQuantity(Offset));
14749   }
14750   case Stmt::UnaryOperatorClass: {
14751     auto *UO = cast<UnaryOperator>(E);
14752     switch (UO->getOpcode()) {
14753     default:
14754       break;
14755     case UO_Deref:
14756       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14757     }
14758     break;
14759   }
14760   case Stmt::BinaryOperatorClass: {
14761     auto *BO = cast<BinaryOperator>(E);
14762     auto Opcode = BO->getOpcode();
14763     switch (Opcode) {
14764     default:
14765       break;
14766     case BO_Comma:
14767       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14768     }
14769     break;
14770   }
14771   }
14772   return llvm::None;
14773 }
14774 
14775 /// This helper function takes a pointer expression and returns the alignment of
14776 /// a VarDecl and a constant offset from the VarDecl.
14777 Optional<std::pair<CharUnits, CharUnits>>
14778 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14779   E = E->IgnoreParens();
14780   switch (E->getStmtClass()) {
14781   default:
14782     break;
14783   case Stmt::CStyleCastExprClass:
14784   case Stmt::CXXStaticCastExprClass:
14785   case Stmt::ImplicitCastExprClass: {
14786     auto *CE = cast<CastExpr>(E);
14787     const Expr *From = CE->getSubExpr();
14788     switch (CE->getCastKind()) {
14789     default:
14790       break;
14791     case CK_NoOp:
14792       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14793     case CK_ArrayToPointerDecay:
14794       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14795     case CK_UncheckedDerivedToBase:
14796     case CK_DerivedToBase: {
14797       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14798       if (!P)
14799         break;
14800       return getDerivedToBaseAlignmentAndOffset(
14801           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14802     }
14803     }
14804     break;
14805   }
14806   case Stmt::CXXThisExprClass: {
14807     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14808     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14809     return std::make_pair(Alignment, CharUnits::Zero());
14810   }
14811   case Stmt::UnaryOperatorClass: {
14812     auto *UO = cast<UnaryOperator>(E);
14813     if (UO->getOpcode() == UO_AddrOf)
14814       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14815     break;
14816   }
14817   case Stmt::BinaryOperatorClass: {
14818     auto *BO = cast<BinaryOperator>(E);
14819     auto Opcode = BO->getOpcode();
14820     switch (Opcode) {
14821     default:
14822       break;
14823     case BO_Add:
14824     case BO_Sub: {
14825       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14826       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14827         std::swap(LHS, RHS);
14828       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14829                                                   Ctx);
14830     }
14831     case BO_Comma:
14832       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14833     }
14834     break;
14835   }
14836   }
14837   return llvm::None;
14838 }
14839 
14840 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14841   // See if we can compute the alignment of a VarDecl and an offset from it.
14842   Optional<std::pair<CharUnits, CharUnits>> P =
14843       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14844 
14845   if (P)
14846     return P->first.alignmentAtOffset(P->second);
14847 
14848   // If that failed, return the type's alignment.
14849   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14850 }
14851 
14852 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14853 /// pointer cast increases the alignment requirements.
14854 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14855   // This is actually a lot of work to potentially be doing on every
14856   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14857   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14858     return;
14859 
14860   // Ignore dependent types.
14861   if (T->isDependentType() || Op->getType()->isDependentType())
14862     return;
14863 
14864   // Require that the destination be a pointer type.
14865   const PointerType *DestPtr = T->getAs<PointerType>();
14866   if (!DestPtr) return;
14867 
14868   // If the destination has alignment 1, we're done.
14869   QualType DestPointee = DestPtr->getPointeeType();
14870   if (DestPointee->isIncompleteType()) return;
14871   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14872   if (DestAlign.isOne()) return;
14873 
14874   // Require that the source be a pointer type.
14875   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14876   if (!SrcPtr) return;
14877   QualType SrcPointee = SrcPtr->getPointeeType();
14878 
14879   // Explicitly allow casts from cv void*.  We already implicitly
14880   // allowed casts to cv void*, since they have alignment 1.
14881   // Also allow casts involving incomplete types, which implicitly
14882   // includes 'void'.
14883   if (SrcPointee->isIncompleteType()) return;
14884 
14885   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14886 
14887   if (SrcAlign >= DestAlign) return;
14888 
14889   Diag(TRange.getBegin(), diag::warn_cast_align)
14890     << Op->getType() << T
14891     << static_cast<unsigned>(SrcAlign.getQuantity())
14892     << static_cast<unsigned>(DestAlign.getQuantity())
14893     << TRange << Op->getSourceRange();
14894 }
14895 
14896 /// Check whether this array fits the idiom of a size-one tail padded
14897 /// array member of a struct.
14898 ///
14899 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14900 /// commonly used to emulate flexible arrays in C89 code.
14901 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14902                                     const NamedDecl *ND) {
14903   if (Size != 1 || !ND) return false;
14904 
14905   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14906   if (!FD) return false;
14907 
14908   // Don't consider sizes resulting from macro expansions or template argument
14909   // substitution to form C89 tail-padded arrays.
14910 
14911   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14912   while (TInfo) {
14913     TypeLoc TL = TInfo->getTypeLoc();
14914     // Look through typedefs.
14915     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14916       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14917       TInfo = TDL->getTypeSourceInfo();
14918       continue;
14919     }
14920     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14921       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14922       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14923         return false;
14924     }
14925     break;
14926   }
14927 
14928   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14929   if (!RD) return false;
14930   if (RD->isUnion()) return false;
14931   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14932     if (!CRD->isStandardLayout()) return false;
14933   }
14934 
14935   // See if this is the last field decl in the record.
14936   const Decl *D = FD;
14937   while ((D = D->getNextDeclInContext()))
14938     if (isa<FieldDecl>(D))
14939       return false;
14940   return true;
14941 }
14942 
14943 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14944                             const ArraySubscriptExpr *ASE,
14945                             bool AllowOnePastEnd, bool IndexNegated) {
14946   // Already diagnosed by the constant evaluator.
14947   if (isConstantEvaluated())
14948     return;
14949 
14950   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14951   if (IndexExpr->isValueDependent())
14952     return;
14953 
14954   const Type *EffectiveType =
14955       BaseExpr->getType()->getPointeeOrArrayElementType();
14956   BaseExpr = BaseExpr->IgnoreParenCasts();
14957   const ConstantArrayType *ArrayTy =
14958       Context.getAsConstantArrayType(BaseExpr->getType());
14959 
14960   const Type *BaseType =
14961       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14962   bool IsUnboundedArray = (BaseType == nullptr);
14963   if (EffectiveType->isDependentType() ||
14964       (!IsUnboundedArray && BaseType->isDependentType()))
14965     return;
14966 
14967   Expr::EvalResult Result;
14968   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14969     return;
14970 
14971   llvm::APSInt index = Result.Val.getInt();
14972   if (IndexNegated) {
14973     index.setIsUnsigned(false);
14974     index = -index;
14975   }
14976 
14977   const NamedDecl *ND = nullptr;
14978   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14979     ND = DRE->getDecl();
14980   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14981     ND = ME->getMemberDecl();
14982 
14983   if (IsUnboundedArray) {
14984     if (index.isUnsigned() || !index.isNegative()) {
14985       const auto &ASTC = getASTContext();
14986       unsigned AddrBits =
14987           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14988               EffectiveType->getCanonicalTypeInternal()));
14989       if (index.getBitWidth() < AddrBits)
14990         index = index.zext(AddrBits);
14991       Optional<CharUnits> ElemCharUnits =
14992           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14993       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14994       // pointer) bounds-checking isn't meaningful.
14995       if (!ElemCharUnits)
14996         return;
14997       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14998       // If index has more active bits than address space, we already know
14999       // we have a bounds violation to warn about.  Otherwise, compute
15000       // address of (index + 1)th element, and warn about bounds violation
15001       // only if that address exceeds address space.
15002       if (index.getActiveBits() <= AddrBits) {
15003         bool Overflow;
15004         llvm::APInt Product(index);
15005         Product += 1;
15006         Product = Product.umul_ov(ElemBytes, Overflow);
15007         if (!Overflow && Product.getActiveBits() <= AddrBits)
15008           return;
15009       }
15010 
15011       // Need to compute max possible elements in address space, since that
15012       // is included in diag message.
15013       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
15014       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
15015       MaxElems += 1;
15016       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15017       MaxElems = MaxElems.udiv(ElemBytes);
15018 
15019       unsigned DiagID =
15020           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15021               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15022 
15023       // Diag message shows element size in bits and in "bytes" (platform-
15024       // dependent CharUnits)
15025       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15026                           PDiag(DiagID)
15027                               << toString(index, 10, true) << AddrBits
15028                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15029                               << toString(ElemBytes, 10, false)
15030                               << toString(MaxElems, 10, false)
15031                               << (unsigned)MaxElems.getLimitedValue(~0U)
15032                               << IndexExpr->getSourceRange());
15033 
15034       if (!ND) {
15035         // Try harder to find a NamedDecl to point at in the note.
15036         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15037           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15038         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15039           ND = DRE->getDecl();
15040         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15041           ND = ME->getMemberDecl();
15042       }
15043 
15044       if (ND)
15045         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15046                             PDiag(diag::note_array_declared_here) << ND);
15047     }
15048     return;
15049   }
15050 
15051   if (index.isUnsigned() || !index.isNegative()) {
15052     // It is possible that the type of the base expression after
15053     // IgnoreParenCasts is incomplete, even though the type of the base
15054     // expression before IgnoreParenCasts is complete (see PR39746 for an
15055     // example). In this case we have no information about whether the array
15056     // access exceeds the array bounds. However we can still diagnose an array
15057     // access which precedes the array bounds.
15058     if (BaseType->isIncompleteType())
15059       return;
15060 
15061     llvm::APInt size = ArrayTy->getSize();
15062     if (!size.isStrictlyPositive())
15063       return;
15064 
15065     if (BaseType != EffectiveType) {
15066       // Make sure we're comparing apples to apples when comparing index to size
15067       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15068       uint64_t array_typesize = Context.getTypeSize(BaseType);
15069       // Handle ptrarith_typesize being zero, such as when casting to void*
15070       if (!ptrarith_typesize) ptrarith_typesize = 1;
15071       if (ptrarith_typesize != array_typesize) {
15072         // There's a cast to a different size type involved
15073         uint64_t ratio = array_typesize / ptrarith_typesize;
15074         // TODO: Be smarter about handling cases where array_typesize is not a
15075         // multiple of ptrarith_typesize
15076         if (ptrarith_typesize * ratio == array_typesize)
15077           size *= llvm::APInt(size.getBitWidth(), ratio);
15078       }
15079     }
15080 
15081     if (size.getBitWidth() > index.getBitWidth())
15082       index = index.zext(size.getBitWidth());
15083     else if (size.getBitWidth() < index.getBitWidth())
15084       size = size.zext(index.getBitWidth());
15085 
15086     // For array subscripting the index must be less than size, but for pointer
15087     // arithmetic also allow the index (offset) to be equal to size since
15088     // computing the next address after the end of the array is legal and
15089     // commonly done e.g. in C++ iterators and range-based for loops.
15090     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15091       return;
15092 
15093     // Also don't warn for arrays of size 1 which are members of some
15094     // structure. These are often used to approximate flexible arrays in C89
15095     // code.
15096     if (IsTailPaddedMemberArray(*this, size, ND))
15097       return;
15098 
15099     // Suppress the warning if the subscript expression (as identified by the
15100     // ']' location) and the index expression are both from macro expansions
15101     // within a system header.
15102     if (ASE) {
15103       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15104           ASE->getRBracketLoc());
15105       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15106         SourceLocation IndexLoc =
15107             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15108         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15109           return;
15110       }
15111     }
15112 
15113     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15114                           : diag::warn_ptr_arith_exceeds_bounds;
15115 
15116     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15117                         PDiag(DiagID) << toString(index, 10, true)
15118                                       << toString(size, 10, true)
15119                                       << (unsigned)size.getLimitedValue(~0U)
15120                                       << IndexExpr->getSourceRange());
15121   } else {
15122     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15123     if (!ASE) {
15124       DiagID = diag::warn_ptr_arith_precedes_bounds;
15125       if (index.isNegative()) index = -index;
15126     }
15127 
15128     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15129                         PDiag(DiagID) << toString(index, 10, true)
15130                                       << IndexExpr->getSourceRange());
15131   }
15132 
15133   if (!ND) {
15134     // Try harder to find a NamedDecl to point at in the note.
15135     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15136       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15137     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15138       ND = DRE->getDecl();
15139     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15140       ND = ME->getMemberDecl();
15141   }
15142 
15143   if (ND)
15144     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15145                         PDiag(diag::note_array_declared_here) << ND);
15146 }
15147 
15148 void Sema::CheckArrayAccess(const Expr *expr) {
15149   int AllowOnePastEnd = 0;
15150   while (expr) {
15151     expr = expr->IgnoreParenImpCasts();
15152     switch (expr->getStmtClass()) {
15153       case Stmt::ArraySubscriptExprClass: {
15154         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15155         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15156                          AllowOnePastEnd > 0);
15157         expr = ASE->getBase();
15158         break;
15159       }
15160       case Stmt::MemberExprClass: {
15161         expr = cast<MemberExpr>(expr)->getBase();
15162         break;
15163       }
15164       case Stmt::OMPArraySectionExprClass: {
15165         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15166         if (ASE->getLowerBound())
15167           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15168                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15169         return;
15170       }
15171       case Stmt::UnaryOperatorClass: {
15172         // Only unwrap the * and & unary operators
15173         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15174         expr = UO->getSubExpr();
15175         switch (UO->getOpcode()) {
15176           case UO_AddrOf:
15177             AllowOnePastEnd++;
15178             break;
15179           case UO_Deref:
15180             AllowOnePastEnd--;
15181             break;
15182           default:
15183             return;
15184         }
15185         break;
15186       }
15187       case Stmt::ConditionalOperatorClass: {
15188         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15189         if (const Expr *lhs = cond->getLHS())
15190           CheckArrayAccess(lhs);
15191         if (const Expr *rhs = cond->getRHS())
15192           CheckArrayAccess(rhs);
15193         return;
15194       }
15195       case Stmt::CXXOperatorCallExprClass: {
15196         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15197         for (const auto *Arg : OCE->arguments())
15198           CheckArrayAccess(Arg);
15199         return;
15200       }
15201       default:
15202         return;
15203     }
15204   }
15205 }
15206 
15207 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15208 
15209 namespace {
15210 
15211 struct RetainCycleOwner {
15212   VarDecl *Variable = nullptr;
15213   SourceRange Range;
15214   SourceLocation Loc;
15215   bool Indirect = false;
15216 
15217   RetainCycleOwner() = default;
15218 
15219   void setLocsFrom(Expr *e) {
15220     Loc = e->getExprLoc();
15221     Range = e->getSourceRange();
15222   }
15223 };
15224 
15225 } // namespace
15226 
15227 /// Consider whether capturing the given variable can possibly lead to
15228 /// a retain cycle.
15229 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15230   // In ARC, it's captured strongly iff the variable has __strong
15231   // lifetime.  In MRR, it's captured strongly if the variable is
15232   // __block and has an appropriate type.
15233   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15234     return false;
15235 
15236   owner.Variable = var;
15237   if (ref)
15238     owner.setLocsFrom(ref);
15239   return true;
15240 }
15241 
15242 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15243   while (true) {
15244     e = e->IgnoreParens();
15245     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15246       switch (cast->getCastKind()) {
15247       case CK_BitCast:
15248       case CK_LValueBitCast:
15249       case CK_LValueToRValue:
15250       case CK_ARCReclaimReturnedObject:
15251         e = cast->getSubExpr();
15252         continue;
15253 
15254       default:
15255         return false;
15256       }
15257     }
15258 
15259     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15260       ObjCIvarDecl *ivar = ref->getDecl();
15261       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15262         return false;
15263 
15264       // Try to find a retain cycle in the base.
15265       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15266         return false;
15267 
15268       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15269       owner.Indirect = true;
15270       return true;
15271     }
15272 
15273     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15274       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15275       if (!var) return false;
15276       return considerVariable(var, ref, owner);
15277     }
15278 
15279     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15280       if (member->isArrow()) return false;
15281 
15282       // Don't count this as an indirect ownership.
15283       e = member->getBase();
15284       continue;
15285     }
15286 
15287     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15288       // Only pay attention to pseudo-objects on property references.
15289       ObjCPropertyRefExpr *pre
15290         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15291                                               ->IgnoreParens());
15292       if (!pre) return false;
15293       if (pre->isImplicitProperty()) return false;
15294       ObjCPropertyDecl *property = pre->getExplicitProperty();
15295       if (!property->isRetaining() &&
15296           !(property->getPropertyIvarDecl() &&
15297             property->getPropertyIvarDecl()->getType()
15298               .getObjCLifetime() == Qualifiers::OCL_Strong))
15299           return false;
15300 
15301       owner.Indirect = true;
15302       if (pre->isSuperReceiver()) {
15303         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15304         if (!owner.Variable)
15305           return false;
15306         owner.Loc = pre->getLocation();
15307         owner.Range = pre->getSourceRange();
15308         return true;
15309       }
15310       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15311                               ->getSourceExpr());
15312       continue;
15313     }
15314 
15315     // Array ivars?
15316 
15317     return false;
15318   }
15319 }
15320 
15321 namespace {
15322 
15323   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15324     ASTContext &Context;
15325     VarDecl *Variable;
15326     Expr *Capturer = nullptr;
15327     bool VarWillBeReased = false;
15328 
15329     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15330         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15331           Context(Context), Variable(variable) {}
15332 
15333     void VisitDeclRefExpr(DeclRefExpr *ref) {
15334       if (ref->getDecl() == Variable && !Capturer)
15335         Capturer = ref;
15336     }
15337 
15338     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15339       if (Capturer) return;
15340       Visit(ref->getBase());
15341       if (Capturer && ref->isFreeIvar())
15342         Capturer = ref;
15343     }
15344 
15345     void VisitBlockExpr(BlockExpr *block) {
15346       // Look inside nested blocks
15347       if (block->getBlockDecl()->capturesVariable(Variable))
15348         Visit(block->getBlockDecl()->getBody());
15349     }
15350 
15351     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15352       if (Capturer) return;
15353       if (OVE->getSourceExpr())
15354         Visit(OVE->getSourceExpr());
15355     }
15356 
15357     void VisitBinaryOperator(BinaryOperator *BinOp) {
15358       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15359         return;
15360       Expr *LHS = BinOp->getLHS();
15361       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15362         if (DRE->getDecl() != Variable)
15363           return;
15364         if (Expr *RHS = BinOp->getRHS()) {
15365           RHS = RHS->IgnoreParenCasts();
15366           Optional<llvm::APSInt> Value;
15367           VarWillBeReased =
15368               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15369                *Value == 0);
15370         }
15371       }
15372     }
15373   };
15374 
15375 } // namespace
15376 
15377 /// Check whether the given argument is a block which captures a
15378 /// variable.
15379 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15380   assert(owner.Variable && owner.Loc.isValid());
15381 
15382   e = e->IgnoreParenCasts();
15383 
15384   // Look through [^{...} copy] and Block_copy(^{...}).
15385   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15386     Selector Cmd = ME->getSelector();
15387     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15388       e = ME->getInstanceReceiver();
15389       if (!e)
15390         return nullptr;
15391       e = e->IgnoreParenCasts();
15392     }
15393   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15394     if (CE->getNumArgs() == 1) {
15395       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15396       if (Fn) {
15397         const IdentifierInfo *FnI = Fn->getIdentifier();
15398         if (FnI && FnI->isStr("_Block_copy")) {
15399           e = CE->getArg(0)->IgnoreParenCasts();
15400         }
15401       }
15402     }
15403   }
15404 
15405   BlockExpr *block = dyn_cast<BlockExpr>(e);
15406   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15407     return nullptr;
15408 
15409   FindCaptureVisitor visitor(S.Context, owner.Variable);
15410   visitor.Visit(block->getBlockDecl()->getBody());
15411   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15412 }
15413 
15414 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15415                                 RetainCycleOwner &owner) {
15416   assert(capturer);
15417   assert(owner.Variable && owner.Loc.isValid());
15418 
15419   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15420     << owner.Variable << capturer->getSourceRange();
15421   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15422     << owner.Indirect << owner.Range;
15423 }
15424 
15425 /// Check for a keyword selector that starts with the word 'add' or
15426 /// 'set'.
15427 static bool isSetterLikeSelector(Selector sel) {
15428   if (sel.isUnarySelector()) return false;
15429 
15430   StringRef str = sel.getNameForSlot(0);
15431   while (!str.empty() && str.front() == '_') str = str.substr(1);
15432   if (str.startswith("set"))
15433     str = str.substr(3);
15434   else if (str.startswith("add")) {
15435     // Specially allow 'addOperationWithBlock:'.
15436     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15437       return false;
15438     str = str.substr(3);
15439   }
15440   else
15441     return false;
15442 
15443   if (str.empty()) return true;
15444   return !isLowercase(str.front());
15445 }
15446 
15447 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15448                                                     ObjCMessageExpr *Message) {
15449   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15450                                                 Message->getReceiverInterface(),
15451                                                 NSAPI::ClassId_NSMutableArray);
15452   if (!IsMutableArray) {
15453     return None;
15454   }
15455 
15456   Selector Sel = Message->getSelector();
15457 
15458   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15459     S.NSAPIObj->getNSArrayMethodKind(Sel);
15460   if (!MKOpt) {
15461     return None;
15462   }
15463 
15464   NSAPI::NSArrayMethodKind MK = *MKOpt;
15465 
15466   switch (MK) {
15467     case NSAPI::NSMutableArr_addObject:
15468     case NSAPI::NSMutableArr_insertObjectAtIndex:
15469     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15470       return 0;
15471     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15472       return 1;
15473 
15474     default:
15475       return None;
15476   }
15477 
15478   return None;
15479 }
15480 
15481 static
15482 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15483                                                   ObjCMessageExpr *Message) {
15484   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15485                                             Message->getReceiverInterface(),
15486                                             NSAPI::ClassId_NSMutableDictionary);
15487   if (!IsMutableDictionary) {
15488     return None;
15489   }
15490 
15491   Selector Sel = Message->getSelector();
15492 
15493   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15494     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15495   if (!MKOpt) {
15496     return None;
15497   }
15498 
15499   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15500 
15501   switch (MK) {
15502     case NSAPI::NSMutableDict_setObjectForKey:
15503     case NSAPI::NSMutableDict_setValueForKey:
15504     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15505       return 0;
15506 
15507     default:
15508       return None;
15509   }
15510 
15511   return None;
15512 }
15513 
15514 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15515   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15516                                                 Message->getReceiverInterface(),
15517                                                 NSAPI::ClassId_NSMutableSet);
15518 
15519   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15520                                             Message->getReceiverInterface(),
15521                                             NSAPI::ClassId_NSMutableOrderedSet);
15522   if (!IsMutableSet && !IsMutableOrderedSet) {
15523     return None;
15524   }
15525 
15526   Selector Sel = Message->getSelector();
15527 
15528   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15529   if (!MKOpt) {
15530     return None;
15531   }
15532 
15533   NSAPI::NSSetMethodKind MK = *MKOpt;
15534 
15535   switch (MK) {
15536     case NSAPI::NSMutableSet_addObject:
15537     case NSAPI::NSOrderedSet_setObjectAtIndex:
15538     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15539     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15540       return 0;
15541     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15542       return 1;
15543   }
15544 
15545   return None;
15546 }
15547 
15548 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15549   if (!Message->isInstanceMessage()) {
15550     return;
15551   }
15552 
15553   Optional<int> ArgOpt;
15554 
15555   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15556       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15557       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15558     return;
15559   }
15560 
15561   int ArgIndex = *ArgOpt;
15562 
15563   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15564   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15565     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15566   }
15567 
15568   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15569     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15570       if (ArgRE->isObjCSelfExpr()) {
15571         Diag(Message->getSourceRange().getBegin(),
15572              diag::warn_objc_circular_container)
15573           << ArgRE->getDecl() << StringRef("'super'");
15574       }
15575     }
15576   } else {
15577     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15578 
15579     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15580       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15581     }
15582 
15583     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15584       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15585         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15586           ValueDecl *Decl = ReceiverRE->getDecl();
15587           Diag(Message->getSourceRange().getBegin(),
15588                diag::warn_objc_circular_container)
15589             << Decl << Decl;
15590           if (!ArgRE->isObjCSelfExpr()) {
15591             Diag(Decl->getLocation(),
15592                  diag::note_objc_circular_container_declared_here)
15593               << Decl;
15594           }
15595         }
15596       }
15597     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15598       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15599         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15600           ObjCIvarDecl *Decl = IvarRE->getDecl();
15601           Diag(Message->getSourceRange().getBegin(),
15602                diag::warn_objc_circular_container)
15603             << Decl << Decl;
15604           Diag(Decl->getLocation(),
15605                diag::note_objc_circular_container_declared_here)
15606             << Decl;
15607         }
15608       }
15609     }
15610   }
15611 }
15612 
15613 /// Check a message send to see if it's likely to cause a retain cycle.
15614 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15615   // Only check instance methods whose selector looks like a setter.
15616   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15617     return;
15618 
15619   // Try to find a variable that the receiver is strongly owned by.
15620   RetainCycleOwner owner;
15621   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15622     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15623       return;
15624   } else {
15625     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15626     owner.Variable = getCurMethodDecl()->getSelfDecl();
15627     owner.Loc = msg->getSuperLoc();
15628     owner.Range = msg->getSuperLoc();
15629   }
15630 
15631   // Check whether the receiver is captured by any of the arguments.
15632   const ObjCMethodDecl *MD = msg->getMethodDecl();
15633   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15634     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15635       // noescape blocks should not be retained by the method.
15636       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15637         continue;
15638       return diagnoseRetainCycle(*this, capturer, owner);
15639     }
15640   }
15641 }
15642 
15643 /// Check a property assign to see if it's likely to cause a retain cycle.
15644 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15645   RetainCycleOwner owner;
15646   if (!findRetainCycleOwner(*this, receiver, owner))
15647     return;
15648 
15649   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15650     diagnoseRetainCycle(*this, capturer, owner);
15651 }
15652 
15653 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15654   RetainCycleOwner Owner;
15655   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15656     return;
15657 
15658   // Because we don't have an expression for the variable, we have to set the
15659   // location explicitly here.
15660   Owner.Loc = Var->getLocation();
15661   Owner.Range = Var->getSourceRange();
15662 
15663   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15664     diagnoseRetainCycle(*this, Capturer, Owner);
15665 }
15666 
15667 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15668                                      Expr *RHS, bool isProperty) {
15669   // Check if RHS is an Objective-C object literal, which also can get
15670   // immediately zapped in a weak reference.  Note that we explicitly
15671   // allow ObjCStringLiterals, since those are designed to never really die.
15672   RHS = RHS->IgnoreParenImpCasts();
15673 
15674   // This enum needs to match with the 'select' in
15675   // warn_objc_arc_literal_assign (off-by-1).
15676   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15677   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15678     return false;
15679 
15680   S.Diag(Loc, diag::warn_arc_literal_assign)
15681     << (unsigned) Kind
15682     << (isProperty ? 0 : 1)
15683     << RHS->getSourceRange();
15684 
15685   return true;
15686 }
15687 
15688 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15689                                     Qualifiers::ObjCLifetime LT,
15690                                     Expr *RHS, bool isProperty) {
15691   // Strip off any implicit cast added to get to the one ARC-specific.
15692   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15693     if (cast->getCastKind() == CK_ARCConsumeObject) {
15694       S.Diag(Loc, diag::warn_arc_retained_assign)
15695         << (LT == Qualifiers::OCL_ExplicitNone)
15696         << (isProperty ? 0 : 1)
15697         << RHS->getSourceRange();
15698       return true;
15699     }
15700     RHS = cast->getSubExpr();
15701   }
15702 
15703   if (LT == Qualifiers::OCL_Weak &&
15704       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15705     return true;
15706 
15707   return false;
15708 }
15709 
15710 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15711                               QualType LHS, Expr *RHS) {
15712   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15713 
15714   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15715     return false;
15716 
15717   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15718     return true;
15719 
15720   return false;
15721 }
15722 
15723 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15724                               Expr *LHS, Expr *RHS) {
15725   QualType LHSType;
15726   // PropertyRef on LHS type need be directly obtained from
15727   // its declaration as it has a PseudoType.
15728   ObjCPropertyRefExpr *PRE
15729     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15730   if (PRE && !PRE->isImplicitProperty()) {
15731     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15732     if (PD)
15733       LHSType = PD->getType();
15734   }
15735 
15736   if (LHSType.isNull())
15737     LHSType = LHS->getType();
15738 
15739   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15740 
15741   if (LT == Qualifiers::OCL_Weak) {
15742     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15743       getCurFunction()->markSafeWeakUse(LHS);
15744   }
15745 
15746   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15747     return;
15748 
15749   // FIXME. Check for other life times.
15750   if (LT != Qualifiers::OCL_None)
15751     return;
15752 
15753   if (PRE) {
15754     if (PRE->isImplicitProperty())
15755       return;
15756     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15757     if (!PD)
15758       return;
15759 
15760     unsigned Attributes = PD->getPropertyAttributes();
15761     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15762       // when 'assign' attribute was not explicitly specified
15763       // by user, ignore it and rely on property type itself
15764       // for lifetime info.
15765       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15766       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15767           LHSType->isObjCRetainableType())
15768         return;
15769 
15770       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15771         if (cast->getCastKind() == CK_ARCConsumeObject) {
15772           Diag(Loc, diag::warn_arc_retained_property_assign)
15773           << RHS->getSourceRange();
15774           return;
15775         }
15776         RHS = cast->getSubExpr();
15777       }
15778     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15779       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15780         return;
15781     }
15782   }
15783 }
15784 
15785 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15786 
15787 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15788                                         SourceLocation StmtLoc,
15789                                         const NullStmt *Body) {
15790   // Do not warn if the body is a macro that expands to nothing, e.g:
15791   //
15792   // #define CALL(x)
15793   // if (condition)
15794   //   CALL(0);
15795   if (Body->hasLeadingEmptyMacro())
15796     return false;
15797 
15798   // Get line numbers of statement and body.
15799   bool StmtLineInvalid;
15800   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15801                                                       &StmtLineInvalid);
15802   if (StmtLineInvalid)
15803     return false;
15804 
15805   bool BodyLineInvalid;
15806   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15807                                                       &BodyLineInvalid);
15808   if (BodyLineInvalid)
15809     return false;
15810 
15811   // Warn if null statement and body are on the same line.
15812   if (StmtLine != BodyLine)
15813     return false;
15814 
15815   return true;
15816 }
15817 
15818 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15819                                  const Stmt *Body,
15820                                  unsigned DiagID) {
15821   // Since this is a syntactic check, don't emit diagnostic for template
15822   // instantiations, this just adds noise.
15823   if (CurrentInstantiationScope)
15824     return;
15825 
15826   // The body should be a null statement.
15827   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15828   if (!NBody)
15829     return;
15830 
15831   // Do the usual checks.
15832   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15833     return;
15834 
15835   Diag(NBody->getSemiLoc(), DiagID);
15836   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15837 }
15838 
15839 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15840                                  const Stmt *PossibleBody) {
15841   assert(!CurrentInstantiationScope); // Ensured by caller
15842 
15843   SourceLocation StmtLoc;
15844   const Stmt *Body;
15845   unsigned DiagID;
15846   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15847     StmtLoc = FS->getRParenLoc();
15848     Body = FS->getBody();
15849     DiagID = diag::warn_empty_for_body;
15850   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15851     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15852     Body = WS->getBody();
15853     DiagID = diag::warn_empty_while_body;
15854   } else
15855     return; // Neither `for' nor `while'.
15856 
15857   // The body should be a null statement.
15858   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15859   if (!NBody)
15860     return;
15861 
15862   // Skip expensive checks if diagnostic is disabled.
15863   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15864     return;
15865 
15866   // Do the usual checks.
15867   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15868     return;
15869 
15870   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15871   // noise level low, emit diagnostics only if for/while is followed by a
15872   // CompoundStmt, e.g.:
15873   //    for (int i = 0; i < n; i++);
15874   //    {
15875   //      a(i);
15876   //    }
15877   // or if for/while is followed by a statement with more indentation
15878   // than for/while itself:
15879   //    for (int i = 0; i < n; i++);
15880   //      a(i);
15881   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15882   if (!ProbableTypo) {
15883     bool BodyColInvalid;
15884     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15885         PossibleBody->getBeginLoc(), &BodyColInvalid);
15886     if (BodyColInvalid)
15887       return;
15888 
15889     bool StmtColInvalid;
15890     unsigned StmtCol =
15891         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15892     if (StmtColInvalid)
15893       return;
15894 
15895     if (BodyCol > StmtCol)
15896       ProbableTypo = true;
15897   }
15898 
15899   if (ProbableTypo) {
15900     Diag(NBody->getSemiLoc(), DiagID);
15901     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15902   }
15903 }
15904 
15905 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15906 
15907 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15908 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15909                              SourceLocation OpLoc) {
15910   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15911     return;
15912 
15913   if (inTemplateInstantiation())
15914     return;
15915 
15916   // Strip parens and casts away.
15917   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15918   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15919 
15920   // Check for a call expression
15921   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15922   if (!CE || CE->getNumArgs() != 1)
15923     return;
15924 
15925   // Check for a call to std::move
15926   if (!CE->isCallToStdMove())
15927     return;
15928 
15929   // Get argument from std::move
15930   RHSExpr = CE->getArg(0);
15931 
15932   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15933   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15934 
15935   // Two DeclRefExpr's, check that the decls are the same.
15936   if (LHSDeclRef && RHSDeclRef) {
15937     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15938       return;
15939     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15940         RHSDeclRef->getDecl()->getCanonicalDecl())
15941       return;
15942 
15943     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15944                                         << LHSExpr->getSourceRange()
15945                                         << RHSExpr->getSourceRange();
15946     return;
15947   }
15948 
15949   // Member variables require a different approach to check for self moves.
15950   // MemberExpr's are the same if every nested MemberExpr refers to the same
15951   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15952   // the base Expr's are CXXThisExpr's.
15953   const Expr *LHSBase = LHSExpr;
15954   const Expr *RHSBase = RHSExpr;
15955   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15956   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15957   if (!LHSME || !RHSME)
15958     return;
15959 
15960   while (LHSME && RHSME) {
15961     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15962         RHSME->getMemberDecl()->getCanonicalDecl())
15963       return;
15964 
15965     LHSBase = LHSME->getBase();
15966     RHSBase = RHSME->getBase();
15967     LHSME = dyn_cast<MemberExpr>(LHSBase);
15968     RHSME = dyn_cast<MemberExpr>(RHSBase);
15969   }
15970 
15971   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15972   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15973   if (LHSDeclRef && RHSDeclRef) {
15974     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15975       return;
15976     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15977         RHSDeclRef->getDecl()->getCanonicalDecl())
15978       return;
15979 
15980     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15981                                         << LHSExpr->getSourceRange()
15982                                         << RHSExpr->getSourceRange();
15983     return;
15984   }
15985 
15986   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15987     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15988                                         << LHSExpr->getSourceRange()
15989                                         << RHSExpr->getSourceRange();
15990 }
15991 
15992 //===--- Layout compatibility ----------------------------------------------//
15993 
15994 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15995 
15996 /// Check if two enumeration types are layout-compatible.
15997 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15998   // C++11 [dcl.enum] p8:
15999   // Two enumeration types are layout-compatible if they have the same
16000   // underlying type.
16001   return ED1->isComplete() && ED2->isComplete() &&
16002          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
16003 }
16004 
16005 /// Check if two fields are layout-compatible.
16006 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
16007                                FieldDecl *Field2) {
16008   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
16009     return false;
16010 
16011   if (Field1->isBitField() != Field2->isBitField())
16012     return false;
16013 
16014   if (Field1->isBitField()) {
16015     // Make sure that the bit-fields are the same length.
16016     unsigned Bits1 = Field1->getBitWidthValue(C);
16017     unsigned Bits2 = Field2->getBitWidthValue(C);
16018 
16019     if (Bits1 != Bits2)
16020       return false;
16021   }
16022 
16023   return true;
16024 }
16025 
16026 /// Check if two standard-layout structs are layout-compatible.
16027 /// (C++11 [class.mem] p17)
16028 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16029                                      RecordDecl *RD2) {
16030   // If both records are C++ classes, check that base classes match.
16031   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16032     // If one of records is a CXXRecordDecl we are in C++ mode,
16033     // thus the other one is a CXXRecordDecl, too.
16034     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16035     // Check number of base classes.
16036     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16037       return false;
16038 
16039     // Check the base classes.
16040     for (CXXRecordDecl::base_class_const_iterator
16041                Base1 = D1CXX->bases_begin(),
16042            BaseEnd1 = D1CXX->bases_end(),
16043               Base2 = D2CXX->bases_begin();
16044          Base1 != BaseEnd1;
16045          ++Base1, ++Base2) {
16046       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16047         return false;
16048     }
16049   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16050     // If only RD2 is a C++ class, it should have zero base classes.
16051     if (D2CXX->getNumBases() > 0)
16052       return false;
16053   }
16054 
16055   // Check the fields.
16056   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16057                              Field2End = RD2->field_end(),
16058                              Field1 = RD1->field_begin(),
16059                              Field1End = RD1->field_end();
16060   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16061     if (!isLayoutCompatible(C, *Field1, *Field2))
16062       return false;
16063   }
16064   if (Field1 != Field1End || Field2 != Field2End)
16065     return false;
16066 
16067   return true;
16068 }
16069 
16070 /// Check if two standard-layout unions are layout-compatible.
16071 /// (C++11 [class.mem] p18)
16072 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16073                                     RecordDecl *RD2) {
16074   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16075   for (auto *Field2 : RD2->fields())
16076     UnmatchedFields.insert(Field2);
16077 
16078   for (auto *Field1 : RD1->fields()) {
16079     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16080         I = UnmatchedFields.begin(),
16081         E = UnmatchedFields.end();
16082 
16083     for ( ; I != E; ++I) {
16084       if (isLayoutCompatible(C, Field1, *I)) {
16085         bool Result = UnmatchedFields.erase(*I);
16086         (void) Result;
16087         assert(Result);
16088         break;
16089       }
16090     }
16091     if (I == E)
16092       return false;
16093   }
16094 
16095   return UnmatchedFields.empty();
16096 }
16097 
16098 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16099                                RecordDecl *RD2) {
16100   if (RD1->isUnion() != RD2->isUnion())
16101     return false;
16102 
16103   if (RD1->isUnion())
16104     return isLayoutCompatibleUnion(C, RD1, RD2);
16105   else
16106     return isLayoutCompatibleStruct(C, RD1, RD2);
16107 }
16108 
16109 /// Check if two types are layout-compatible in C++11 sense.
16110 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16111   if (T1.isNull() || T2.isNull())
16112     return false;
16113 
16114   // C++11 [basic.types] p11:
16115   // If two types T1 and T2 are the same type, then T1 and T2 are
16116   // layout-compatible types.
16117   if (C.hasSameType(T1, T2))
16118     return true;
16119 
16120   T1 = T1.getCanonicalType().getUnqualifiedType();
16121   T2 = T2.getCanonicalType().getUnqualifiedType();
16122 
16123   const Type::TypeClass TC1 = T1->getTypeClass();
16124   const Type::TypeClass TC2 = T2->getTypeClass();
16125 
16126   if (TC1 != TC2)
16127     return false;
16128 
16129   if (TC1 == Type::Enum) {
16130     return isLayoutCompatible(C,
16131                               cast<EnumType>(T1)->getDecl(),
16132                               cast<EnumType>(T2)->getDecl());
16133   } else if (TC1 == Type::Record) {
16134     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16135       return false;
16136 
16137     return isLayoutCompatible(C,
16138                               cast<RecordType>(T1)->getDecl(),
16139                               cast<RecordType>(T2)->getDecl());
16140   }
16141 
16142   return false;
16143 }
16144 
16145 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16146 
16147 /// Given a type tag expression find the type tag itself.
16148 ///
16149 /// \param TypeExpr Type tag expression, as it appears in user's code.
16150 ///
16151 /// \param VD Declaration of an identifier that appears in a type tag.
16152 ///
16153 /// \param MagicValue Type tag magic value.
16154 ///
16155 /// \param isConstantEvaluated whether the evalaution should be performed in
16156 
16157 /// constant context.
16158 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16159                             const ValueDecl **VD, uint64_t *MagicValue,
16160                             bool isConstantEvaluated) {
16161   while(true) {
16162     if (!TypeExpr)
16163       return false;
16164 
16165     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16166 
16167     switch (TypeExpr->getStmtClass()) {
16168     case Stmt::UnaryOperatorClass: {
16169       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16170       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16171         TypeExpr = UO->getSubExpr();
16172         continue;
16173       }
16174       return false;
16175     }
16176 
16177     case Stmt::DeclRefExprClass: {
16178       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16179       *VD = DRE->getDecl();
16180       return true;
16181     }
16182 
16183     case Stmt::IntegerLiteralClass: {
16184       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16185       llvm::APInt MagicValueAPInt = IL->getValue();
16186       if (MagicValueAPInt.getActiveBits() <= 64) {
16187         *MagicValue = MagicValueAPInt.getZExtValue();
16188         return true;
16189       } else
16190         return false;
16191     }
16192 
16193     case Stmt::BinaryConditionalOperatorClass:
16194     case Stmt::ConditionalOperatorClass: {
16195       const AbstractConditionalOperator *ACO =
16196           cast<AbstractConditionalOperator>(TypeExpr);
16197       bool Result;
16198       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16199                                                      isConstantEvaluated)) {
16200         if (Result)
16201           TypeExpr = ACO->getTrueExpr();
16202         else
16203           TypeExpr = ACO->getFalseExpr();
16204         continue;
16205       }
16206       return false;
16207     }
16208 
16209     case Stmt::BinaryOperatorClass: {
16210       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16211       if (BO->getOpcode() == BO_Comma) {
16212         TypeExpr = BO->getRHS();
16213         continue;
16214       }
16215       return false;
16216     }
16217 
16218     default:
16219       return false;
16220     }
16221   }
16222 }
16223 
16224 /// Retrieve the C type corresponding to type tag TypeExpr.
16225 ///
16226 /// \param TypeExpr Expression that specifies a type tag.
16227 ///
16228 /// \param MagicValues Registered magic values.
16229 ///
16230 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16231 ///        kind.
16232 ///
16233 /// \param TypeInfo Information about the corresponding C type.
16234 ///
16235 /// \param isConstantEvaluated whether the evalaution should be performed in
16236 /// constant context.
16237 ///
16238 /// \returns true if the corresponding C type was found.
16239 static bool GetMatchingCType(
16240     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16241     const ASTContext &Ctx,
16242     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16243         *MagicValues,
16244     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16245     bool isConstantEvaluated) {
16246   FoundWrongKind = false;
16247 
16248   // Variable declaration that has type_tag_for_datatype attribute.
16249   const ValueDecl *VD = nullptr;
16250 
16251   uint64_t MagicValue;
16252 
16253   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16254     return false;
16255 
16256   if (VD) {
16257     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16258       if (I->getArgumentKind() != ArgumentKind) {
16259         FoundWrongKind = true;
16260         return false;
16261       }
16262       TypeInfo.Type = I->getMatchingCType();
16263       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16264       TypeInfo.MustBeNull = I->getMustBeNull();
16265       return true;
16266     }
16267     return false;
16268   }
16269 
16270   if (!MagicValues)
16271     return false;
16272 
16273   llvm::DenseMap<Sema::TypeTagMagicValue,
16274                  Sema::TypeTagData>::const_iterator I =
16275       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16276   if (I == MagicValues->end())
16277     return false;
16278 
16279   TypeInfo = I->second;
16280   return true;
16281 }
16282 
16283 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16284                                       uint64_t MagicValue, QualType Type,
16285                                       bool LayoutCompatible,
16286                                       bool MustBeNull) {
16287   if (!TypeTagForDatatypeMagicValues)
16288     TypeTagForDatatypeMagicValues.reset(
16289         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16290 
16291   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16292   (*TypeTagForDatatypeMagicValues)[Magic] =
16293       TypeTagData(Type, LayoutCompatible, MustBeNull);
16294 }
16295 
16296 static bool IsSameCharType(QualType T1, QualType T2) {
16297   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16298   if (!BT1)
16299     return false;
16300 
16301   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16302   if (!BT2)
16303     return false;
16304 
16305   BuiltinType::Kind T1Kind = BT1->getKind();
16306   BuiltinType::Kind T2Kind = BT2->getKind();
16307 
16308   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16309          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16310          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16311          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16312 }
16313 
16314 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16315                                     const ArrayRef<const Expr *> ExprArgs,
16316                                     SourceLocation CallSiteLoc) {
16317   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16318   bool IsPointerAttr = Attr->getIsPointer();
16319 
16320   // Retrieve the argument representing the 'type_tag'.
16321   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16322   if (TypeTagIdxAST >= ExprArgs.size()) {
16323     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16324         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16325     return;
16326   }
16327   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16328   bool FoundWrongKind;
16329   TypeTagData TypeInfo;
16330   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16331                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16332                         TypeInfo, isConstantEvaluated())) {
16333     if (FoundWrongKind)
16334       Diag(TypeTagExpr->getExprLoc(),
16335            diag::warn_type_tag_for_datatype_wrong_kind)
16336         << TypeTagExpr->getSourceRange();
16337     return;
16338   }
16339 
16340   // Retrieve the argument representing the 'arg_idx'.
16341   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16342   if (ArgumentIdxAST >= ExprArgs.size()) {
16343     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16344         << 1 << Attr->getArgumentIdx().getSourceIndex();
16345     return;
16346   }
16347   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16348   if (IsPointerAttr) {
16349     // Skip implicit cast of pointer to `void *' (as a function argument).
16350     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16351       if (ICE->getType()->isVoidPointerType() &&
16352           ICE->getCastKind() == CK_BitCast)
16353         ArgumentExpr = ICE->getSubExpr();
16354   }
16355   QualType ArgumentType = ArgumentExpr->getType();
16356 
16357   // Passing a `void*' pointer shouldn't trigger a warning.
16358   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16359     return;
16360 
16361   if (TypeInfo.MustBeNull) {
16362     // Type tag with matching void type requires a null pointer.
16363     if (!ArgumentExpr->isNullPointerConstant(Context,
16364                                              Expr::NPC_ValueDependentIsNotNull)) {
16365       Diag(ArgumentExpr->getExprLoc(),
16366            diag::warn_type_safety_null_pointer_required)
16367           << ArgumentKind->getName()
16368           << ArgumentExpr->getSourceRange()
16369           << TypeTagExpr->getSourceRange();
16370     }
16371     return;
16372   }
16373 
16374   QualType RequiredType = TypeInfo.Type;
16375   if (IsPointerAttr)
16376     RequiredType = Context.getPointerType(RequiredType);
16377 
16378   bool mismatch = false;
16379   if (!TypeInfo.LayoutCompatible) {
16380     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16381 
16382     // C++11 [basic.fundamental] p1:
16383     // Plain char, signed char, and unsigned char are three distinct types.
16384     //
16385     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16386     // char' depending on the current char signedness mode.
16387     if (mismatch)
16388       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16389                                            RequiredType->getPointeeType())) ||
16390           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16391         mismatch = false;
16392   } else
16393     if (IsPointerAttr)
16394       mismatch = !isLayoutCompatible(Context,
16395                                      ArgumentType->getPointeeType(),
16396                                      RequiredType->getPointeeType());
16397     else
16398       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16399 
16400   if (mismatch)
16401     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16402         << ArgumentType << ArgumentKind
16403         << TypeInfo.LayoutCompatible << RequiredType
16404         << ArgumentExpr->getSourceRange()
16405         << TypeTagExpr->getSourceRange();
16406 }
16407 
16408 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16409                                          CharUnits Alignment) {
16410   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16411 }
16412 
16413 void Sema::DiagnoseMisalignedMembers() {
16414   for (MisalignedMember &m : MisalignedMembers) {
16415     const NamedDecl *ND = m.RD;
16416     if (ND->getName().empty()) {
16417       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16418         ND = TD;
16419     }
16420     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16421         << m.MD << ND << m.E->getSourceRange();
16422   }
16423   MisalignedMembers.clear();
16424 }
16425 
16426 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16427   E = E->IgnoreParens();
16428   if (!T->isPointerType() && !T->isIntegerType())
16429     return;
16430   if (isa<UnaryOperator>(E) &&
16431       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16432     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16433     if (isa<MemberExpr>(Op)) {
16434       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16435       if (MA != MisalignedMembers.end() &&
16436           (T->isIntegerType() ||
16437            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16438                                    Context.getTypeAlignInChars(
16439                                        T->getPointeeType()) <= MA->Alignment))))
16440         MisalignedMembers.erase(MA);
16441     }
16442   }
16443 }
16444 
16445 void Sema::RefersToMemberWithReducedAlignment(
16446     Expr *E,
16447     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16448         Action) {
16449   const auto *ME = dyn_cast<MemberExpr>(E);
16450   if (!ME)
16451     return;
16452 
16453   // No need to check expressions with an __unaligned-qualified type.
16454   if (E->getType().getQualifiers().hasUnaligned())
16455     return;
16456 
16457   // For a chain of MemberExpr like "a.b.c.d" this list
16458   // will keep FieldDecl's like [d, c, b].
16459   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16460   const MemberExpr *TopME = nullptr;
16461   bool AnyIsPacked = false;
16462   do {
16463     QualType BaseType = ME->getBase()->getType();
16464     if (BaseType->isDependentType())
16465       return;
16466     if (ME->isArrow())
16467       BaseType = BaseType->getPointeeType();
16468     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16469     if (RD->isInvalidDecl())
16470       return;
16471 
16472     ValueDecl *MD = ME->getMemberDecl();
16473     auto *FD = dyn_cast<FieldDecl>(MD);
16474     // We do not care about non-data members.
16475     if (!FD || FD->isInvalidDecl())
16476       return;
16477 
16478     AnyIsPacked =
16479         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16480     ReverseMemberChain.push_back(FD);
16481 
16482     TopME = ME;
16483     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16484   } while (ME);
16485   assert(TopME && "We did not compute a topmost MemberExpr!");
16486 
16487   // Not the scope of this diagnostic.
16488   if (!AnyIsPacked)
16489     return;
16490 
16491   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16492   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16493   // TODO: The innermost base of the member expression may be too complicated.
16494   // For now, just disregard these cases. This is left for future
16495   // improvement.
16496   if (!DRE && !isa<CXXThisExpr>(TopBase))
16497       return;
16498 
16499   // Alignment expected by the whole expression.
16500   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16501 
16502   // No need to do anything else with this case.
16503   if (ExpectedAlignment.isOne())
16504     return;
16505 
16506   // Synthesize offset of the whole access.
16507   CharUnits Offset;
16508   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16509        I++) {
16510     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16511   }
16512 
16513   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16514   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16515       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16516 
16517   // The base expression of the innermost MemberExpr may give
16518   // stronger guarantees than the class containing the member.
16519   if (DRE && !TopME->isArrow()) {
16520     const ValueDecl *VD = DRE->getDecl();
16521     if (!VD->getType()->isReferenceType())
16522       CompleteObjectAlignment =
16523           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16524   }
16525 
16526   // Check if the synthesized offset fulfills the alignment.
16527   if (Offset % ExpectedAlignment != 0 ||
16528       // It may fulfill the offset it but the effective alignment may still be
16529       // lower than the expected expression alignment.
16530       CompleteObjectAlignment < ExpectedAlignment) {
16531     // If this happens, we want to determine a sensible culprit of this.
16532     // Intuitively, watching the chain of member expressions from right to
16533     // left, we start with the required alignment (as required by the field
16534     // type) but some packed attribute in that chain has reduced the alignment.
16535     // It may happen that another packed structure increases it again. But if
16536     // we are here such increase has not been enough. So pointing the first
16537     // FieldDecl that either is packed or else its RecordDecl is,
16538     // seems reasonable.
16539     FieldDecl *FD = nullptr;
16540     CharUnits Alignment;
16541     for (FieldDecl *FDI : ReverseMemberChain) {
16542       if (FDI->hasAttr<PackedAttr>() ||
16543           FDI->getParent()->hasAttr<PackedAttr>()) {
16544         FD = FDI;
16545         Alignment = std::min(
16546             Context.getTypeAlignInChars(FD->getType()),
16547             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16548         break;
16549       }
16550     }
16551     assert(FD && "We did not find a packed FieldDecl!");
16552     Action(E, FD->getParent(), FD, Alignment);
16553   }
16554 }
16555 
16556 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16557   using namespace std::placeholders;
16558 
16559   RefersToMemberWithReducedAlignment(
16560       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16561                      _2, _3, _4));
16562 }
16563 
16564 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16565                                             ExprResult CallResult) {
16566   if (checkArgCount(*this, TheCall, 1))
16567     return ExprError();
16568 
16569   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16570   if (MatrixArg.isInvalid())
16571     return MatrixArg;
16572   Expr *Matrix = MatrixArg.get();
16573 
16574   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16575   if (!MType) {
16576     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16577     return ExprError();
16578   }
16579 
16580   // Create returned matrix type by swapping rows and columns of the argument
16581   // matrix type.
16582   QualType ResultType = Context.getConstantMatrixType(
16583       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16584 
16585   // Change the return type to the type of the returned matrix.
16586   TheCall->setType(ResultType);
16587 
16588   // Update call argument to use the possibly converted matrix argument.
16589   TheCall->setArg(0, Matrix);
16590   return CallResult;
16591 }
16592 
16593 // Get and verify the matrix dimensions.
16594 static llvm::Optional<unsigned>
16595 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16596   SourceLocation ErrorPos;
16597   Optional<llvm::APSInt> Value =
16598       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16599   if (!Value) {
16600     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16601         << Name;
16602     return {};
16603   }
16604   uint64_t Dim = Value->getZExtValue();
16605   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16606     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16607         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16608     return {};
16609   }
16610   return Dim;
16611 }
16612 
16613 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16614                                                   ExprResult CallResult) {
16615   if (!getLangOpts().MatrixTypes) {
16616     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16617     return ExprError();
16618   }
16619 
16620   if (checkArgCount(*this, TheCall, 4))
16621     return ExprError();
16622 
16623   unsigned PtrArgIdx = 0;
16624   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16625   Expr *RowsExpr = TheCall->getArg(1);
16626   Expr *ColumnsExpr = TheCall->getArg(2);
16627   Expr *StrideExpr = TheCall->getArg(3);
16628 
16629   bool ArgError = false;
16630 
16631   // Check pointer argument.
16632   {
16633     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16634     if (PtrConv.isInvalid())
16635       return PtrConv;
16636     PtrExpr = PtrConv.get();
16637     TheCall->setArg(0, PtrExpr);
16638     if (PtrExpr->isTypeDependent()) {
16639       TheCall->setType(Context.DependentTy);
16640       return TheCall;
16641     }
16642   }
16643 
16644   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16645   QualType ElementTy;
16646   if (!PtrTy) {
16647     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16648         << PtrArgIdx + 1;
16649     ArgError = true;
16650   } else {
16651     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16652 
16653     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16654       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16655           << PtrArgIdx + 1;
16656       ArgError = true;
16657     }
16658   }
16659 
16660   // Apply default Lvalue conversions and convert the expression to size_t.
16661   auto ApplyArgumentConversions = [this](Expr *E) {
16662     ExprResult Conv = DefaultLvalueConversion(E);
16663     if (Conv.isInvalid())
16664       return Conv;
16665 
16666     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16667   };
16668 
16669   // Apply conversion to row and column expressions.
16670   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16671   if (!RowsConv.isInvalid()) {
16672     RowsExpr = RowsConv.get();
16673     TheCall->setArg(1, RowsExpr);
16674   } else
16675     RowsExpr = nullptr;
16676 
16677   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16678   if (!ColumnsConv.isInvalid()) {
16679     ColumnsExpr = ColumnsConv.get();
16680     TheCall->setArg(2, ColumnsExpr);
16681   } else
16682     ColumnsExpr = nullptr;
16683 
16684   // If any any part of the result matrix type is still pending, just use
16685   // Context.DependentTy, until all parts are resolved.
16686   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16687       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16688     TheCall->setType(Context.DependentTy);
16689     return CallResult;
16690   }
16691 
16692   // Check row and column dimensions.
16693   llvm::Optional<unsigned> MaybeRows;
16694   if (RowsExpr)
16695     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16696 
16697   llvm::Optional<unsigned> MaybeColumns;
16698   if (ColumnsExpr)
16699     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16700 
16701   // Check stride argument.
16702   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16703   if (StrideConv.isInvalid())
16704     return ExprError();
16705   StrideExpr = StrideConv.get();
16706   TheCall->setArg(3, StrideExpr);
16707 
16708   if (MaybeRows) {
16709     if (Optional<llvm::APSInt> Value =
16710             StrideExpr->getIntegerConstantExpr(Context)) {
16711       uint64_t Stride = Value->getZExtValue();
16712       if (Stride < *MaybeRows) {
16713         Diag(StrideExpr->getBeginLoc(),
16714              diag::err_builtin_matrix_stride_too_small);
16715         ArgError = true;
16716       }
16717     }
16718   }
16719 
16720   if (ArgError || !MaybeRows || !MaybeColumns)
16721     return ExprError();
16722 
16723   TheCall->setType(
16724       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16725   return CallResult;
16726 }
16727 
16728 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16729                                                    ExprResult CallResult) {
16730   if (checkArgCount(*this, TheCall, 3))
16731     return ExprError();
16732 
16733   unsigned PtrArgIdx = 1;
16734   Expr *MatrixExpr = TheCall->getArg(0);
16735   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16736   Expr *StrideExpr = TheCall->getArg(2);
16737 
16738   bool ArgError = false;
16739 
16740   {
16741     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16742     if (MatrixConv.isInvalid())
16743       return MatrixConv;
16744     MatrixExpr = MatrixConv.get();
16745     TheCall->setArg(0, MatrixExpr);
16746   }
16747   if (MatrixExpr->isTypeDependent()) {
16748     TheCall->setType(Context.DependentTy);
16749     return TheCall;
16750   }
16751 
16752   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16753   if (!MatrixTy) {
16754     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16755     ArgError = true;
16756   }
16757 
16758   {
16759     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16760     if (PtrConv.isInvalid())
16761       return PtrConv;
16762     PtrExpr = PtrConv.get();
16763     TheCall->setArg(1, PtrExpr);
16764     if (PtrExpr->isTypeDependent()) {
16765       TheCall->setType(Context.DependentTy);
16766       return TheCall;
16767     }
16768   }
16769 
16770   // Check pointer argument.
16771   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16772   if (!PtrTy) {
16773     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16774         << PtrArgIdx + 1;
16775     ArgError = true;
16776   } else {
16777     QualType ElementTy = PtrTy->getPointeeType();
16778     if (ElementTy.isConstQualified()) {
16779       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16780       ArgError = true;
16781     }
16782     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16783     if (MatrixTy &&
16784         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16785       Diag(PtrExpr->getBeginLoc(),
16786            diag::err_builtin_matrix_pointer_arg_mismatch)
16787           << ElementTy << MatrixTy->getElementType();
16788       ArgError = true;
16789     }
16790   }
16791 
16792   // Apply default Lvalue conversions and convert the stride expression to
16793   // size_t.
16794   {
16795     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16796     if (StrideConv.isInvalid())
16797       return StrideConv;
16798 
16799     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16800     if (StrideConv.isInvalid())
16801       return StrideConv;
16802     StrideExpr = StrideConv.get();
16803     TheCall->setArg(2, StrideExpr);
16804   }
16805 
16806   // Check stride argument.
16807   if (MatrixTy) {
16808     if (Optional<llvm::APSInt> Value =
16809             StrideExpr->getIntegerConstantExpr(Context)) {
16810       uint64_t Stride = Value->getZExtValue();
16811       if (Stride < MatrixTy->getNumRows()) {
16812         Diag(StrideExpr->getBeginLoc(),
16813              diag::err_builtin_matrix_stride_too_small);
16814         ArgError = true;
16815       }
16816     }
16817   }
16818 
16819   if (ArgError)
16820     return ExprError();
16821 
16822   return CallResult;
16823 }
16824 
16825 /// \brief Enforce the bounds of a TCB
16826 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16827 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16828 /// and enforce_tcb_leaf attributes.
16829 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16830                                const FunctionDecl *Callee) {
16831   const FunctionDecl *Caller = getCurFunctionDecl();
16832 
16833   // Calls to builtins are not enforced.
16834   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16835       Callee->getBuiltinID() != 0)
16836     return;
16837 
16838   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16839   // all TCBs the callee is a part of.
16840   llvm::StringSet<> CalleeTCBs;
16841   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16842            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16843   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16844            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16845 
16846   // Go through the TCBs the caller is a part of and emit warnings if Caller
16847   // is in a TCB that the Callee is not.
16848   for_each(
16849       Caller->specific_attrs<EnforceTCBAttr>(),
16850       [&](const auto *A) {
16851         StringRef CallerTCB = A->getTCBName();
16852         if (CalleeTCBs.count(CallerTCB) == 0) {
16853           this->Diag(TheCall->getExprLoc(),
16854                      diag::warn_tcb_enforcement_violation) << Callee
16855                                                            << CallerTCB;
16856         }
16857       });
16858 }
16859