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 unlikley that the user wrote the __builtin explicitly.
777   if (IsChkVariant) {
778     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780   } else if (FunctionName.startswith("__builtin_")) {
781     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782   }
783 
784   SmallString<16> DestinationStr;
785   SmallString<16> SourceStr;
786   DestinationSize->toString(DestinationStr, /*Radix=*/10);
787   SourceSize->toString(SourceStr, /*Radix=*/10);
788   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
789                       PDiag(DiagID)
790                           << FunctionName << DestinationStr << SourceStr);
791 }
792 
793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
794                                      Scope::ScopeFlags NeededScopeFlags,
795                                      unsigned DiagID) {
796   // Scopes aren't available during instantiation. Fortunately, builtin
797   // functions cannot be template args so they cannot be formed through template
798   // instantiation. Therefore checking once during the parse is sufficient.
799   if (SemaRef.inTemplateInstantiation())
800     return false;
801 
802   Scope *S = SemaRef.getCurScope();
803   while (S && !S->isSEHExceptScope())
804     S = S->getParent();
805   if (!S || !(S->getFlags() & NeededScopeFlags)) {
806     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
807     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
808         << DRE->getDecl()->getIdentifier();
809     return true;
810   }
811 
812   return false;
813 }
814 
815 static inline bool isBlockPointer(Expr *Arg) {
816   return Arg->getType()->isBlockPointerType();
817 }
818 
819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
820 /// void*, which is a requirement of device side enqueue.
821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
822   const BlockPointerType *BPT =
823       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
824   ArrayRef<QualType> Params =
825       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
826   unsigned ArgCounter = 0;
827   bool IllegalParams = false;
828   // Iterate through the block parameters until either one is found that is not
829   // a local void*, or the block is valid.
830   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
831        I != E; ++I, ++ArgCounter) {
832     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
833         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
834             LangAS::opencl_local) {
835       // Get the location of the error. If a block literal has been passed
836       // (BlockExpr) then we can point straight to the offending argument,
837       // else we just point to the variable reference.
838       SourceLocation ErrorLoc;
839       if (isa<BlockExpr>(BlockArg)) {
840         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
841         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
842       } else if (isa<DeclRefExpr>(BlockArg)) {
843         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
844       }
845       S.Diag(ErrorLoc,
846              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
847       IllegalParams = true;
848     }
849   }
850 
851   return IllegalParams;
852 }
853 
854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
855   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
856     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
857         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
858     return true;
859   }
860   return false;
861 }
862 
863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
864   if (checkArgCount(S, TheCall, 2))
865     return true;
866 
867   if (checkOpenCLSubgroupExt(S, TheCall))
868     return true;
869 
870   // First argument is an ndrange_t type.
871   Expr *NDRangeArg = TheCall->getArg(0);
872   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
873     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
874         << TheCall->getDirectCallee() << "'ndrange_t'";
875     return true;
876   }
877 
878   Expr *BlockArg = TheCall->getArg(1);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
888 /// get_kernel_work_group_size
889 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
891   if (checkArgCount(S, TheCall, 1))
892     return true;
893 
894   Expr *BlockArg = TheCall->getArg(0);
895   if (!isBlockPointer(BlockArg)) {
896     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
897         << TheCall->getDirectCallee() << "block";
898     return true;
899   }
900   return checkOpenCLBlockArgs(S, BlockArg);
901 }
902 
903 /// Diagnose integer type and any valid implicit conversion to it.
904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
905                                       const QualType &IntType);
906 
907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
908                                             unsigned Start, unsigned End) {
909   bool IllegalParams = false;
910   for (unsigned I = Start; I <= End; ++I)
911     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
912                                               S.Context.getSizeType());
913   return IllegalParams;
914 }
915 
916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
917 /// 'local void*' parameter of passed block.
918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
919                                            Expr *BlockArg,
920                                            unsigned NumNonVarArgs) {
921   const BlockPointerType *BPT =
922       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
923   unsigned NumBlockParams =
924       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
925   unsigned TotalNumArgs = TheCall->getNumArgs();
926 
927   // For each argument passed to the block, a corresponding uint needs to
928   // be passed to describe the size of the local memory.
929   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
930     S.Diag(TheCall->getBeginLoc(),
931            diag::err_opencl_enqueue_kernel_local_size_args);
932     return true;
933   }
934 
935   // Check that the sizes of the local memory are specified by integers.
936   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
937                                          TotalNumArgs - 1);
938 }
939 
940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
941 /// overload formats specified in Table 6.13.17.1.
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    void (^block)(void))
946 /// int enqueue_kernel(queue_t queue,
947 ///                    kernel_enqueue_flags_t flags,
948 ///                    const ndrange_t ndrange,
949 ///                    uint num_events_in_wait_list,
950 ///                    clk_event_t *event_wait_list,
951 ///                    clk_event_t *event_ret,
952 ///                    void (^block)(void))
953 /// int enqueue_kernel(queue_t queue,
954 ///                    kernel_enqueue_flags_t flags,
955 ///                    const ndrange_t ndrange,
956 ///                    void (^block)(local void*, ...),
957 ///                    uint size0, ...)
958 /// int enqueue_kernel(queue_t queue,
959 ///                    kernel_enqueue_flags_t flags,
960 ///                    const ndrange_t ndrange,
961 ///                    uint num_events_in_wait_list,
962 ///                    clk_event_t *event_wait_list,
963 ///                    clk_event_t *event_ret,
964 ///                    void (^block)(local void*, ...),
965 ///                    uint size0, ...)
966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
967   unsigned NumArgs = TheCall->getNumArgs();
968 
969   if (NumArgs < 4) {
970     S.Diag(TheCall->getBeginLoc(),
971            diag::err_typecheck_call_too_few_args_at_least)
972         << 0 << 4 << NumArgs;
973     return true;
974   }
975 
976   Expr *Arg0 = TheCall->getArg(0);
977   Expr *Arg1 = TheCall->getArg(1);
978   Expr *Arg2 = TheCall->getArg(2);
979   Expr *Arg3 = TheCall->getArg(3);
980 
981   // First argument always needs to be a queue_t type.
982   if (!Arg0->getType()->isQueueT()) {
983     S.Diag(TheCall->getArg(0)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
986     return true;
987   }
988 
989   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
990   if (!Arg1->getType()->isIntegerType()) {
991     S.Diag(TheCall->getArg(1)->getBeginLoc(),
992            diag::err_opencl_builtin_expected_type)
993         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
994     return true;
995   }
996 
997   // Third argument is always an ndrange_t type.
998   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
999     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1000            diag::err_opencl_builtin_expected_type)
1001         << TheCall->getDirectCallee() << "'ndrange_t'";
1002     return true;
1003   }
1004 
1005   // With four arguments, there is only one form that the function could be
1006   // called in: no events and no variable arguments.
1007   if (NumArgs == 4) {
1008     // check that the last argument is the right block type.
1009     if (!isBlockPointer(Arg3)) {
1010       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1011           << TheCall->getDirectCallee() << "block";
1012       return true;
1013     }
1014     // we have a block type, check the prototype
1015     const BlockPointerType *BPT =
1016         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1017     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1018       S.Diag(Arg3->getBeginLoc(),
1019              diag::err_opencl_enqueue_kernel_blocks_no_args);
1020       return true;
1021     }
1022     return false;
1023   }
1024   // we can have block + varargs.
1025   if (isBlockPointer(Arg3))
1026     return (checkOpenCLBlockArgs(S, Arg3) ||
1027             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1028   // last two cases with either exactly 7 args or 7 args and varargs.
1029   if (NumArgs >= 7) {
1030     // check common block argument.
1031     Expr *Arg6 = TheCall->getArg(6);
1032     if (!isBlockPointer(Arg6)) {
1033       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1034           << TheCall->getDirectCallee() << "block";
1035       return true;
1036     }
1037     if (checkOpenCLBlockArgs(S, Arg6))
1038       return true;
1039 
1040     // Forth argument has to be any integer type.
1041     if (!Arg3->getType()->isIntegerType()) {
1042       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee() << "integer";
1045       return true;
1046     }
1047     // check remaining common arguments.
1048     Expr *Arg4 = TheCall->getArg(4);
1049     Expr *Arg5 = TheCall->getArg(5);
1050 
1051     // Fifth argument is always passed as a pointer to clk_event_t.
1052     if (!Arg4->isNullPointerConstant(S.Context,
1053                                      Expr::NPC_ValueDependentIsNotNull) &&
1054         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1055       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1056              diag::err_opencl_builtin_expected_type)
1057           << TheCall->getDirectCallee()
1058           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1059       return true;
1060     }
1061 
1062     // Sixth argument is always passed as a pointer to clk_event_t.
1063     if (!Arg5->isNullPointerConstant(S.Context,
1064                                      Expr::NPC_ValueDependentIsNotNull) &&
1065         !(Arg5->getType()->isPointerType() &&
1066           Arg5->getType()->getPointeeType()->isClkEventT())) {
1067       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1068              diag::err_opencl_builtin_expected_type)
1069           << TheCall->getDirectCallee()
1070           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1071       return true;
1072     }
1073 
1074     if (NumArgs == 7)
1075       return false;
1076 
1077     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1078   }
1079 
1080   // None of the specific case has been detected, give generic error
1081   S.Diag(TheCall->getBeginLoc(),
1082          diag::err_opencl_enqueue_kernel_incorrect_args);
1083   return true;
1084 }
1085 
1086 /// Returns OpenCL access qual.
1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1088     return D->getAttr<OpenCLAccessAttr>();
1089 }
1090 
1091 /// Returns true if pipe element type is different from the pointer.
1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1093   const Expr *Arg0 = Call->getArg(0);
1094   // First argument type should always be pipe.
1095   if (!Arg0->getType()->isPipeType()) {
1096     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1097         << Call->getDirectCallee() << Arg0->getSourceRange();
1098     return true;
1099   }
1100   OpenCLAccessAttr *AccessQual =
1101       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1102   // Validates the access qualifier is compatible with the call.
1103   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1104   // read_only and write_only, and assumed to be read_only if no qualifier is
1105   // specified.
1106   switch (Call->getDirectCallee()->getBuiltinID()) {
1107   case Builtin::BIread_pipe:
1108   case Builtin::BIreserve_read_pipe:
1109   case Builtin::BIcommit_read_pipe:
1110   case Builtin::BIwork_group_reserve_read_pipe:
1111   case Builtin::BIsub_group_reserve_read_pipe:
1112   case Builtin::BIwork_group_commit_read_pipe:
1113   case Builtin::BIsub_group_commit_read_pipe:
1114     if (!(!AccessQual || AccessQual->isReadOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "read_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   case Builtin::BIwrite_pipe:
1122   case Builtin::BIreserve_write_pipe:
1123   case Builtin::BIcommit_write_pipe:
1124   case Builtin::BIwork_group_reserve_write_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126   case Builtin::BIwork_group_commit_write_pipe:
1127   case Builtin::BIsub_group_commit_write_pipe:
1128     if (!(AccessQual && AccessQual->isWriteOnly())) {
1129       S.Diag(Arg0->getBeginLoc(),
1130              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1131           << "write_only" << Arg0->getSourceRange();
1132       return true;
1133     }
1134     break;
1135   default:
1136     break;
1137   }
1138   return false;
1139 }
1140 
1141 /// Returns true if pipe element type is different from the pointer.
1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1143   const Expr *Arg0 = Call->getArg(0);
1144   const Expr *ArgIdx = Call->getArg(Idx);
1145   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1146   const QualType EltTy = PipeTy->getElementType();
1147   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1148   // The Idx argument should be a pointer and the type of the pointer and
1149   // the type of pipe element should also be the same.
1150   if (!ArgTy ||
1151       !S.Context.hasSameType(
1152           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1153     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1154         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1155         << ArgIdx->getType() << ArgIdx->getSourceRange();
1156     return true;
1157   }
1158   return false;
1159 }
1160 
1161 // Performs semantic analysis for the read/write_pipe call.
1162 // \param S Reference to the semantic analyzer.
1163 // \param Call A pointer to the builtin call.
1164 // \return True if a semantic error has been found, false otherwise.
1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1166   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1167   // functions have two forms.
1168   switch (Call->getNumArgs()) {
1169   case 2:
1170     if (checkOpenCLPipeArg(S, Call))
1171       return true;
1172     // The call with 2 arguments should be
1173     // read/write_pipe(pipe T, T*).
1174     // Check packet type T.
1175     if (checkOpenCLPipePacketType(S, Call, 1))
1176       return true;
1177     break;
1178 
1179   case 4: {
1180     if (checkOpenCLPipeArg(S, Call))
1181       return true;
1182     // The call with 4 arguments should be
1183     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1184     // Check reserve_id_t.
1185     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1186       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1187           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1188           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1189       return true;
1190     }
1191 
1192     // Check the index.
1193     const Expr *Arg2 = Call->getArg(2);
1194     if (!Arg2->getType()->isIntegerType() &&
1195         !Arg2->getType()->isUnsignedIntegerType()) {
1196       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1197           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1198           << Arg2->getType() << Arg2->getSourceRange();
1199       return true;
1200     }
1201 
1202     // Check packet type T.
1203     if (checkOpenCLPipePacketType(S, Call, 3))
1204       return true;
1205   } break;
1206   default:
1207     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1208         << Call->getDirectCallee() << Call->getSourceRange();
1209     return true;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on the {work_group_/sub_group_
1216 //        /_}reserve_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check the reserve size.
1228   if (!Call->getArg(1)->getType()->isIntegerType() &&
1229       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1230     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1231         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1232         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1233     return true;
1234   }
1235 
1236   // Since return type of reserve_read/write_pipe built-in function is
1237   // reserve_id_t, which is not defined in the builtin def file , we used int
1238   // as return type and need to override the return type of these functions.
1239   Call->setType(S.Context.OCLReserveIDTy);
1240 
1241   return false;
1242 }
1243 
1244 // Performs a semantic analysis on {work_group_/sub_group_
1245 //        /_}commit_{read/write}_pipe
1246 // \param S Reference to the semantic analyzer.
1247 // \param Call The call to the builtin function to be analyzed.
1248 // \return True if a semantic error was found, false otherwise.
1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1250   if (checkArgCount(S, Call, 2))
1251     return true;
1252 
1253   if (checkOpenCLPipeArg(S, Call))
1254     return true;
1255 
1256   // Check reserve_id_t.
1257   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1258     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1259         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1260         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 // Performs a semantic analysis on the call to built-in Pipe
1268 //        Query Functions.
1269 // \param S Reference to the semantic analyzer.
1270 // \param Call The call to the builtin function to be analyzed.
1271 // \return True if a semantic error was found, false otherwise.
1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1273   if (checkArgCount(S, Call, 1))
1274     return true;
1275 
1276   if (!Call->getArg(0)->getType()->isPipeType()) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1278         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1279     return true;
1280   }
1281 
1282   return false;
1283 }
1284 
1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1286 // Performs semantic analysis for the to_global/local/private call.
1287 // \param S Reference to the semantic analyzer.
1288 // \param BuiltinID ID of the builtin function.
1289 // \param Call A pointer to the builtin call.
1290 // \return True if a semantic error has been found, false otherwise.
1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1292                                     CallExpr *Call) {
1293   if (checkArgCount(S, Call, 1))
1294     return true;
1295 
1296   auto RT = Call->getArg(0)->getType();
1297   if (!RT->isPointerType() || RT->getPointeeType()
1298       .getAddressSpace() == LangAS::opencl_constant) {
1299     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1300         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1301     return true;
1302   }
1303 
1304   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1305     S.Diag(Call->getArg(0)->getBeginLoc(),
1306            diag::warn_opencl_generic_address_space_arg)
1307         << Call->getDirectCallee()->getNameInfo().getAsString()
1308         << Call->getArg(0)->getSourceRange();
1309   }
1310 
1311   RT = RT->getPointeeType();
1312   auto Qual = RT.getQualifiers();
1313   switch (BuiltinID) {
1314   case Builtin::BIto_global:
1315     Qual.setAddressSpace(LangAS::opencl_global);
1316     break;
1317   case Builtin::BIto_local:
1318     Qual.setAddressSpace(LangAS::opencl_local);
1319     break;
1320   case Builtin::BIto_private:
1321     Qual.setAddressSpace(LangAS::opencl_private);
1322     break;
1323   default:
1324     llvm_unreachable("Invalid builtin function");
1325   }
1326   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1327       RT.getUnqualifiedType(), Qual)));
1328 
1329   return false;
1330 }
1331 
1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1333   if (checkArgCount(S, TheCall, 1))
1334     return ExprError();
1335 
1336   // Compute __builtin_launder's parameter type from the argument.
1337   // The parameter type is:
1338   //  * The type of the argument if it's not an array or function type,
1339   //  Otherwise,
1340   //  * The decayed argument type.
1341   QualType ParamTy = [&]() {
1342     QualType ArgTy = TheCall->getArg(0)->getType();
1343     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1344       return S.Context.getPointerType(Ty->getElementType());
1345     if (ArgTy->isFunctionType()) {
1346       return S.Context.getPointerType(ArgTy);
1347     }
1348     return ArgTy;
1349   }();
1350 
1351   TheCall->setType(ParamTy);
1352 
1353   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1354     if (!ParamTy->isPointerType())
1355       return 0;
1356     if (ParamTy->isFunctionPointerType())
1357       return 1;
1358     if (ParamTy->isVoidPointerType())
1359       return 2;
1360     return llvm::Optional<unsigned>{};
1361   }();
1362   if (DiagSelect.hasValue()) {
1363     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1364         << DiagSelect.getValue() << TheCall->getSourceRange();
1365     return ExprError();
1366   }
1367 
1368   // We either have an incomplete class type, or we have a class template
1369   // whose instantiation has not been forced. Example:
1370   //
1371   //   template <class T> struct Foo { T value; };
1372   //   Foo<int> *p = nullptr;
1373   //   auto *d = __builtin_launder(p);
1374   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1375                             diag::err_incomplete_type))
1376     return ExprError();
1377 
1378   assert(ParamTy->getPointeeType()->isObjectType() &&
1379          "Unhandled non-object pointer case");
1380 
1381   InitializedEntity Entity =
1382       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1383   ExprResult Arg =
1384       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1385   if (Arg.isInvalid())
1386     return ExprError();
1387   TheCall->setArg(0, Arg.get());
1388 
1389   return TheCall;
1390 }
1391 
1392 // Emit an error and return true if the current architecture is not in the list
1393 // of supported architectures.
1394 static bool
1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1396                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1397   llvm::Triple::ArchType CurArch =
1398       S.getASTContext().getTargetInfo().getTriple().getArch();
1399   if (llvm::is_contained(SupportedArchs, CurArch))
1400     return false;
1401   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1402       << TheCall->getSourceRange();
1403   return true;
1404 }
1405 
1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1407                                  SourceLocation CallSiteLoc);
1408 
1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1410                                       CallExpr *TheCall) {
1411   switch (TI.getTriple().getArch()) {
1412   default:
1413     // Some builtins don't require additional checking, so just consider these
1414     // acceptable.
1415     return false;
1416   case llvm::Triple::arm:
1417   case llvm::Triple::armeb:
1418   case llvm::Triple::thumb:
1419   case llvm::Triple::thumbeb:
1420     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::aarch64:
1422   case llvm::Triple::aarch64_32:
1423   case llvm::Triple::aarch64_be:
1424     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::bpfeb:
1426   case llvm::Triple::bpfel:
1427     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1428   case llvm::Triple::hexagon:
1429     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1430   case llvm::Triple::mips:
1431   case llvm::Triple::mipsel:
1432   case llvm::Triple::mips64:
1433   case llvm::Triple::mips64el:
1434     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   case llvm::Triple::systemz:
1436     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1437   case llvm::Triple::x86:
1438   case llvm::Triple::x86_64:
1439     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1440   case llvm::Triple::ppc:
1441   case llvm::Triple::ppcle:
1442   case llvm::Triple::ppc64:
1443   case llvm::Triple::ppc64le:
1444     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1445   case llvm::Triple::amdgcn:
1446     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1447   case llvm::Triple::riscv32:
1448   case llvm::Triple::riscv64:
1449     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1450   }
1451 }
1452 
1453 ExprResult
1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1455                                CallExpr *TheCall) {
1456   ExprResult TheCallResult(TheCall);
1457 
1458   // Find out if any arguments are required to be integer constant expressions.
1459   unsigned ICEArguments = 0;
1460   ASTContext::GetBuiltinTypeError Error;
1461   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1462   if (Error != ASTContext::GE_None)
1463     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1464 
1465   // If any arguments are required to be ICE's, check and diagnose.
1466   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1467     // Skip arguments not required to be ICE's.
1468     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1469 
1470     llvm::APSInt Result;
1471     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1472       return true;
1473     ICEArguments &= ~(1 << ArgNo);
1474   }
1475 
1476   switch (BuiltinID) {
1477   case Builtin::BI__builtin___CFStringMakeConstantString:
1478     assert(TheCall->getNumArgs() == 1 &&
1479            "Wrong # arguments to builtin CFStringMakeConstantString");
1480     if (CheckObjCString(TheCall->getArg(0)))
1481       return ExprError();
1482     break;
1483   case Builtin::BI__builtin_ms_va_start:
1484   case Builtin::BI__builtin_stdarg_start:
1485   case Builtin::BI__builtin_va_start:
1486     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BI__va_start: {
1490     switch (Context.getTargetInfo().getTriple().getArch()) {
1491     case llvm::Triple::aarch64:
1492     case llvm::Triple::arm:
1493     case llvm::Triple::thumb:
1494       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1495         return ExprError();
1496       break;
1497     default:
1498       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1499         return ExprError();
1500       break;
1501     }
1502     break;
1503   }
1504 
1505   // The acquire, release, and no fence variants are ARM and AArch64 only.
1506   case Builtin::BI_interlockedbittestandset_acq:
1507   case Builtin::BI_interlockedbittestandset_rel:
1508   case Builtin::BI_interlockedbittestandset_nf:
1509   case Builtin::BI_interlockedbittestandreset_acq:
1510   case Builtin::BI_interlockedbittestandreset_rel:
1511   case Builtin::BI_interlockedbittestandreset_nf:
1512     if (CheckBuiltinTargetSupport(
1513             *this, BuiltinID, TheCall,
1514             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1519   case Builtin::BI_bittest64:
1520   case Builtin::BI_bittestandcomplement64:
1521   case Builtin::BI_bittestandreset64:
1522   case Builtin::BI_bittestandset64:
1523   case Builtin::BI_interlockedbittestandreset64:
1524   case Builtin::BI_interlockedbittestandset64:
1525     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1526                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1527                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1528       return ExprError();
1529     break;
1530 
1531   case Builtin::BI__builtin_isgreater:
1532   case Builtin::BI__builtin_isgreaterequal:
1533   case Builtin::BI__builtin_isless:
1534   case Builtin::BI__builtin_islessequal:
1535   case Builtin::BI__builtin_islessgreater:
1536   case Builtin::BI__builtin_isunordered:
1537     if (SemaBuiltinUnorderedCompare(TheCall))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_fpclassify:
1541     if (SemaBuiltinFPClassification(TheCall, 6))
1542       return ExprError();
1543     break;
1544   case Builtin::BI__builtin_isfinite:
1545   case Builtin::BI__builtin_isinf:
1546   case Builtin::BI__builtin_isinf_sign:
1547   case Builtin::BI__builtin_isnan:
1548   case Builtin::BI__builtin_isnormal:
1549   case Builtin::BI__builtin_signbit:
1550   case Builtin::BI__builtin_signbitf:
1551   case Builtin::BI__builtin_signbitl:
1552     if (SemaBuiltinFPClassification(TheCall, 1))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_shufflevector:
1556     return SemaBuiltinShuffleVector(TheCall);
1557     // TheCall will be freed by the smart pointer here, but that's fine, since
1558     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1559   case Builtin::BI__builtin_prefetch:
1560     if (SemaBuiltinPrefetch(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_alloca_with_align:
1564     if (SemaBuiltinAllocaWithAlign(TheCall))
1565       return ExprError();
1566     LLVM_FALLTHROUGH;
1567   case Builtin::BI__builtin_alloca:
1568     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1569         << TheCall->getDirectCallee();
1570     break;
1571   case Builtin::BI__arithmetic_fence:
1572     if (SemaBuiltinArithmeticFence(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__assume:
1576   case Builtin::BI__builtin_assume:
1577     if (SemaBuiltinAssume(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_assume_aligned:
1581     if (SemaBuiltinAssumeAligned(TheCall))
1582       return ExprError();
1583     break;
1584   case Builtin::BI__builtin_dynamic_object_size:
1585   case Builtin::BI__builtin_object_size:
1586     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1587       return ExprError();
1588     break;
1589   case Builtin::BI__builtin_longjmp:
1590     if (SemaBuiltinLongjmp(TheCall))
1591       return ExprError();
1592     break;
1593   case Builtin::BI__builtin_setjmp:
1594     if (SemaBuiltinSetjmp(TheCall))
1595       return ExprError();
1596     break;
1597   case Builtin::BI__builtin_classify_type:
1598     if (checkArgCount(*this, TheCall, 1)) return true;
1599     TheCall->setType(Context.IntTy);
1600     break;
1601   case Builtin::BI__builtin_complex:
1602     if (SemaBuiltinComplex(TheCall))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_constant_p: {
1606     if (checkArgCount(*this, TheCall, 1)) return true;
1607     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1608     if (Arg.isInvalid()) return true;
1609     TheCall->setArg(0, Arg.get());
1610     TheCall->setType(Context.IntTy);
1611     break;
1612   }
1613   case Builtin::BI__builtin_launder:
1614     return SemaBuiltinLaunder(*this, TheCall);
1615   case Builtin::BI__sync_fetch_and_add:
1616   case Builtin::BI__sync_fetch_and_add_1:
1617   case Builtin::BI__sync_fetch_and_add_2:
1618   case Builtin::BI__sync_fetch_and_add_4:
1619   case Builtin::BI__sync_fetch_and_add_8:
1620   case Builtin::BI__sync_fetch_and_add_16:
1621   case Builtin::BI__sync_fetch_and_sub:
1622   case Builtin::BI__sync_fetch_and_sub_1:
1623   case Builtin::BI__sync_fetch_and_sub_2:
1624   case Builtin::BI__sync_fetch_and_sub_4:
1625   case Builtin::BI__sync_fetch_and_sub_8:
1626   case Builtin::BI__sync_fetch_and_sub_16:
1627   case Builtin::BI__sync_fetch_and_or:
1628   case Builtin::BI__sync_fetch_and_or_1:
1629   case Builtin::BI__sync_fetch_and_or_2:
1630   case Builtin::BI__sync_fetch_and_or_4:
1631   case Builtin::BI__sync_fetch_and_or_8:
1632   case Builtin::BI__sync_fetch_and_or_16:
1633   case Builtin::BI__sync_fetch_and_and:
1634   case Builtin::BI__sync_fetch_and_and_1:
1635   case Builtin::BI__sync_fetch_and_and_2:
1636   case Builtin::BI__sync_fetch_and_and_4:
1637   case Builtin::BI__sync_fetch_and_and_8:
1638   case Builtin::BI__sync_fetch_and_and_16:
1639   case Builtin::BI__sync_fetch_and_xor:
1640   case Builtin::BI__sync_fetch_and_xor_1:
1641   case Builtin::BI__sync_fetch_and_xor_2:
1642   case Builtin::BI__sync_fetch_and_xor_4:
1643   case Builtin::BI__sync_fetch_and_xor_8:
1644   case Builtin::BI__sync_fetch_and_xor_16:
1645   case Builtin::BI__sync_fetch_and_nand:
1646   case Builtin::BI__sync_fetch_and_nand_1:
1647   case Builtin::BI__sync_fetch_and_nand_2:
1648   case Builtin::BI__sync_fetch_and_nand_4:
1649   case Builtin::BI__sync_fetch_and_nand_8:
1650   case Builtin::BI__sync_fetch_and_nand_16:
1651   case Builtin::BI__sync_add_and_fetch:
1652   case Builtin::BI__sync_add_and_fetch_1:
1653   case Builtin::BI__sync_add_and_fetch_2:
1654   case Builtin::BI__sync_add_and_fetch_4:
1655   case Builtin::BI__sync_add_and_fetch_8:
1656   case Builtin::BI__sync_add_and_fetch_16:
1657   case Builtin::BI__sync_sub_and_fetch:
1658   case Builtin::BI__sync_sub_and_fetch_1:
1659   case Builtin::BI__sync_sub_and_fetch_2:
1660   case Builtin::BI__sync_sub_and_fetch_4:
1661   case Builtin::BI__sync_sub_and_fetch_8:
1662   case Builtin::BI__sync_sub_and_fetch_16:
1663   case Builtin::BI__sync_and_and_fetch:
1664   case Builtin::BI__sync_and_and_fetch_1:
1665   case Builtin::BI__sync_and_and_fetch_2:
1666   case Builtin::BI__sync_and_and_fetch_4:
1667   case Builtin::BI__sync_and_and_fetch_8:
1668   case Builtin::BI__sync_and_and_fetch_16:
1669   case Builtin::BI__sync_or_and_fetch:
1670   case Builtin::BI__sync_or_and_fetch_1:
1671   case Builtin::BI__sync_or_and_fetch_2:
1672   case Builtin::BI__sync_or_and_fetch_4:
1673   case Builtin::BI__sync_or_and_fetch_8:
1674   case Builtin::BI__sync_or_and_fetch_16:
1675   case Builtin::BI__sync_xor_and_fetch:
1676   case Builtin::BI__sync_xor_and_fetch_1:
1677   case Builtin::BI__sync_xor_and_fetch_2:
1678   case Builtin::BI__sync_xor_and_fetch_4:
1679   case Builtin::BI__sync_xor_and_fetch_8:
1680   case Builtin::BI__sync_xor_and_fetch_16:
1681   case Builtin::BI__sync_nand_and_fetch:
1682   case Builtin::BI__sync_nand_and_fetch_1:
1683   case Builtin::BI__sync_nand_and_fetch_2:
1684   case Builtin::BI__sync_nand_and_fetch_4:
1685   case Builtin::BI__sync_nand_and_fetch_8:
1686   case Builtin::BI__sync_nand_and_fetch_16:
1687   case Builtin::BI__sync_val_compare_and_swap:
1688   case Builtin::BI__sync_val_compare_and_swap_1:
1689   case Builtin::BI__sync_val_compare_and_swap_2:
1690   case Builtin::BI__sync_val_compare_and_swap_4:
1691   case Builtin::BI__sync_val_compare_and_swap_8:
1692   case Builtin::BI__sync_val_compare_and_swap_16:
1693   case Builtin::BI__sync_bool_compare_and_swap:
1694   case Builtin::BI__sync_bool_compare_and_swap_1:
1695   case Builtin::BI__sync_bool_compare_and_swap_2:
1696   case Builtin::BI__sync_bool_compare_and_swap_4:
1697   case Builtin::BI__sync_bool_compare_and_swap_8:
1698   case Builtin::BI__sync_bool_compare_and_swap_16:
1699   case Builtin::BI__sync_lock_test_and_set:
1700   case Builtin::BI__sync_lock_test_and_set_1:
1701   case Builtin::BI__sync_lock_test_and_set_2:
1702   case Builtin::BI__sync_lock_test_and_set_4:
1703   case Builtin::BI__sync_lock_test_and_set_8:
1704   case Builtin::BI__sync_lock_test_and_set_16:
1705   case Builtin::BI__sync_lock_release:
1706   case Builtin::BI__sync_lock_release_1:
1707   case Builtin::BI__sync_lock_release_2:
1708   case Builtin::BI__sync_lock_release_4:
1709   case Builtin::BI__sync_lock_release_8:
1710   case Builtin::BI__sync_lock_release_16:
1711   case Builtin::BI__sync_swap:
1712   case Builtin::BI__sync_swap_1:
1713   case Builtin::BI__sync_swap_2:
1714   case Builtin::BI__sync_swap_4:
1715   case Builtin::BI__sync_swap_8:
1716   case Builtin::BI__sync_swap_16:
1717     return SemaBuiltinAtomicOverloaded(TheCallResult);
1718   case Builtin::BI__sync_synchronize:
1719     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1720         << TheCall->getCallee()->getSourceRange();
1721     break;
1722   case Builtin::BI__builtin_nontemporal_load:
1723   case Builtin::BI__builtin_nontemporal_store:
1724     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1725   case Builtin::BI__builtin_memcpy_inline: {
1726     clang::Expr *SizeOp = TheCall->getArg(2);
1727     // We warn about copying to or from `nullptr` pointers when `size` is
1728     // greater than 0. When `size` is value dependent we cannot evaluate its
1729     // value so we bail out.
1730     if (SizeOp->isValueDependent())
1731       break;
1732     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1733       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1734       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1735     }
1736     break;
1737   }
1738 #define BUILTIN(ID, TYPE, ATTRS)
1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1740   case Builtin::BI##ID: \
1741     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1742 #include "clang/Basic/Builtins.def"
1743   case Builtin::BI__annotation:
1744     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_annotation:
1748     if (SemaBuiltinAnnotation(*this, TheCall))
1749       return ExprError();
1750     break;
1751   case Builtin::BI__builtin_addressof:
1752     if (SemaBuiltinAddressof(*this, TheCall))
1753       return ExprError();
1754     break;
1755   case Builtin::BI__builtin_is_aligned:
1756   case Builtin::BI__builtin_align_up:
1757   case Builtin::BI__builtin_align_down:
1758     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__builtin_add_overflow:
1762   case Builtin::BI__builtin_sub_overflow:
1763   case Builtin::BI__builtin_mul_overflow:
1764     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1765       return ExprError();
1766     break;
1767   case Builtin::BI__builtin_operator_new:
1768   case Builtin::BI__builtin_operator_delete: {
1769     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1770     ExprResult Res =
1771         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1772     if (Res.isInvalid())
1773       CorrectDelayedTyposInExpr(TheCallResult.get());
1774     return Res;
1775   }
1776   case Builtin::BI__builtin_dump_struct: {
1777     // We first want to ensure we are called with 2 arguments
1778     if (checkArgCount(*this, TheCall, 2))
1779       return ExprError();
1780     // Ensure that the first argument is of type 'struct XX *'
1781     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1782     const QualType PtrArgType = PtrArg->getType();
1783     if (!PtrArgType->isPointerType() ||
1784         !PtrArgType->getPointeeType()->isRecordType()) {
1785       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1787           << "structure pointer";
1788       return ExprError();
1789     }
1790 
1791     // Ensure that the second argument is of type 'FunctionType'
1792     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1793     const QualType FnPtrArgType = FnPtrArg->getType();
1794     if (!FnPtrArgType->isPointerType()) {
1795       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1797           << FnPtrArgType << "'int (*)(const char *, ...)'";
1798       return ExprError();
1799     }
1800 
1801     const auto *FuncType =
1802         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1803 
1804     if (!FuncType) {
1805       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1806           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1807           << FnPtrArgType << "'int (*)(const char *, ...)'";
1808       return ExprError();
1809     }
1810 
1811     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1812       if (!FT->getNumParams()) {
1813         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1814             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1815             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1816         return ExprError();
1817       }
1818       QualType PT = FT->getParamType(0);
1819       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1820           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1821           !PT->getPointeeType().isConstQualified()) {
1822         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1823             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1824             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1825         return ExprError();
1826       }
1827     }
1828 
1829     TheCall->setType(Context.IntTy);
1830     break;
1831   }
1832   case Builtin::BI__builtin_expect_with_probability: {
1833     // We first want to ensure we are called with 3 arguments
1834     if (checkArgCount(*this, TheCall, 3))
1835       return ExprError();
1836     // then check probability is constant float in range [0.0, 1.0]
1837     const Expr *ProbArg = TheCall->getArg(2);
1838     SmallVector<PartialDiagnosticAt, 8> Notes;
1839     Expr::EvalResult Eval;
1840     Eval.Diag = &Notes;
1841     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1842         !Eval.Val.isFloat()) {
1843       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1844           << ProbArg->getSourceRange();
1845       for (const PartialDiagnosticAt &PDiag : Notes)
1846         Diag(PDiag.first, PDiag.second);
1847       return ExprError();
1848     }
1849     llvm::APFloat Probability = Eval.Val.getFloat();
1850     bool LoseInfo = false;
1851     Probability.convert(llvm::APFloat::IEEEdouble(),
1852                         llvm::RoundingMode::Dynamic, &LoseInfo);
1853     if (!(Probability >= llvm::APFloat(0.0) &&
1854           Probability <= llvm::APFloat(1.0))) {
1855       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1856           << ProbArg->getSourceRange();
1857       return ExprError();
1858     }
1859     break;
1860   }
1861   case Builtin::BI__builtin_preserve_access_index:
1862     if (SemaBuiltinPreserveAI(*this, TheCall))
1863       return ExprError();
1864     break;
1865   case Builtin::BI__builtin_call_with_static_chain:
1866     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__exception_code:
1870   case Builtin::BI_exception_code:
1871     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1872                                  diag::err_seh___except_block))
1873       return ExprError();
1874     break;
1875   case Builtin::BI__exception_info:
1876   case Builtin::BI_exception_info:
1877     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1878                                  diag::err_seh___except_filter))
1879       return ExprError();
1880     break;
1881   case Builtin::BI__GetExceptionInfo:
1882     if (checkArgCount(*this, TheCall, 1))
1883       return ExprError();
1884 
1885     if (CheckCXXThrowOperand(
1886             TheCall->getBeginLoc(),
1887             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1888             TheCall))
1889       return ExprError();
1890 
1891     TheCall->setType(Context.VoidPtrTy);
1892     break;
1893   // OpenCL v2.0, s6.13.16 - Pipe functions
1894   case Builtin::BIread_pipe:
1895   case Builtin::BIwrite_pipe:
1896     // Since those two functions are declared with var args, we need a semantic
1897     // check for the argument.
1898     if (SemaBuiltinRWPipe(*this, TheCall))
1899       return ExprError();
1900     break;
1901   case Builtin::BIreserve_read_pipe:
1902   case Builtin::BIreserve_write_pipe:
1903   case Builtin::BIwork_group_reserve_read_pipe:
1904   case Builtin::BIwork_group_reserve_write_pipe:
1905     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIsub_group_reserve_read_pipe:
1909   case Builtin::BIsub_group_reserve_write_pipe:
1910     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1911         SemaBuiltinReserveRWPipe(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIcommit_read_pipe:
1915   case Builtin::BIcommit_write_pipe:
1916   case Builtin::BIwork_group_commit_read_pipe:
1917   case Builtin::BIwork_group_commit_write_pipe:
1918     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1919       return ExprError();
1920     break;
1921   case Builtin::BIsub_group_commit_read_pipe:
1922   case Builtin::BIsub_group_commit_write_pipe:
1923     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1924         SemaBuiltinCommitRWPipe(*this, TheCall))
1925       return ExprError();
1926     break;
1927   case Builtin::BIget_pipe_num_packets:
1928   case Builtin::BIget_pipe_max_packets:
1929     if (SemaBuiltinPipePackets(*this, TheCall))
1930       return ExprError();
1931     break;
1932   case Builtin::BIto_global:
1933   case Builtin::BIto_local:
1934   case Builtin::BIto_private:
1935     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1936       return ExprError();
1937     break;
1938   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1939   case Builtin::BIenqueue_kernel:
1940     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1941       return ExprError();
1942     break;
1943   case Builtin::BIget_kernel_work_group_size:
1944   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1945     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1946       return ExprError();
1947     break;
1948   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1949   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1950     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1951       return ExprError();
1952     break;
1953   case Builtin::BI__builtin_os_log_format:
1954     Cleanup.setExprNeedsCleanups(true);
1955     LLVM_FALLTHROUGH;
1956   case Builtin::BI__builtin_os_log_format_buffer_size:
1957     if (SemaBuiltinOSLogFormat(TheCall))
1958       return ExprError();
1959     break;
1960   case Builtin::BI__builtin_frame_address:
1961   case Builtin::BI__builtin_return_address: {
1962     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1963       return ExprError();
1964 
1965     // -Wframe-address warning if non-zero passed to builtin
1966     // return/frame address.
1967     Expr::EvalResult Result;
1968     if (!TheCall->getArg(0)->isValueDependent() &&
1969         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1970         Result.Val.getInt() != 0)
1971       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1972           << ((BuiltinID == Builtin::BI__builtin_return_address)
1973                   ? "__builtin_return_address"
1974                   : "__builtin_frame_address")
1975           << TheCall->getSourceRange();
1976     break;
1977   }
1978 
1979   case Builtin::BI__builtin_matrix_transpose:
1980     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1981 
1982   case Builtin::BI__builtin_matrix_column_major_load:
1983     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1984 
1985   case Builtin::BI__builtin_matrix_column_major_store:
1986     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1987 
1988   case Builtin::BI__builtin_get_device_side_mangled_name: {
1989     auto Check = [](CallExpr *TheCall) {
1990       if (TheCall->getNumArgs() != 1)
1991         return false;
1992       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1993       if (!DRE)
1994         return false;
1995       auto *D = DRE->getDecl();
1996       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1997         return false;
1998       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1999              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2000     };
2001     if (!Check(TheCall)) {
2002       Diag(TheCall->getBeginLoc(),
2003            diag::err_hip_invalid_args_builtin_mangled_name);
2004       return ExprError();
2005     }
2006   }
2007   }
2008 
2009   // Since the target specific builtins for each arch overlap, only check those
2010   // of the arch we are compiling for.
2011   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2012     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2013       assert(Context.getAuxTargetInfo() &&
2014              "Aux Target Builtin, but not an aux target?");
2015 
2016       if (CheckTSBuiltinFunctionCall(
2017               *Context.getAuxTargetInfo(),
2018               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2019         return ExprError();
2020     } else {
2021       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2022                                      TheCall))
2023         return ExprError();
2024     }
2025   }
2026 
2027   return TheCallResult;
2028 }
2029 
2030 // Get the valid immediate range for the specified NEON type code.
2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2032   NeonTypeFlags Type(t);
2033   int IsQuad = ForceQuad ? true : Type.isQuad();
2034   switch (Type.getEltType()) {
2035   case NeonTypeFlags::Int8:
2036   case NeonTypeFlags::Poly8:
2037     return shift ? 7 : (8 << IsQuad) - 1;
2038   case NeonTypeFlags::Int16:
2039   case NeonTypeFlags::Poly16:
2040     return shift ? 15 : (4 << IsQuad) - 1;
2041   case NeonTypeFlags::Int32:
2042     return shift ? 31 : (2 << IsQuad) - 1;
2043   case NeonTypeFlags::Int64:
2044   case NeonTypeFlags::Poly64:
2045     return shift ? 63 : (1 << IsQuad) - 1;
2046   case NeonTypeFlags::Poly128:
2047     return shift ? 127 : (1 << IsQuad) - 1;
2048   case NeonTypeFlags::Float16:
2049     assert(!shift && "cannot shift float types!");
2050     return (4 << IsQuad) - 1;
2051   case NeonTypeFlags::Float32:
2052     assert(!shift && "cannot shift float types!");
2053     return (2 << IsQuad) - 1;
2054   case NeonTypeFlags::Float64:
2055     assert(!shift && "cannot shift float types!");
2056     return (1 << IsQuad) - 1;
2057   case NeonTypeFlags::BFloat16:
2058     assert(!shift && "cannot shift float types!");
2059     return (4 << IsQuad) - 1;
2060   }
2061   llvm_unreachable("Invalid NeonTypeFlag!");
2062 }
2063 
2064 /// getNeonEltType - Return the QualType corresponding to the elements of
2065 /// the vector type specified by the NeonTypeFlags.  This is used to check
2066 /// the pointer arguments for Neon load/store intrinsics.
2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2068                                bool IsPolyUnsigned, bool IsInt64Long) {
2069   switch (Flags.getEltType()) {
2070   case NeonTypeFlags::Int8:
2071     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2072   case NeonTypeFlags::Int16:
2073     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2074   case NeonTypeFlags::Int32:
2075     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2076   case NeonTypeFlags::Int64:
2077     if (IsInt64Long)
2078       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2079     else
2080       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2081                                 : Context.LongLongTy;
2082   case NeonTypeFlags::Poly8:
2083     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2084   case NeonTypeFlags::Poly16:
2085     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2086   case NeonTypeFlags::Poly64:
2087     if (IsInt64Long)
2088       return Context.UnsignedLongTy;
2089     else
2090       return Context.UnsignedLongLongTy;
2091   case NeonTypeFlags::Poly128:
2092     break;
2093   case NeonTypeFlags::Float16:
2094     return Context.HalfTy;
2095   case NeonTypeFlags::Float32:
2096     return Context.FloatTy;
2097   case NeonTypeFlags::Float64:
2098     return Context.DoubleTy;
2099   case NeonTypeFlags::BFloat16:
2100     return Context.BFloat16Ty;
2101   }
2102   llvm_unreachable("Invalid NeonTypeFlag!");
2103 }
2104 
2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2106   // Range check SVE intrinsics that take immediate values.
2107   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2108 
2109   switch (BuiltinID) {
2110   default:
2111     return false;
2112 #define GET_SVE_IMMEDIATE_CHECK
2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2114 #undef GET_SVE_IMMEDIATE_CHECK
2115   }
2116 
2117   // Perform all the immediate checks for this builtin call.
2118   bool HasError = false;
2119   for (auto &I : ImmChecks) {
2120     int ArgNum, CheckTy, ElementSizeInBits;
2121     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2122 
2123     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2124 
2125     // Function that checks whether the operand (ArgNum) is an immediate
2126     // that is one of the predefined values.
2127     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2128                                    int ErrDiag) -> bool {
2129       // We can't check the value of a dependent argument.
2130       Expr *Arg = TheCall->getArg(ArgNum);
2131       if (Arg->isTypeDependent() || Arg->isValueDependent())
2132         return false;
2133 
2134       // Check constant-ness first.
2135       llvm::APSInt Imm;
2136       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2137         return true;
2138 
2139       if (!CheckImm(Imm.getSExtValue()))
2140         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2141       return false;
2142     };
2143 
2144     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2145     case SVETypeFlags::ImmCheck0_31:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2147         HasError = true;
2148       break;
2149     case SVETypeFlags::ImmCheck0_13:
2150       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2151         HasError = true;
2152       break;
2153     case SVETypeFlags::ImmCheck1_16:
2154       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheck0_7:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckExtract:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       (2048 / ElementSizeInBits) - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckShiftRight:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2168         HasError = true;
2169       break;
2170     case SVETypeFlags::ImmCheckShiftRightNarrow:
2171       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2172                                       ElementSizeInBits / 2))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheckShiftLeft:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2177                                       ElementSizeInBits - 1))
2178         HasError = true;
2179       break;
2180     case SVETypeFlags::ImmCheckLaneIndex:
2181       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2182                                       (128 / (1 * ElementSizeInBits)) - 1))
2183         HasError = true;
2184       break;
2185     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2186       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2187                                       (128 / (2 * ElementSizeInBits)) - 1))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheckLaneIndexDot:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2192                                       (128 / (4 * ElementSizeInBits)) - 1))
2193         HasError = true;
2194       break;
2195     case SVETypeFlags::ImmCheckComplexRot90_270:
2196       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2197                               diag::err_rotation_argument_to_cadd))
2198         HasError = true;
2199       break;
2200     case SVETypeFlags::ImmCheckComplexRotAll90:
2201       if (CheckImmediateInSet(
2202               [](int64_t V) {
2203                 return V == 0 || V == 90 || V == 180 || V == 270;
2204               },
2205               diag::err_rotation_argument_to_cmla))
2206         HasError = true;
2207       break;
2208     case SVETypeFlags::ImmCheck0_1:
2209       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2210         HasError = true;
2211       break;
2212     case SVETypeFlags::ImmCheck0_2:
2213       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2214         HasError = true;
2215       break;
2216     case SVETypeFlags::ImmCheck0_3:
2217       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2218         HasError = true;
2219       break;
2220     }
2221   }
2222 
2223   return HasError;
2224 }
2225 
2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2227                                         unsigned BuiltinID, CallExpr *TheCall) {
2228   llvm::APSInt Result;
2229   uint64_t mask = 0;
2230   unsigned TV = 0;
2231   int PtrArgNum = -1;
2232   bool HasConstPtr = false;
2233   switch (BuiltinID) {
2234 #define GET_NEON_OVERLOAD_CHECK
2235 #include "clang/Basic/arm_neon.inc"
2236 #include "clang/Basic/arm_fp16.inc"
2237 #undef GET_NEON_OVERLOAD_CHECK
2238   }
2239 
2240   // For NEON intrinsics which are overloaded on vector element type, validate
2241   // the immediate which specifies which variant to emit.
2242   unsigned ImmArg = TheCall->getNumArgs()-1;
2243   if (mask) {
2244     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2245       return true;
2246 
2247     TV = Result.getLimitedValue(64);
2248     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2249       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2250              << TheCall->getArg(ImmArg)->getSourceRange();
2251   }
2252 
2253   if (PtrArgNum >= 0) {
2254     // Check that pointer arguments have the specified type.
2255     Expr *Arg = TheCall->getArg(PtrArgNum);
2256     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2257       Arg = ICE->getSubExpr();
2258     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2259     QualType RHSTy = RHS.get()->getType();
2260 
2261     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2262     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2263                           Arch == llvm::Triple::aarch64_32 ||
2264                           Arch == llvm::Triple::aarch64_be;
2265     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2266     QualType EltTy =
2267         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2268     if (HasConstPtr)
2269       EltTy = EltTy.withConst();
2270     QualType LHSTy = Context.getPointerType(EltTy);
2271     AssignConvertType ConvTy;
2272     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2273     if (RHS.isInvalid())
2274       return true;
2275     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2276                                  RHS.get(), AA_Assigning))
2277       return true;
2278   }
2279 
2280   // For NEON intrinsics which take an immediate value as part of the
2281   // instruction, range check them here.
2282   unsigned i = 0, l = 0, u = 0;
2283   switch (BuiltinID) {
2284   default:
2285     return false;
2286   #define GET_NEON_IMMEDIATE_CHECK
2287   #include "clang/Basic/arm_neon.inc"
2288   #include "clang/Basic/arm_fp16.inc"
2289   #undef GET_NEON_IMMEDIATE_CHECK
2290   }
2291 
2292   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2293 }
2294 
2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2296   switch (BuiltinID) {
2297   default:
2298     return false;
2299   #include "clang/Basic/arm_mve_builtin_sema.inc"
2300   }
2301 }
2302 
2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2304                                        CallExpr *TheCall) {
2305   bool Err = false;
2306   switch (BuiltinID) {
2307   default:
2308     return false;
2309 #include "clang/Basic/arm_cde_builtin_sema.inc"
2310   }
2311 
2312   if (Err)
2313     return true;
2314 
2315   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2316 }
2317 
2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2319                                         const Expr *CoprocArg, bool WantCDE) {
2320   if (isConstantEvaluated())
2321     return false;
2322 
2323   // We can't check the value of a dependent argument.
2324   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2325     return false;
2326 
2327   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2328   int64_t CoprocNo = CoprocNoAP.getExtValue();
2329   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2330 
2331   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2332   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2333 
2334   if (IsCDECoproc != WantCDE)
2335     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2336            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2337 
2338   return false;
2339 }
2340 
2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2342                                         unsigned MaxWidth) {
2343   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2344           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2345           BuiltinID == ARM::BI__builtin_arm_strex ||
2346           BuiltinID == ARM::BI__builtin_arm_stlex ||
2347           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2348           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2349           BuiltinID == AArch64::BI__builtin_arm_strex ||
2350           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2351          "unexpected ARM builtin");
2352   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2353                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2354                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2355                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2356 
2357   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2358 
2359   // Ensure that we have the proper number of arguments.
2360   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2361     return true;
2362 
2363   // Inspect the pointer argument of the atomic builtin.  This should always be
2364   // a pointer type, whose element is an integral scalar or pointer type.
2365   // Because it is a pointer type, we don't have to worry about any implicit
2366   // casts here.
2367   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2368   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2369   if (PointerArgRes.isInvalid())
2370     return true;
2371   PointerArg = PointerArgRes.get();
2372 
2373   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2374   if (!pointerType) {
2375     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2376         << PointerArg->getType() << PointerArg->getSourceRange();
2377     return true;
2378   }
2379 
2380   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2381   // task is to insert the appropriate casts into the AST. First work out just
2382   // what the appropriate type is.
2383   QualType ValType = pointerType->getPointeeType();
2384   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2385   if (IsLdrex)
2386     AddrType.addConst();
2387 
2388   // Issue a warning if the cast is dodgy.
2389   CastKind CastNeeded = CK_NoOp;
2390   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2391     CastNeeded = CK_BitCast;
2392     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2393         << PointerArg->getType() << Context.getPointerType(AddrType)
2394         << AA_Passing << PointerArg->getSourceRange();
2395   }
2396 
2397   // Finally, do the cast and replace the argument with the corrected version.
2398   AddrType = Context.getPointerType(AddrType);
2399   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2400   if (PointerArgRes.isInvalid())
2401     return true;
2402   PointerArg = PointerArgRes.get();
2403 
2404   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2405 
2406   // In general, we allow ints, floats and pointers to be loaded and stored.
2407   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2408       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2409     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2410         << PointerArg->getType() << PointerArg->getSourceRange();
2411     return true;
2412   }
2413 
2414   // But ARM doesn't have instructions to deal with 128-bit versions.
2415   if (Context.getTypeSize(ValType) > MaxWidth) {
2416     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2417     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2418         << PointerArg->getType() << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   switch (ValType.getObjCLifetime()) {
2423   case Qualifiers::OCL_None:
2424   case Qualifiers::OCL_ExplicitNone:
2425     // okay
2426     break;
2427 
2428   case Qualifiers::OCL_Weak:
2429   case Qualifiers::OCL_Strong:
2430   case Qualifiers::OCL_Autoreleasing:
2431     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2432         << ValType << PointerArg->getSourceRange();
2433     return true;
2434   }
2435 
2436   if (IsLdrex) {
2437     TheCall->setType(ValType);
2438     return false;
2439   }
2440 
2441   // Initialize the argument to be stored.
2442   ExprResult ValArg = TheCall->getArg(0);
2443   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2444       Context, ValType, /*consume*/ false);
2445   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2446   if (ValArg.isInvalid())
2447     return true;
2448   TheCall->setArg(0, ValArg.get());
2449 
2450   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2451   // but the custom checker bypasses all default analysis.
2452   TheCall->setType(Context.IntTy);
2453   return false;
2454 }
2455 
2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2457                                        CallExpr *TheCall) {
2458   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2459       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2460       BuiltinID == ARM::BI__builtin_arm_strex ||
2461       BuiltinID == ARM::BI__builtin_arm_stlex) {
2462     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2463   }
2464 
2465   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2466     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2467       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2468   }
2469 
2470   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2471       BuiltinID == ARM::BI__builtin_arm_wsr64)
2472     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2473 
2474   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2475       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2476       BuiltinID == ARM::BI__builtin_arm_wsr ||
2477       BuiltinID == ARM::BI__builtin_arm_wsrp)
2478     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2479 
2480   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2481     return true;
2482   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2483     return true;
2484   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2485     return true;
2486 
2487   // For intrinsics which take an immediate value as part of the instruction,
2488   // range check them here.
2489   // FIXME: VFP Intrinsics should error if VFP not present.
2490   switch (BuiltinID) {
2491   default: return false;
2492   case ARM::BI__builtin_arm_ssat:
2493     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2494   case ARM::BI__builtin_arm_usat:
2495     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2496   case ARM::BI__builtin_arm_ssat16:
2497     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2498   case ARM::BI__builtin_arm_usat16:
2499     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2500   case ARM::BI__builtin_arm_vcvtr_f:
2501   case ARM::BI__builtin_arm_vcvtr_d:
2502     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2503   case ARM::BI__builtin_arm_dmb:
2504   case ARM::BI__builtin_arm_dsb:
2505   case ARM::BI__builtin_arm_isb:
2506   case ARM::BI__builtin_arm_dbg:
2507     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2508   case ARM::BI__builtin_arm_cdp:
2509   case ARM::BI__builtin_arm_cdp2:
2510   case ARM::BI__builtin_arm_mcr:
2511   case ARM::BI__builtin_arm_mcr2:
2512   case ARM::BI__builtin_arm_mrc:
2513   case ARM::BI__builtin_arm_mrc2:
2514   case ARM::BI__builtin_arm_mcrr:
2515   case ARM::BI__builtin_arm_mcrr2:
2516   case ARM::BI__builtin_arm_mrrc:
2517   case ARM::BI__builtin_arm_mrrc2:
2518   case ARM::BI__builtin_arm_ldc:
2519   case ARM::BI__builtin_arm_ldcl:
2520   case ARM::BI__builtin_arm_ldc2:
2521   case ARM::BI__builtin_arm_ldc2l:
2522   case ARM::BI__builtin_arm_stc:
2523   case ARM::BI__builtin_arm_stcl:
2524   case ARM::BI__builtin_arm_stc2:
2525   case ARM::BI__builtin_arm_stc2l:
2526     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2527            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2528                                         /*WantCDE*/ false);
2529   }
2530 }
2531 
2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2533                                            unsigned BuiltinID,
2534                                            CallExpr *TheCall) {
2535   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2536       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2537       BuiltinID == AArch64::BI__builtin_arm_strex ||
2538       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2539     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2540   }
2541 
2542   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2543     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2544       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2545       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2546       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2550       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2551     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2552 
2553   // Memory Tagging Extensions (MTE) Intrinsics
2554   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2555       BuiltinID == AArch64::BI__builtin_arm_addg ||
2556       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2557       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2558       BuiltinID == AArch64::BI__builtin_arm_stg ||
2559       BuiltinID == AArch64::BI__builtin_arm_subp) {
2560     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2561   }
2562 
2563   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2564       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2565       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2566       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2567     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2568 
2569   // Only check the valid encoding range. Any constant in this range would be
2570   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2571   // an exception for incorrect registers. This matches MSVC behavior.
2572   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2573       BuiltinID == AArch64::BI_WriteStatusReg)
2574     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2575 
2576   if (BuiltinID == AArch64::BI__getReg)
2577     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2578 
2579   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2580     return true;
2581 
2582   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2583     return true;
2584 
2585   // For intrinsics which take an immediate value as part of the instruction,
2586   // range check them here.
2587   unsigned i = 0, l = 0, u = 0;
2588   switch (BuiltinID) {
2589   default: return false;
2590   case AArch64::BI__builtin_arm_dmb:
2591   case AArch64::BI__builtin_arm_dsb:
2592   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2593   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2594   }
2595 
2596   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2597 }
2598 
2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2600   if (Arg->getType()->getAsPlaceholderType())
2601     return false;
2602 
2603   // The first argument needs to be a record field access.
2604   // If it is an array element access, we delay decision
2605   // to BPF backend to check whether the access is a
2606   // field access or not.
2607   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2608           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2609           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2610 }
2611 
2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2613                             QualType VectorTy, QualType EltTy) {
2614   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2615   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2616     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2617         << Call->getSourceRange() << VectorEltTy << EltTy;
2618     return false;
2619   }
2620   return true;
2621 }
2622 
2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2624   QualType ArgType = Arg->getType();
2625   if (ArgType->getAsPlaceholderType())
2626     return false;
2627 
2628   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2629   // format:
2630   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2631   //   2. <type> var;
2632   //      __builtin_preserve_type_info(var, flag);
2633   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2634       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2635     return false;
2636 
2637   // Typedef type.
2638   if (ArgType->getAs<TypedefType>())
2639     return true;
2640 
2641   // Record type or Enum type.
2642   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2643   if (const auto *RT = Ty->getAs<RecordType>()) {
2644     if (!RT->getDecl()->getDeclName().isEmpty())
2645       return true;
2646   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2647     if (!ET->getDecl()->getDeclName().isEmpty())
2648       return true;
2649   }
2650 
2651   return false;
2652 }
2653 
2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2655   QualType ArgType = Arg->getType();
2656   if (ArgType->getAsPlaceholderType())
2657     return false;
2658 
2659   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2660   // format:
2661   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2662   //                                 flag);
2663   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2664   if (!UO)
2665     return false;
2666 
2667   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2668   if (!CE)
2669     return false;
2670   if (CE->getCastKind() != CK_IntegralToPointer &&
2671       CE->getCastKind() != CK_NullToPointer)
2672     return false;
2673 
2674   // The integer must be from an EnumConstantDecl.
2675   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2676   if (!DR)
2677     return false;
2678 
2679   const EnumConstantDecl *Enumerator =
2680       dyn_cast<EnumConstantDecl>(DR->getDecl());
2681   if (!Enumerator)
2682     return false;
2683 
2684   // The type must be EnumType.
2685   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2686   const auto *ET = Ty->getAs<EnumType>();
2687   if (!ET)
2688     return false;
2689 
2690   // The enum value must be supported.
2691   for (auto *EDI : ET->getDecl()->enumerators()) {
2692     if (EDI == Enumerator)
2693       return true;
2694   }
2695 
2696   return false;
2697 }
2698 
2699 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2700                                        CallExpr *TheCall) {
2701   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2702           BuiltinID == BPF::BI__builtin_btf_type_id ||
2703           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2704           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2705          "unexpected BPF builtin");
2706 
2707   if (checkArgCount(*this, TheCall, 2))
2708     return true;
2709 
2710   // The second argument needs to be a constant int
2711   Expr *Arg = TheCall->getArg(1);
2712   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2713   diag::kind kind;
2714   if (!Value) {
2715     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2716       kind = diag::err_preserve_field_info_not_const;
2717     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2718       kind = diag::err_btf_type_id_not_const;
2719     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2720       kind = diag::err_preserve_type_info_not_const;
2721     else
2722       kind = diag::err_preserve_enum_value_not_const;
2723     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2724     return true;
2725   }
2726 
2727   // The first argument
2728   Arg = TheCall->getArg(0);
2729   bool InvalidArg = false;
2730   bool ReturnUnsignedInt = true;
2731   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2732     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2733       InvalidArg = true;
2734       kind = diag::err_preserve_field_info_not_field;
2735     }
2736   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2737     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2738       InvalidArg = true;
2739       kind = diag::err_preserve_type_info_invalid;
2740     }
2741   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2742     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2743       InvalidArg = true;
2744       kind = diag::err_preserve_enum_value_invalid;
2745     }
2746     ReturnUnsignedInt = false;
2747   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2748     ReturnUnsignedInt = false;
2749   }
2750 
2751   if (InvalidArg) {
2752     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2753     return true;
2754   }
2755 
2756   if (ReturnUnsignedInt)
2757     TheCall->setType(Context.UnsignedIntTy);
2758   else
2759     TheCall->setType(Context.UnsignedLongTy);
2760   return false;
2761 }
2762 
2763 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2764   struct ArgInfo {
2765     uint8_t OpNum;
2766     bool IsSigned;
2767     uint8_t BitWidth;
2768     uint8_t Align;
2769   };
2770   struct BuiltinInfo {
2771     unsigned BuiltinID;
2772     ArgInfo Infos[2];
2773   };
2774 
2775   static BuiltinInfo Infos[] = {
2776     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2777     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2778     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2779     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2780     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2782     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2783     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2785     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2786     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2787 
2788     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2791     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2792     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2793     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2799 
2800     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2852                                                       {{ 1, false, 6,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2860                                                       {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2867                                                        { 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2869                                                        { 2, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2871                                                        { 3, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2873                                                        { 3, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2890                                                       {{ 2, false, 4,  0 },
2891                                                        { 3, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2893                                                       {{ 2, false, 4,  0 },
2894                                                        { 3, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2896                                                       {{ 2, false, 4,  0 },
2897                                                        { 3, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2899                                                       {{ 2, false, 4,  0 },
2900                                                        { 3, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2912                                                        { 2, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2914                                                        { 2, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2924                                                       {{ 1, false, 4,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2927                                                       {{ 1, false, 4,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2948                                                       {{ 3, false, 1,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2953                                                       {{ 3, false, 1,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2957     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2958                                                       {{ 3, false, 1,  0 }} },
2959   };
2960 
2961   // Use a dynamically initialized static to sort the table exactly once on
2962   // first run.
2963   static const bool SortOnce =
2964       (llvm::sort(Infos,
2965                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2966                    return LHS.BuiltinID < RHS.BuiltinID;
2967                  }),
2968        true);
2969   (void)SortOnce;
2970 
2971   const BuiltinInfo *F = llvm::partition_point(
2972       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2973   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2974     return false;
2975 
2976   bool Error = false;
2977 
2978   for (const ArgInfo &A : F->Infos) {
2979     // Ignore empty ArgInfo elements.
2980     if (A.BitWidth == 0)
2981       continue;
2982 
2983     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2984     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2985     if (!A.Align) {
2986       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2987     } else {
2988       unsigned M = 1 << A.Align;
2989       Min *= M;
2990       Max *= M;
2991       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2992                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2993     }
2994   }
2995   return Error;
2996 }
2997 
2998 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2999                                            CallExpr *TheCall) {
3000   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3001 }
3002 
3003 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3004                                         unsigned BuiltinID, CallExpr *TheCall) {
3005   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3006          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3007 }
3008 
3009 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3010                                CallExpr *TheCall) {
3011 
3012   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3013       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3014     if (!TI.hasFeature("dsp"))
3015       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3016   }
3017 
3018   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3019       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3020     if (!TI.hasFeature("dspr2"))
3021       return Diag(TheCall->getBeginLoc(),
3022                   diag::err_mips_builtin_requires_dspr2);
3023   }
3024 
3025   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3026       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3027     if (!TI.hasFeature("msa"))
3028       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3029   }
3030 
3031   return false;
3032 }
3033 
3034 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3035 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3036 // ordering for DSP is unspecified. MSA is ordered by the data format used
3037 // by the underlying instruction i.e., df/m, df/n and then by size.
3038 //
3039 // FIXME: The size tests here should instead be tablegen'd along with the
3040 //        definitions from include/clang/Basic/BuiltinsMips.def.
3041 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3042 //        be too.
3043 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3044   unsigned i = 0, l = 0, u = 0, m = 0;
3045   switch (BuiltinID) {
3046   default: return false;
3047   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3048   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3049   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3050   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3051   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3052   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3053   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3054   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3055   // df/m field.
3056   // These intrinsics take an unsigned 3 bit immediate.
3057   case Mips::BI__builtin_msa_bclri_b:
3058   case Mips::BI__builtin_msa_bnegi_b:
3059   case Mips::BI__builtin_msa_bseti_b:
3060   case Mips::BI__builtin_msa_sat_s_b:
3061   case Mips::BI__builtin_msa_sat_u_b:
3062   case Mips::BI__builtin_msa_slli_b:
3063   case Mips::BI__builtin_msa_srai_b:
3064   case Mips::BI__builtin_msa_srari_b:
3065   case Mips::BI__builtin_msa_srli_b:
3066   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3067   case Mips::BI__builtin_msa_binsli_b:
3068   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3069   // These intrinsics take an unsigned 4 bit immediate.
3070   case Mips::BI__builtin_msa_bclri_h:
3071   case Mips::BI__builtin_msa_bnegi_h:
3072   case Mips::BI__builtin_msa_bseti_h:
3073   case Mips::BI__builtin_msa_sat_s_h:
3074   case Mips::BI__builtin_msa_sat_u_h:
3075   case Mips::BI__builtin_msa_slli_h:
3076   case Mips::BI__builtin_msa_srai_h:
3077   case Mips::BI__builtin_msa_srari_h:
3078   case Mips::BI__builtin_msa_srli_h:
3079   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3080   case Mips::BI__builtin_msa_binsli_h:
3081   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3082   // These intrinsics take an unsigned 5 bit immediate.
3083   // The first block of intrinsics actually have an unsigned 5 bit field,
3084   // not a df/n field.
3085   case Mips::BI__builtin_msa_cfcmsa:
3086   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3087   case Mips::BI__builtin_msa_clei_u_b:
3088   case Mips::BI__builtin_msa_clei_u_h:
3089   case Mips::BI__builtin_msa_clei_u_w:
3090   case Mips::BI__builtin_msa_clei_u_d:
3091   case Mips::BI__builtin_msa_clti_u_b:
3092   case Mips::BI__builtin_msa_clti_u_h:
3093   case Mips::BI__builtin_msa_clti_u_w:
3094   case Mips::BI__builtin_msa_clti_u_d:
3095   case Mips::BI__builtin_msa_maxi_u_b:
3096   case Mips::BI__builtin_msa_maxi_u_h:
3097   case Mips::BI__builtin_msa_maxi_u_w:
3098   case Mips::BI__builtin_msa_maxi_u_d:
3099   case Mips::BI__builtin_msa_mini_u_b:
3100   case Mips::BI__builtin_msa_mini_u_h:
3101   case Mips::BI__builtin_msa_mini_u_w:
3102   case Mips::BI__builtin_msa_mini_u_d:
3103   case Mips::BI__builtin_msa_addvi_b:
3104   case Mips::BI__builtin_msa_addvi_h:
3105   case Mips::BI__builtin_msa_addvi_w:
3106   case Mips::BI__builtin_msa_addvi_d:
3107   case Mips::BI__builtin_msa_bclri_w:
3108   case Mips::BI__builtin_msa_bnegi_w:
3109   case Mips::BI__builtin_msa_bseti_w:
3110   case Mips::BI__builtin_msa_sat_s_w:
3111   case Mips::BI__builtin_msa_sat_u_w:
3112   case Mips::BI__builtin_msa_slli_w:
3113   case Mips::BI__builtin_msa_srai_w:
3114   case Mips::BI__builtin_msa_srari_w:
3115   case Mips::BI__builtin_msa_srli_w:
3116   case Mips::BI__builtin_msa_srlri_w:
3117   case Mips::BI__builtin_msa_subvi_b:
3118   case Mips::BI__builtin_msa_subvi_h:
3119   case Mips::BI__builtin_msa_subvi_w:
3120   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3121   case Mips::BI__builtin_msa_binsli_w:
3122   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3123   // These intrinsics take an unsigned 6 bit immediate.
3124   case Mips::BI__builtin_msa_bclri_d:
3125   case Mips::BI__builtin_msa_bnegi_d:
3126   case Mips::BI__builtin_msa_bseti_d:
3127   case Mips::BI__builtin_msa_sat_s_d:
3128   case Mips::BI__builtin_msa_sat_u_d:
3129   case Mips::BI__builtin_msa_slli_d:
3130   case Mips::BI__builtin_msa_srai_d:
3131   case Mips::BI__builtin_msa_srari_d:
3132   case Mips::BI__builtin_msa_srli_d:
3133   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3134   case Mips::BI__builtin_msa_binsli_d:
3135   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3136   // These intrinsics take a signed 5 bit immediate.
3137   case Mips::BI__builtin_msa_ceqi_b:
3138   case Mips::BI__builtin_msa_ceqi_h:
3139   case Mips::BI__builtin_msa_ceqi_w:
3140   case Mips::BI__builtin_msa_ceqi_d:
3141   case Mips::BI__builtin_msa_clti_s_b:
3142   case Mips::BI__builtin_msa_clti_s_h:
3143   case Mips::BI__builtin_msa_clti_s_w:
3144   case Mips::BI__builtin_msa_clti_s_d:
3145   case Mips::BI__builtin_msa_clei_s_b:
3146   case Mips::BI__builtin_msa_clei_s_h:
3147   case Mips::BI__builtin_msa_clei_s_w:
3148   case Mips::BI__builtin_msa_clei_s_d:
3149   case Mips::BI__builtin_msa_maxi_s_b:
3150   case Mips::BI__builtin_msa_maxi_s_h:
3151   case Mips::BI__builtin_msa_maxi_s_w:
3152   case Mips::BI__builtin_msa_maxi_s_d:
3153   case Mips::BI__builtin_msa_mini_s_b:
3154   case Mips::BI__builtin_msa_mini_s_h:
3155   case Mips::BI__builtin_msa_mini_s_w:
3156   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3157   // These intrinsics take an unsigned 8 bit immediate.
3158   case Mips::BI__builtin_msa_andi_b:
3159   case Mips::BI__builtin_msa_nori_b:
3160   case Mips::BI__builtin_msa_ori_b:
3161   case Mips::BI__builtin_msa_shf_b:
3162   case Mips::BI__builtin_msa_shf_h:
3163   case Mips::BI__builtin_msa_shf_w:
3164   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3165   case Mips::BI__builtin_msa_bseli_b:
3166   case Mips::BI__builtin_msa_bmnzi_b:
3167   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3168   // df/n format
3169   // These intrinsics take an unsigned 4 bit immediate.
3170   case Mips::BI__builtin_msa_copy_s_b:
3171   case Mips::BI__builtin_msa_copy_u_b:
3172   case Mips::BI__builtin_msa_insve_b:
3173   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3174   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3175   // These intrinsics take an unsigned 3 bit immediate.
3176   case Mips::BI__builtin_msa_copy_s_h:
3177   case Mips::BI__builtin_msa_copy_u_h:
3178   case Mips::BI__builtin_msa_insve_h:
3179   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3180   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3181   // These intrinsics take an unsigned 2 bit immediate.
3182   case Mips::BI__builtin_msa_copy_s_w:
3183   case Mips::BI__builtin_msa_copy_u_w:
3184   case Mips::BI__builtin_msa_insve_w:
3185   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3186   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3187   // These intrinsics take an unsigned 1 bit immediate.
3188   case Mips::BI__builtin_msa_copy_s_d:
3189   case Mips::BI__builtin_msa_copy_u_d:
3190   case Mips::BI__builtin_msa_insve_d:
3191   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3192   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3193   // Memory offsets and immediate loads.
3194   // These intrinsics take a signed 10 bit immediate.
3195   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3196   case Mips::BI__builtin_msa_ldi_h:
3197   case Mips::BI__builtin_msa_ldi_w:
3198   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3199   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3200   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3201   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3202   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3203   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3204   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3205   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3206   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3207   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3208   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3209   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3210   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3211   }
3212 
3213   if (!m)
3214     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3215 
3216   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3217          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3218 }
3219 
3220 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3221 /// advancing the pointer over the consumed characters. The decoded type is
3222 /// returned. If the decoded type represents a constant integer with a
3223 /// constraint on its value then Mask is set to that value. The type descriptors
3224 /// used in Str are specific to PPC MMA builtins and are documented in the file
3225 /// defining the PPC builtins.
3226 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3227                                         unsigned &Mask) {
3228   bool RequireICE = false;
3229   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3230   switch (*Str++) {
3231   case 'V':
3232     return Context.getVectorType(Context.UnsignedCharTy, 16,
3233                                  VectorType::VectorKind::AltiVecVector);
3234   case 'i': {
3235     char *End;
3236     unsigned size = strtoul(Str, &End, 10);
3237     assert(End != Str && "Missing constant parameter constraint");
3238     Str = End;
3239     Mask = size;
3240     return Context.IntTy;
3241   }
3242   case 'W': {
3243     char *End;
3244     unsigned size = strtoul(Str, &End, 10);
3245     assert(End != Str && "Missing PowerPC MMA type size");
3246     Str = End;
3247     QualType Type;
3248     switch (size) {
3249   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3250     case size: Type = Context.Id##Ty; break;
3251   #include "clang/Basic/PPCTypes.def"
3252     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3253     }
3254     bool CheckVectorArgs = false;
3255     while (!CheckVectorArgs) {
3256       switch (*Str++) {
3257       case '*':
3258         Type = Context.getPointerType(Type);
3259         break;
3260       case 'C':
3261         Type = Type.withConst();
3262         break;
3263       default:
3264         CheckVectorArgs = true;
3265         --Str;
3266         break;
3267       }
3268     }
3269     return Type;
3270   }
3271   default:
3272     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3273   }
3274 }
3275 
3276 static bool isPPC_64Builtin(unsigned BuiltinID) {
3277   // These builtins only work on PPC 64bit targets.
3278   switch (BuiltinID) {
3279   case PPC::BI__builtin_divde:
3280   case PPC::BI__builtin_divdeu:
3281   case PPC::BI__builtin_bpermd:
3282   case PPC::BI__builtin_ppc_ldarx:
3283   case PPC::BI__builtin_ppc_stdcx:
3284   case PPC::BI__builtin_ppc_tdw:
3285   case PPC::BI__builtin_ppc_trapd:
3286   case PPC::BI__builtin_ppc_cmpeqb:
3287   case PPC::BI__builtin_ppc_setb:
3288   case PPC::BI__builtin_ppc_mulhd:
3289   case PPC::BI__builtin_ppc_mulhdu:
3290   case PPC::BI__builtin_ppc_maddhd:
3291   case PPC::BI__builtin_ppc_maddhdu:
3292   case PPC::BI__builtin_ppc_maddld:
3293   case PPC::BI__builtin_ppc_load8r:
3294   case PPC::BI__builtin_ppc_store8r:
3295   case PPC::BI__builtin_ppc_insert_exp:
3296   case PPC::BI__builtin_ppc_extract_sig:
3297   case PPC::BI__builtin_ppc_addex:
3298     return true;
3299   }
3300   return false;
3301 }
3302 
3303 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3304                              StringRef FeatureToCheck, unsigned DiagID,
3305                              StringRef DiagArg = "") {
3306   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3307     return false;
3308 
3309   if (DiagArg.empty())
3310     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3311   else
3312     S.Diag(TheCall->getBeginLoc(), DiagID)
3313         << DiagArg << TheCall->getSourceRange();
3314 
3315   return true;
3316 }
3317 
3318 /// Returns true if the argument consists of one contiguous run of 1s with any
3319 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3320 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3321 /// since all 1s are not contiguous.
3322 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3323   llvm::APSInt Result;
3324   // We can't check the value of a dependent argument.
3325   Expr *Arg = TheCall->getArg(ArgNum);
3326   if (Arg->isTypeDependent() || Arg->isValueDependent())
3327     return false;
3328 
3329   // Check constant-ness first.
3330   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3331     return true;
3332 
3333   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3334   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3335     return false;
3336 
3337   return Diag(TheCall->getBeginLoc(),
3338               diag::err_argument_not_contiguous_bit_field)
3339          << ArgNum << Arg->getSourceRange();
3340 }
3341 
3342 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3343                                        CallExpr *TheCall) {
3344   unsigned i = 0, l = 0, u = 0;
3345   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3346   llvm::APSInt Result;
3347 
3348   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3349     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3350            << TheCall->getSourceRange();
3351 
3352   switch (BuiltinID) {
3353   default: return false;
3354   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3355   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3356     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3357            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3358   case PPC::BI__builtin_altivec_dss:
3359     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3360   case PPC::BI__builtin_tbegin:
3361   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3362   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3363   case PPC::BI__builtin_tabortwc:
3364   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3365   case PPC::BI__builtin_tabortwci:
3366   case PPC::BI__builtin_tabortdci:
3367     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3368            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3369   case PPC::BI__builtin_altivec_dst:
3370   case PPC::BI__builtin_altivec_dstt:
3371   case PPC::BI__builtin_altivec_dstst:
3372   case PPC::BI__builtin_altivec_dststt:
3373     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3374   case PPC::BI__builtin_vsx_xxpermdi:
3375   case PPC::BI__builtin_vsx_xxsldwi:
3376     return SemaBuiltinVSX(TheCall);
3377   case PPC::BI__builtin_divwe:
3378   case PPC::BI__builtin_divweu:
3379   case PPC::BI__builtin_divde:
3380   case PPC::BI__builtin_divdeu:
3381     return SemaFeatureCheck(*this, TheCall, "extdiv",
3382                             diag::err_ppc_builtin_only_on_arch, "7");
3383   case PPC::BI__builtin_bpermd:
3384     return SemaFeatureCheck(*this, TheCall, "bpermd",
3385                             diag::err_ppc_builtin_only_on_arch, "7");
3386   case PPC::BI__builtin_unpack_vector_int128:
3387     return SemaFeatureCheck(*this, TheCall, "vsx",
3388                             diag::err_ppc_builtin_only_on_arch, "7") ||
3389            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3390   case PPC::BI__builtin_pack_vector_int128:
3391     return SemaFeatureCheck(*this, TheCall, "vsx",
3392                             diag::err_ppc_builtin_only_on_arch, "7");
3393   case PPC::BI__builtin_altivec_vgnb:
3394      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3395   case PPC::BI__builtin_altivec_vec_replace_elt:
3396   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3397     QualType VecTy = TheCall->getArg(0)->getType();
3398     QualType EltTy = TheCall->getArg(1)->getType();
3399     unsigned Width = Context.getIntWidth(EltTy);
3400     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3401            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3402   }
3403   case PPC::BI__builtin_vsx_xxeval:
3404      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3405   case PPC::BI__builtin_altivec_vsldbi:
3406      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3407   case PPC::BI__builtin_altivec_vsrdbi:
3408      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3409   case PPC::BI__builtin_vsx_xxpermx:
3410      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3411   case PPC::BI__builtin_ppc_tw:
3412   case PPC::BI__builtin_ppc_tdw:
3413     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3414   case PPC::BI__builtin_ppc_cmpeqb:
3415   case PPC::BI__builtin_ppc_setb:
3416   case PPC::BI__builtin_ppc_maddhd:
3417   case PPC::BI__builtin_ppc_maddhdu:
3418   case PPC::BI__builtin_ppc_maddld:
3419     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3420                             diag::err_ppc_builtin_only_on_arch, "9");
3421   case PPC::BI__builtin_ppc_cmprb:
3422     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3423                             diag::err_ppc_builtin_only_on_arch, "9") ||
3424            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3425   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3426   // be a constant that represents a contiguous bit field.
3427   case PPC::BI__builtin_ppc_rlwnm:
3428     return SemaBuiltinConstantArg(TheCall, 1, Result) ||
3429            SemaValueIsRunOfOnes(TheCall, 2);
3430   case PPC::BI__builtin_ppc_rlwimi:
3431   case PPC::BI__builtin_ppc_rldimi:
3432     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3433            SemaValueIsRunOfOnes(TheCall, 3);
3434   case PPC::BI__builtin_ppc_extract_exp:
3435   case PPC::BI__builtin_ppc_extract_sig:
3436   case PPC::BI__builtin_ppc_insert_exp:
3437     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3438                             diag::err_ppc_builtin_only_on_arch, "9");
3439   case PPC::BI__builtin_ppc_addex: {
3440     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3441                          diag::err_ppc_builtin_only_on_arch, "9") ||
3442         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3443       return true;
3444     // Output warning for reserved values 1 to 3.
3445     int ArgValue =
3446         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3447     if (ArgValue != 0)
3448       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3449           << ArgValue;
3450     return false;
3451   }
3452   case PPC::BI__builtin_ppc_mtfsb0:
3453   case PPC::BI__builtin_ppc_mtfsb1:
3454     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3455   case PPC::BI__builtin_ppc_mtfsf:
3456     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3457   case PPC::BI__builtin_ppc_mtfsfi:
3458     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3459            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3460   case PPC::BI__builtin_ppc_alignx:
3461     return SemaBuiltinConstantArgPower2(TheCall, 0);
3462   case PPC::BI__builtin_ppc_rdlam:
3463     return SemaValueIsRunOfOnes(TheCall, 2);
3464   case PPC::BI__builtin_ppc_icbt:
3465   case PPC::BI__builtin_ppc_sthcx:
3466   case PPC::BI__builtin_ppc_stbcx:
3467   case PPC::BI__builtin_ppc_lharx:
3468   case PPC::BI__builtin_ppc_lbarx:
3469     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3470                             diag::err_ppc_builtin_only_on_arch, "8");
3471   case PPC::BI__builtin_vsx_ldrmb:
3472   case PPC::BI__builtin_vsx_strmb:
3473     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3474                             diag::err_ppc_builtin_only_on_arch, "8") ||
3475            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3476 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3477   case PPC::BI__builtin_##Name: \
3478     return SemaBuiltinPPCMMACall(TheCall, Types);
3479 #include "clang/Basic/BuiltinsPPC.def"
3480   }
3481   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3482 }
3483 
3484 // Check if the given type is a non-pointer PPC MMA type. This function is used
3485 // in Sema to prevent invalid uses of restricted PPC MMA types.
3486 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3487   if (Type->isPointerType() || Type->isArrayType())
3488     return false;
3489 
3490   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3491 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3492   if (false
3493 #include "clang/Basic/PPCTypes.def"
3494      ) {
3495     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3496     return true;
3497   }
3498   return false;
3499 }
3500 
3501 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3502                                           CallExpr *TheCall) {
3503   // position of memory order and scope arguments in the builtin
3504   unsigned OrderIndex, ScopeIndex;
3505   switch (BuiltinID) {
3506   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3507   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3508   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3509   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3510     OrderIndex = 2;
3511     ScopeIndex = 3;
3512     break;
3513   case AMDGPU::BI__builtin_amdgcn_fence:
3514     OrderIndex = 0;
3515     ScopeIndex = 1;
3516     break;
3517   default:
3518     return false;
3519   }
3520 
3521   ExprResult Arg = TheCall->getArg(OrderIndex);
3522   auto ArgExpr = Arg.get();
3523   Expr::EvalResult ArgResult;
3524 
3525   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3526     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3527            << ArgExpr->getType();
3528   auto Ord = ArgResult.Val.getInt().getZExtValue();
3529 
3530   // Check valididty of memory ordering as per C11 / C++11's memody model.
3531   // Only fence needs check. Atomic dec/inc allow all memory orders.
3532   if (!llvm::isValidAtomicOrderingCABI(Ord))
3533     return Diag(ArgExpr->getBeginLoc(),
3534                 diag::warn_atomic_op_has_invalid_memory_order)
3535            << ArgExpr->getSourceRange();
3536   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3537   case llvm::AtomicOrderingCABI::relaxed:
3538   case llvm::AtomicOrderingCABI::consume:
3539     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3540       return Diag(ArgExpr->getBeginLoc(),
3541                   diag::warn_atomic_op_has_invalid_memory_order)
3542              << ArgExpr->getSourceRange();
3543     break;
3544   case llvm::AtomicOrderingCABI::acquire:
3545   case llvm::AtomicOrderingCABI::release:
3546   case llvm::AtomicOrderingCABI::acq_rel:
3547   case llvm::AtomicOrderingCABI::seq_cst:
3548     break;
3549   }
3550 
3551   Arg = TheCall->getArg(ScopeIndex);
3552   ArgExpr = Arg.get();
3553   Expr::EvalResult ArgResult1;
3554   // Check that sync scope is a constant literal
3555   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3556     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3557            << ArgExpr->getType();
3558 
3559   return false;
3560 }
3561 
3562 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3563   llvm::APSInt Result;
3564 
3565   // We can't check the value of a dependent argument.
3566   Expr *Arg = TheCall->getArg(ArgNum);
3567   if (Arg->isTypeDependent() || Arg->isValueDependent())
3568     return false;
3569 
3570   // Check constant-ness first.
3571   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3572     return true;
3573 
3574   int64_t Val = Result.getSExtValue();
3575   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3576     return false;
3577 
3578   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3579          << Arg->getSourceRange();
3580 }
3581 
3582 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3583                                          unsigned BuiltinID,
3584                                          CallExpr *TheCall) {
3585   // CodeGenFunction can also detect this, but this gives a better error
3586   // message.
3587   bool FeatureMissing = false;
3588   SmallVector<StringRef> ReqFeatures;
3589   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3590   Features.split(ReqFeatures, ',');
3591 
3592   // Check if each required feature is included
3593   for (StringRef F : ReqFeatures) {
3594     if (TI.hasFeature(F))
3595       continue;
3596 
3597     // If the feature is 64bit, alter the string so it will print better in
3598     // the diagnostic.
3599     if (F == "64bit")
3600       F = "RV64";
3601 
3602     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3603     F.consume_front("experimental-");
3604     std::string FeatureStr = F.str();
3605     FeatureStr[0] = std::toupper(FeatureStr[0]);
3606 
3607     // Error message
3608     FeatureMissing = true;
3609     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3610         << TheCall->getSourceRange() << StringRef(FeatureStr);
3611   }
3612 
3613   if (FeatureMissing)
3614     return true;
3615 
3616   switch (BuiltinID) {
3617   case RISCV::BI__builtin_rvv_vsetvli:
3618     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3619            CheckRISCVLMUL(TheCall, 2);
3620   case RISCV::BI__builtin_rvv_vsetvlimax:
3621     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3622            CheckRISCVLMUL(TheCall, 1);
3623   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3624   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3625   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3626   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3627   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3628   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3629   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3630   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3631   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3632   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3633   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3634   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3635   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3636   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3637   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3638   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3639   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3640   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3641   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3642   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3643   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3644   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3645   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3646   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3647   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3648   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3649   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3650   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3651   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3652   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3653     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3654   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3655   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3656   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3657   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3658   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3659   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3660   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3661   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3662   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3663   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3664   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3665   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3666   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3667   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3668   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3669   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3670   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3671   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3672   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3673   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3674     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3675   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3676   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3677   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3678   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3679   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3680   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3681   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3682   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3683   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3684   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3685     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3686   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3687   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3688   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3689   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3690   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3691   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3692   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3693   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3694   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3695   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3696   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3697   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3698   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3699   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3700   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3701   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3702   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3703   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3704   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3705   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3706   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3707   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3708   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3709   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3710   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3711   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3712   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3713   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3714   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3715   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3716     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3717   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3718   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3719   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3720   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3721   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3722   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3723   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3724   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3725   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3726   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3727   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3728   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3729   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3730   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3731   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3732   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3733   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3734   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3735   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3736   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3737     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3738   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3739   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3740   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3741   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3742   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3743   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3744   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3745   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3746   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3747   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3748     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3749   }
3750 
3751   return false;
3752 }
3753 
3754 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3755                                            CallExpr *TheCall) {
3756   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3757     Expr *Arg = TheCall->getArg(0);
3758     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3759       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3760         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3761                << Arg->getSourceRange();
3762   }
3763 
3764   // For intrinsics which take an immediate value as part of the instruction,
3765   // range check them here.
3766   unsigned i = 0, l = 0, u = 0;
3767   switch (BuiltinID) {
3768   default: return false;
3769   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3770   case SystemZ::BI__builtin_s390_verimb:
3771   case SystemZ::BI__builtin_s390_verimh:
3772   case SystemZ::BI__builtin_s390_verimf:
3773   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3774   case SystemZ::BI__builtin_s390_vfaeb:
3775   case SystemZ::BI__builtin_s390_vfaeh:
3776   case SystemZ::BI__builtin_s390_vfaef:
3777   case SystemZ::BI__builtin_s390_vfaebs:
3778   case SystemZ::BI__builtin_s390_vfaehs:
3779   case SystemZ::BI__builtin_s390_vfaefs:
3780   case SystemZ::BI__builtin_s390_vfaezb:
3781   case SystemZ::BI__builtin_s390_vfaezh:
3782   case SystemZ::BI__builtin_s390_vfaezf:
3783   case SystemZ::BI__builtin_s390_vfaezbs:
3784   case SystemZ::BI__builtin_s390_vfaezhs:
3785   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3786   case SystemZ::BI__builtin_s390_vfisb:
3787   case SystemZ::BI__builtin_s390_vfidb:
3788     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3789            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3790   case SystemZ::BI__builtin_s390_vftcisb:
3791   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3792   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3793   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3794   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3795   case SystemZ::BI__builtin_s390_vstrcb:
3796   case SystemZ::BI__builtin_s390_vstrch:
3797   case SystemZ::BI__builtin_s390_vstrcf:
3798   case SystemZ::BI__builtin_s390_vstrczb:
3799   case SystemZ::BI__builtin_s390_vstrczh:
3800   case SystemZ::BI__builtin_s390_vstrczf:
3801   case SystemZ::BI__builtin_s390_vstrcbs:
3802   case SystemZ::BI__builtin_s390_vstrchs:
3803   case SystemZ::BI__builtin_s390_vstrcfs:
3804   case SystemZ::BI__builtin_s390_vstrczbs:
3805   case SystemZ::BI__builtin_s390_vstrczhs:
3806   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3807   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3808   case SystemZ::BI__builtin_s390_vfminsb:
3809   case SystemZ::BI__builtin_s390_vfmaxsb:
3810   case SystemZ::BI__builtin_s390_vfmindb:
3811   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3812   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3813   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3814   case SystemZ::BI__builtin_s390_vclfnhs:
3815   case SystemZ::BI__builtin_s390_vclfnls:
3816   case SystemZ::BI__builtin_s390_vcfn:
3817   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3818   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3819   }
3820   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3821 }
3822 
3823 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3824 /// This checks that the target supports __builtin_cpu_supports and
3825 /// that the string argument is constant and valid.
3826 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3827                                    CallExpr *TheCall) {
3828   Expr *Arg = TheCall->getArg(0);
3829 
3830   // Check if the argument is a string literal.
3831   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3832     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3833            << Arg->getSourceRange();
3834 
3835   // Check the contents of the string.
3836   StringRef Feature =
3837       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3838   if (!TI.validateCpuSupports(Feature))
3839     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3840            << Arg->getSourceRange();
3841   return false;
3842 }
3843 
3844 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3845 /// This checks that the target supports __builtin_cpu_is and
3846 /// that the string argument is constant and valid.
3847 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3848   Expr *Arg = TheCall->getArg(0);
3849 
3850   // Check if the argument is a string literal.
3851   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3852     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3853            << Arg->getSourceRange();
3854 
3855   // Check the contents of the string.
3856   StringRef Feature =
3857       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3858   if (!TI.validateCpuIs(Feature))
3859     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3860            << Arg->getSourceRange();
3861   return false;
3862 }
3863 
3864 // Check if the rounding mode is legal.
3865 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3866   // Indicates if this instruction has rounding control or just SAE.
3867   bool HasRC = false;
3868 
3869   unsigned ArgNum = 0;
3870   switch (BuiltinID) {
3871   default:
3872     return false;
3873   case X86::BI__builtin_ia32_vcvttsd2si32:
3874   case X86::BI__builtin_ia32_vcvttsd2si64:
3875   case X86::BI__builtin_ia32_vcvttsd2usi32:
3876   case X86::BI__builtin_ia32_vcvttsd2usi64:
3877   case X86::BI__builtin_ia32_vcvttss2si32:
3878   case X86::BI__builtin_ia32_vcvttss2si64:
3879   case X86::BI__builtin_ia32_vcvttss2usi32:
3880   case X86::BI__builtin_ia32_vcvttss2usi64:
3881   case X86::BI__builtin_ia32_vcvttsh2si32:
3882   case X86::BI__builtin_ia32_vcvttsh2si64:
3883   case X86::BI__builtin_ia32_vcvttsh2usi32:
3884   case X86::BI__builtin_ia32_vcvttsh2usi64:
3885     ArgNum = 1;
3886     break;
3887   case X86::BI__builtin_ia32_maxpd512:
3888   case X86::BI__builtin_ia32_maxps512:
3889   case X86::BI__builtin_ia32_minpd512:
3890   case X86::BI__builtin_ia32_minps512:
3891   case X86::BI__builtin_ia32_maxph512:
3892   case X86::BI__builtin_ia32_minph512:
3893     ArgNum = 2;
3894     break;
3895   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3896   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3897   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3898   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3899   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3900   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3901   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3902   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3903   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3904   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3905   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3906   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3907   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3908   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3909   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3910   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3911   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3912   case X86::BI__builtin_ia32_exp2pd_mask:
3913   case X86::BI__builtin_ia32_exp2ps_mask:
3914   case X86::BI__builtin_ia32_getexppd512_mask:
3915   case X86::BI__builtin_ia32_getexpps512_mask:
3916   case X86::BI__builtin_ia32_getexpph512_mask:
3917   case X86::BI__builtin_ia32_rcp28pd_mask:
3918   case X86::BI__builtin_ia32_rcp28ps_mask:
3919   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3920   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3921   case X86::BI__builtin_ia32_vcomisd:
3922   case X86::BI__builtin_ia32_vcomiss:
3923   case X86::BI__builtin_ia32_vcomish:
3924   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3925     ArgNum = 3;
3926     break;
3927   case X86::BI__builtin_ia32_cmppd512_mask:
3928   case X86::BI__builtin_ia32_cmpps512_mask:
3929   case X86::BI__builtin_ia32_cmpsd_mask:
3930   case X86::BI__builtin_ia32_cmpss_mask:
3931   case X86::BI__builtin_ia32_cmpsh_mask:
3932   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3933   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3934   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3935   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3936   case X86::BI__builtin_ia32_getexpss128_round_mask:
3937   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3938   case X86::BI__builtin_ia32_getmantpd512_mask:
3939   case X86::BI__builtin_ia32_getmantps512_mask:
3940   case X86::BI__builtin_ia32_getmantph512_mask:
3941   case X86::BI__builtin_ia32_maxsd_round_mask:
3942   case X86::BI__builtin_ia32_maxss_round_mask:
3943   case X86::BI__builtin_ia32_maxsh_round_mask:
3944   case X86::BI__builtin_ia32_minsd_round_mask:
3945   case X86::BI__builtin_ia32_minss_round_mask:
3946   case X86::BI__builtin_ia32_minsh_round_mask:
3947   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3948   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3949   case X86::BI__builtin_ia32_reducepd512_mask:
3950   case X86::BI__builtin_ia32_reduceps512_mask:
3951   case X86::BI__builtin_ia32_reduceph512_mask:
3952   case X86::BI__builtin_ia32_rndscalepd_mask:
3953   case X86::BI__builtin_ia32_rndscaleps_mask:
3954   case X86::BI__builtin_ia32_rndscaleph_mask:
3955   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3956   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3957     ArgNum = 4;
3958     break;
3959   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3960   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3961   case X86::BI__builtin_ia32_fixupimmps512_mask:
3962   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3963   case X86::BI__builtin_ia32_fixupimmsd_mask:
3964   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3965   case X86::BI__builtin_ia32_fixupimmss_mask:
3966   case X86::BI__builtin_ia32_fixupimmss_maskz:
3967   case X86::BI__builtin_ia32_getmantsd_round_mask:
3968   case X86::BI__builtin_ia32_getmantss_round_mask:
3969   case X86::BI__builtin_ia32_getmantsh_round_mask:
3970   case X86::BI__builtin_ia32_rangepd512_mask:
3971   case X86::BI__builtin_ia32_rangeps512_mask:
3972   case X86::BI__builtin_ia32_rangesd128_round_mask:
3973   case X86::BI__builtin_ia32_rangess128_round_mask:
3974   case X86::BI__builtin_ia32_reducesd_mask:
3975   case X86::BI__builtin_ia32_reducess_mask:
3976   case X86::BI__builtin_ia32_reducesh_mask:
3977   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3978   case X86::BI__builtin_ia32_rndscaless_round_mask:
3979   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3980     ArgNum = 5;
3981     break;
3982   case X86::BI__builtin_ia32_vcvtsd2si64:
3983   case X86::BI__builtin_ia32_vcvtsd2si32:
3984   case X86::BI__builtin_ia32_vcvtsd2usi32:
3985   case X86::BI__builtin_ia32_vcvtsd2usi64:
3986   case X86::BI__builtin_ia32_vcvtss2si32:
3987   case X86::BI__builtin_ia32_vcvtss2si64:
3988   case X86::BI__builtin_ia32_vcvtss2usi32:
3989   case X86::BI__builtin_ia32_vcvtss2usi64:
3990   case X86::BI__builtin_ia32_vcvtsh2si32:
3991   case X86::BI__builtin_ia32_vcvtsh2si64:
3992   case X86::BI__builtin_ia32_vcvtsh2usi32:
3993   case X86::BI__builtin_ia32_vcvtsh2usi64:
3994   case X86::BI__builtin_ia32_sqrtpd512:
3995   case X86::BI__builtin_ia32_sqrtps512:
3996   case X86::BI__builtin_ia32_sqrtph512:
3997     ArgNum = 1;
3998     HasRC = true;
3999     break;
4000   case X86::BI__builtin_ia32_addph512:
4001   case X86::BI__builtin_ia32_divph512:
4002   case X86::BI__builtin_ia32_mulph512:
4003   case X86::BI__builtin_ia32_subph512:
4004   case X86::BI__builtin_ia32_addpd512:
4005   case X86::BI__builtin_ia32_addps512:
4006   case X86::BI__builtin_ia32_divpd512:
4007   case X86::BI__builtin_ia32_divps512:
4008   case X86::BI__builtin_ia32_mulpd512:
4009   case X86::BI__builtin_ia32_mulps512:
4010   case X86::BI__builtin_ia32_subpd512:
4011   case X86::BI__builtin_ia32_subps512:
4012   case X86::BI__builtin_ia32_cvtsi2sd64:
4013   case X86::BI__builtin_ia32_cvtsi2ss32:
4014   case X86::BI__builtin_ia32_cvtsi2ss64:
4015   case X86::BI__builtin_ia32_cvtusi2sd64:
4016   case X86::BI__builtin_ia32_cvtusi2ss32:
4017   case X86::BI__builtin_ia32_cvtusi2ss64:
4018   case X86::BI__builtin_ia32_vcvtusi2sh:
4019   case X86::BI__builtin_ia32_vcvtusi642sh:
4020   case X86::BI__builtin_ia32_vcvtsi2sh:
4021   case X86::BI__builtin_ia32_vcvtsi642sh:
4022     ArgNum = 2;
4023     HasRC = true;
4024     break;
4025   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
4026   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
4027   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
4028   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
4029   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
4030   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
4031   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
4032   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
4033   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
4034   case X86::BI__builtin_ia32_cvtps2dq512_mask:
4035   case X86::BI__builtin_ia32_cvtps2qq512_mask:
4036   case X86::BI__builtin_ia32_cvtps2udq512_mask:
4037   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
4038   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
4039   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
4040   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
4041   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
4042   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
4043   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
4044   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
4045   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
4046   case X86::BI__builtin_ia32_vcvtph2w512_mask:
4047   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
4048   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
4049   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
4050   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
4051   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
4052   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
4053   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
4054     ArgNum = 3;
4055     HasRC = true;
4056     break;
4057   case X86::BI__builtin_ia32_addsh_round_mask:
4058   case X86::BI__builtin_ia32_addss_round_mask:
4059   case X86::BI__builtin_ia32_addsd_round_mask:
4060   case X86::BI__builtin_ia32_divsh_round_mask:
4061   case X86::BI__builtin_ia32_divss_round_mask:
4062   case X86::BI__builtin_ia32_divsd_round_mask:
4063   case X86::BI__builtin_ia32_mulsh_round_mask:
4064   case X86::BI__builtin_ia32_mulss_round_mask:
4065   case X86::BI__builtin_ia32_mulsd_round_mask:
4066   case X86::BI__builtin_ia32_subsh_round_mask:
4067   case X86::BI__builtin_ia32_subss_round_mask:
4068   case X86::BI__builtin_ia32_subsd_round_mask:
4069   case X86::BI__builtin_ia32_scalefph512_mask:
4070   case X86::BI__builtin_ia32_scalefpd512_mask:
4071   case X86::BI__builtin_ia32_scalefps512_mask:
4072   case X86::BI__builtin_ia32_scalefsd_round_mask:
4073   case X86::BI__builtin_ia32_scalefss_round_mask:
4074   case X86::BI__builtin_ia32_scalefsh_round_mask:
4075   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4076   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4077   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4078   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4079   case X86::BI__builtin_ia32_sqrtss_round_mask:
4080   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4081   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4082   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4083   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4084   case X86::BI__builtin_ia32_vfmaddss3_mask:
4085   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4086   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4087   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4088   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4089   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4090   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4091   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4092   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4093   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4094   case X86::BI__builtin_ia32_vfmaddps512_mask:
4095   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4096   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4097   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4098   case X86::BI__builtin_ia32_vfmaddph512_mask:
4099   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4100   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4101   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4102   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4103   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4104   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4105   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4106   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4107   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4108   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4109   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4110   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4111   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4112   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4113   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4114     ArgNum = 4;
4115     HasRC = true;
4116     break;
4117   }
4118 
4119   llvm::APSInt Result;
4120 
4121   // We can't check the value of a dependent argument.
4122   Expr *Arg = TheCall->getArg(ArgNum);
4123   if (Arg->isTypeDependent() || Arg->isValueDependent())
4124     return false;
4125 
4126   // Check constant-ness first.
4127   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4128     return true;
4129 
4130   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4131   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4132   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4133   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4134   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4135       Result == 8/*ROUND_NO_EXC*/ ||
4136       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4137       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4138     return false;
4139 
4140   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4141          << Arg->getSourceRange();
4142 }
4143 
4144 // Check if the gather/scatter scale is legal.
4145 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4146                                              CallExpr *TheCall) {
4147   unsigned ArgNum = 0;
4148   switch (BuiltinID) {
4149   default:
4150     return false;
4151   case X86::BI__builtin_ia32_gatherpfdpd:
4152   case X86::BI__builtin_ia32_gatherpfdps:
4153   case X86::BI__builtin_ia32_gatherpfqpd:
4154   case X86::BI__builtin_ia32_gatherpfqps:
4155   case X86::BI__builtin_ia32_scatterpfdpd:
4156   case X86::BI__builtin_ia32_scatterpfdps:
4157   case X86::BI__builtin_ia32_scatterpfqpd:
4158   case X86::BI__builtin_ia32_scatterpfqps:
4159     ArgNum = 3;
4160     break;
4161   case X86::BI__builtin_ia32_gatherd_pd:
4162   case X86::BI__builtin_ia32_gatherd_pd256:
4163   case X86::BI__builtin_ia32_gatherq_pd:
4164   case X86::BI__builtin_ia32_gatherq_pd256:
4165   case X86::BI__builtin_ia32_gatherd_ps:
4166   case X86::BI__builtin_ia32_gatherd_ps256:
4167   case X86::BI__builtin_ia32_gatherq_ps:
4168   case X86::BI__builtin_ia32_gatherq_ps256:
4169   case X86::BI__builtin_ia32_gatherd_q:
4170   case X86::BI__builtin_ia32_gatherd_q256:
4171   case X86::BI__builtin_ia32_gatherq_q:
4172   case X86::BI__builtin_ia32_gatherq_q256:
4173   case X86::BI__builtin_ia32_gatherd_d:
4174   case X86::BI__builtin_ia32_gatherd_d256:
4175   case X86::BI__builtin_ia32_gatherq_d:
4176   case X86::BI__builtin_ia32_gatherq_d256:
4177   case X86::BI__builtin_ia32_gather3div2df:
4178   case X86::BI__builtin_ia32_gather3div2di:
4179   case X86::BI__builtin_ia32_gather3div4df:
4180   case X86::BI__builtin_ia32_gather3div4di:
4181   case X86::BI__builtin_ia32_gather3div4sf:
4182   case X86::BI__builtin_ia32_gather3div4si:
4183   case X86::BI__builtin_ia32_gather3div8sf:
4184   case X86::BI__builtin_ia32_gather3div8si:
4185   case X86::BI__builtin_ia32_gather3siv2df:
4186   case X86::BI__builtin_ia32_gather3siv2di:
4187   case X86::BI__builtin_ia32_gather3siv4df:
4188   case X86::BI__builtin_ia32_gather3siv4di:
4189   case X86::BI__builtin_ia32_gather3siv4sf:
4190   case X86::BI__builtin_ia32_gather3siv4si:
4191   case X86::BI__builtin_ia32_gather3siv8sf:
4192   case X86::BI__builtin_ia32_gather3siv8si:
4193   case X86::BI__builtin_ia32_gathersiv8df:
4194   case X86::BI__builtin_ia32_gathersiv16sf:
4195   case X86::BI__builtin_ia32_gatherdiv8df:
4196   case X86::BI__builtin_ia32_gatherdiv16sf:
4197   case X86::BI__builtin_ia32_gathersiv8di:
4198   case X86::BI__builtin_ia32_gathersiv16si:
4199   case X86::BI__builtin_ia32_gatherdiv8di:
4200   case X86::BI__builtin_ia32_gatherdiv16si:
4201   case X86::BI__builtin_ia32_scatterdiv2df:
4202   case X86::BI__builtin_ia32_scatterdiv2di:
4203   case X86::BI__builtin_ia32_scatterdiv4df:
4204   case X86::BI__builtin_ia32_scatterdiv4di:
4205   case X86::BI__builtin_ia32_scatterdiv4sf:
4206   case X86::BI__builtin_ia32_scatterdiv4si:
4207   case X86::BI__builtin_ia32_scatterdiv8sf:
4208   case X86::BI__builtin_ia32_scatterdiv8si:
4209   case X86::BI__builtin_ia32_scattersiv2df:
4210   case X86::BI__builtin_ia32_scattersiv2di:
4211   case X86::BI__builtin_ia32_scattersiv4df:
4212   case X86::BI__builtin_ia32_scattersiv4di:
4213   case X86::BI__builtin_ia32_scattersiv4sf:
4214   case X86::BI__builtin_ia32_scattersiv4si:
4215   case X86::BI__builtin_ia32_scattersiv8sf:
4216   case X86::BI__builtin_ia32_scattersiv8si:
4217   case X86::BI__builtin_ia32_scattersiv8df:
4218   case X86::BI__builtin_ia32_scattersiv16sf:
4219   case X86::BI__builtin_ia32_scatterdiv8df:
4220   case X86::BI__builtin_ia32_scatterdiv16sf:
4221   case X86::BI__builtin_ia32_scattersiv8di:
4222   case X86::BI__builtin_ia32_scattersiv16si:
4223   case X86::BI__builtin_ia32_scatterdiv8di:
4224   case X86::BI__builtin_ia32_scatterdiv16si:
4225     ArgNum = 4;
4226     break;
4227   }
4228 
4229   llvm::APSInt Result;
4230 
4231   // We can't check the value of a dependent argument.
4232   Expr *Arg = TheCall->getArg(ArgNum);
4233   if (Arg->isTypeDependent() || Arg->isValueDependent())
4234     return false;
4235 
4236   // Check constant-ness first.
4237   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4238     return true;
4239 
4240   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4241     return false;
4242 
4243   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4244          << Arg->getSourceRange();
4245 }
4246 
4247 enum { TileRegLow = 0, TileRegHigh = 7 };
4248 
4249 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4250                                              ArrayRef<int> ArgNums) {
4251   for (int ArgNum : ArgNums) {
4252     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4253       return true;
4254   }
4255   return false;
4256 }
4257 
4258 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4259                                         ArrayRef<int> ArgNums) {
4260   // Because the max number of tile register is TileRegHigh + 1, so here we use
4261   // each bit to represent the usage of them in bitset.
4262   std::bitset<TileRegHigh + 1> ArgValues;
4263   for (int ArgNum : ArgNums) {
4264     Expr *Arg = TheCall->getArg(ArgNum);
4265     if (Arg->isTypeDependent() || Arg->isValueDependent())
4266       continue;
4267 
4268     llvm::APSInt Result;
4269     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4270       return true;
4271     int ArgExtValue = Result.getExtValue();
4272     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4273            "Incorrect tile register num.");
4274     if (ArgValues.test(ArgExtValue))
4275       return Diag(TheCall->getBeginLoc(),
4276                   diag::err_x86_builtin_tile_arg_duplicate)
4277              << TheCall->getArg(ArgNum)->getSourceRange();
4278     ArgValues.set(ArgExtValue);
4279   }
4280   return false;
4281 }
4282 
4283 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4284                                                 ArrayRef<int> ArgNums) {
4285   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4286          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4287 }
4288 
4289 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4290   switch (BuiltinID) {
4291   default:
4292     return false;
4293   case X86::BI__builtin_ia32_tileloadd64:
4294   case X86::BI__builtin_ia32_tileloaddt164:
4295   case X86::BI__builtin_ia32_tilestored64:
4296   case X86::BI__builtin_ia32_tilezero:
4297     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4298   case X86::BI__builtin_ia32_tdpbssd:
4299   case X86::BI__builtin_ia32_tdpbsud:
4300   case X86::BI__builtin_ia32_tdpbusd:
4301   case X86::BI__builtin_ia32_tdpbuud:
4302   case X86::BI__builtin_ia32_tdpbf16ps:
4303     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4304   }
4305 }
4306 static bool isX86_32Builtin(unsigned BuiltinID) {
4307   // These builtins only work on x86-32 targets.
4308   switch (BuiltinID) {
4309   case X86::BI__builtin_ia32_readeflags_u32:
4310   case X86::BI__builtin_ia32_writeeflags_u32:
4311     return true;
4312   }
4313 
4314   return false;
4315 }
4316 
4317 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4318                                        CallExpr *TheCall) {
4319   if (BuiltinID == X86::BI__builtin_cpu_supports)
4320     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4321 
4322   if (BuiltinID == X86::BI__builtin_cpu_is)
4323     return SemaBuiltinCpuIs(*this, TI, TheCall);
4324 
4325   // Check for 32-bit only builtins on a 64-bit target.
4326   const llvm::Triple &TT = TI.getTriple();
4327   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4328     return Diag(TheCall->getCallee()->getBeginLoc(),
4329                 diag::err_32_bit_builtin_64_bit_tgt);
4330 
4331   // If the intrinsic has rounding or SAE make sure its valid.
4332   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4333     return true;
4334 
4335   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4336   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4337     return true;
4338 
4339   // If the intrinsic has a tile arguments, make sure they are valid.
4340   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4341     return true;
4342 
4343   // For intrinsics which take an immediate value as part of the instruction,
4344   // range check them here.
4345   int i = 0, l = 0, u = 0;
4346   switch (BuiltinID) {
4347   default:
4348     return false;
4349   case X86::BI__builtin_ia32_vec_ext_v2si:
4350   case X86::BI__builtin_ia32_vec_ext_v2di:
4351   case X86::BI__builtin_ia32_vextractf128_pd256:
4352   case X86::BI__builtin_ia32_vextractf128_ps256:
4353   case X86::BI__builtin_ia32_vextractf128_si256:
4354   case X86::BI__builtin_ia32_extract128i256:
4355   case X86::BI__builtin_ia32_extractf64x4_mask:
4356   case X86::BI__builtin_ia32_extracti64x4_mask:
4357   case X86::BI__builtin_ia32_extractf32x8_mask:
4358   case X86::BI__builtin_ia32_extracti32x8_mask:
4359   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4360   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4361   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4362   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4363     i = 1; l = 0; u = 1;
4364     break;
4365   case X86::BI__builtin_ia32_vec_set_v2di:
4366   case X86::BI__builtin_ia32_vinsertf128_pd256:
4367   case X86::BI__builtin_ia32_vinsertf128_ps256:
4368   case X86::BI__builtin_ia32_vinsertf128_si256:
4369   case X86::BI__builtin_ia32_insert128i256:
4370   case X86::BI__builtin_ia32_insertf32x8:
4371   case X86::BI__builtin_ia32_inserti32x8:
4372   case X86::BI__builtin_ia32_insertf64x4:
4373   case X86::BI__builtin_ia32_inserti64x4:
4374   case X86::BI__builtin_ia32_insertf64x2_256:
4375   case X86::BI__builtin_ia32_inserti64x2_256:
4376   case X86::BI__builtin_ia32_insertf32x4_256:
4377   case X86::BI__builtin_ia32_inserti32x4_256:
4378     i = 2; l = 0; u = 1;
4379     break;
4380   case X86::BI__builtin_ia32_vpermilpd:
4381   case X86::BI__builtin_ia32_vec_ext_v4hi:
4382   case X86::BI__builtin_ia32_vec_ext_v4si:
4383   case X86::BI__builtin_ia32_vec_ext_v4sf:
4384   case X86::BI__builtin_ia32_vec_ext_v4di:
4385   case X86::BI__builtin_ia32_extractf32x4_mask:
4386   case X86::BI__builtin_ia32_extracti32x4_mask:
4387   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4388   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4389     i = 1; l = 0; u = 3;
4390     break;
4391   case X86::BI_mm_prefetch:
4392   case X86::BI__builtin_ia32_vec_ext_v8hi:
4393   case X86::BI__builtin_ia32_vec_ext_v8si:
4394     i = 1; l = 0; u = 7;
4395     break;
4396   case X86::BI__builtin_ia32_sha1rnds4:
4397   case X86::BI__builtin_ia32_blendpd:
4398   case X86::BI__builtin_ia32_shufpd:
4399   case X86::BI__builtin_ia32_vec_set_v4hi:
4400   case X86::BI__builtin_ia32_vec_set_v4si:
4401   case X86::BI__builtin_ia32_vec_set_v4di:
4402   case X86::BI__builtin_ia32_shuf_f32x4_256:
4403   case X86::BI__builtin_ia32_shuf_f64x2_256:
4404   case X86::BI__builtin_ia32_shuf_i32x4_256:
4405   case X86::BI__builtin_ia32_shuf_i64x2_256:
4406   case X86::BI__builtin_ia32_insertf64x2_512:
4407   case X86::BI__builtin_ia32_inserti64x2_512:
4408   case X86::BI__builtin_ia32_insertf32x4:
4409   case X86::BI__builtin_ia32_inserti32x4:
4410     i = 2; l = 0; u = 3;
4411     break;
4412   case X86::BI__builtin_ia32_vpermil2pd:
4413   case X86::BI__builtin_ia32_vpermil2pd256:
4414   case X86::BI__builtin_ia32_vpermil2ps:
4415   case X86::BI__builtin_ia32_vpermil2ps256:
4416     i = 3; l = 0; u = 3;
4417     break;
4418   case X86::BI__builtin_ia32_cmpb128_mask:
4419   case X86::BI__builtin_ia32_cmpw128_mask:
4420   case X86::BI__builtin_ia32_cmpd128_mask:
4421   case X86::BI__builtin_ia32_cmpq128_mask:
4422   case X86::BI__builtin_ia32_cmpb256_mask:
4423   case X86::BI__builtin_ia32_cmpw256_mask:
4424   case X86::BI__builtin_ia32_cmpd256_mask:
4425   case X86::BI__builtin_ia32_cmpq256_mask:
4426   case X86::BI__builtin_ia32_cmpb512_mask:
4427   case X86::BI__builtin_ia32_cmpw512_mask:
4428   case X86::BI__builtin_ia32_cmpd512_mask:
4429   case X86::BI__builtin_ia32_cmpq512_mask:
4430   case X86::BI__builtin_ia32_ucmpb128_mask:
4431   case X86::BI__builtin_ia32_ucmpw128_mask:
4432   case X86::BI__builtin_ia32_ucmpd128_mask:
4433   case X86::BI__builtin_ia32_ucmpq128_mask:
4434   case X86::BI__builtin_ia32_ucmpb256_mask:
4435   case X86::BI__builtin_ia32_ucmpw256_mask:
4436   case X86::BI__builtin_ia32_ucmpd256_mask:
4437   case X86::BI__builtin_ia32_ucmpq256_mask:
4438   case X86::BI__builtin_ia32_ucmpb512_mask:
4439   case X86::BI__builtin_ia32_ucmpw512_mask:
4440   case X86::BI__builtin_ia32_ucmpd512_mask:
4441   case X86::BI__builtin_ia32_ucmpq512_mask:
4442   case X86::BI__builtin_ia32_vpcomub:
4443   case X86::BI__builtin_ia32_vpcomuw:
4444   case X86::BI__builtin_ia32_vpcomud:
4445   case X86::BI__builtin_ia32_vpcomuq:
4446   case X86::BI__builtin_ia32_vpcomb:
4447   case X86::BI__builtin_ia32_vpcomw:
4448   case X86::BI__builtin_ia32_vpcomd:
4449   case X86::BI__builtin_ia32_vpcomq:
4450   case X86::BI__builtin_ia32_vec_set_v8hi:
4451   case X86::BI__builtin_ia32_vec_set_v8si:
4452     i = 2; l = 0; u = 7;
4453     break;
4454   case X86::BI__builtin_ia32_vpermilpd256:
4455   case X86::BI__builtin_ia32_roundps:
4456   case X86::BI__builtin_ia32_roundpd:
4457   case X86::BI__builtin_ia32_roundps256:
4458   case X86::BI__builtin_ia32_roundpd256:
4459   case X86::BI__builtin_ia32_getmantpd128_mask:
4460   case X86::BI__builtin_ia32_getmantpd256_mask:
4461   case X86::BI__builtin_ia32_getmantps128_mask:
4462   case X86::BI__builtin_ia32_getmantps256_mask:
4463   case X86::BI__builtin_ia32_getmantpd512_mask:
4464   case X86::BI__builtin_ia32_getmantps512_mask:
4465   case X86::BI__builtin_ia32_getmantph128_mask:
4466   case X86::BI__builtin_ia32_getmantph256_mask:
4467   case X86::BI__builtin_ia32_getmantph512_mask:
4468   case X86::BI__builtin_ia32_vec_ext_v16qi:
4469   case X86::BI__builtin_ia32_vec_ext_v16hi:
4470     i = 1; l = 0; u = 15;
4471     break;
4472   case X86::BI__builtin_ia32_pblendd128:
4473   case X86::BI__builtin_ia32_blendps:
4474   case X86::BI__builtin_ia32_blendpd256:
4475   case X86::BI__builtin_ia32_shufpd256:
4476   case X86::BI__builtin_ia32_roundss:
4477   case X86::BI__builtin_ia32_roundsd:
4478   case X86::BI__builtin_ia32_rangepd128_mask:
4479   case X86::BI__builtin_ia32_rangepd256_mask:
4480   case X86::BI__builtin_ia32_rangepd512_mask:
4481   case X86::BI__builtin_ia32_rangeps128_mask:
4482   case X86::BI__builtin_ia32_rangeps256_mask:
4483   case X86::BI__builtin_ia32_rangeps512_mask:
4484   case X86::BI__builtin_ia32_getmantsd_round_mask:
4485   case X86::BI__builtin_ia32_getmantss_round_mask:
4486   case X86::BI__builtin_ia32_getmantsh_round_mask:
4487   case X86::BI__builtin_ia32_vec_set_v16qi:
4488   case X86::BI__builtin_ia32_vec_set_v16hi:
4489     i = 2; l = 0; u = 15;
4490     break;
4491   case X86::BI__builtin_ia32_vec_ext_v32qi:
4492     i = 1; l = 0; u = 31;
4493     break;
4494   case X86::BI__builtin_ia32_cmpps:
4495   case X86::BI__builtin_ia32_cmpss:
4496   case X86::BI__builtin_ia32_cmppd:
4497   case X86::BI__builtin_ia32_cmpsd:
4498   case X86::BI__builtin_ia32_cmpps256:
4499   case X86::BI__builtin_ia32_cmppd256:
4500   case X86::BI__builtin_ia32_cmpps128_mask:
4501   case X86::BI__builtin_ia32_cmppd128_mask:
4502   case X86::BI__builtin_ia32_cmpps256_mask:
4503   case X86::BI__builtin_ia32_cmppd256_mask:
4504   case X86::BI__builtin_ia32_cmpps512_mask:
4505   case X86::BI__builtin_ia32_cmppd512_mask:
4506   case X86::BI__builtin_ia32_cmpsd_mask:
4507   case X86::BI__builtin_ia32_cmpss_mask:
4508   case X86::BI__builtin_ia32_vec_set_v32qi:
4509     i = 2; l = 0; u = 31;
4510     break;
4511   case X86::BI__builtin_ia32_permdf256:
4512   case X86::BI__builtin_ia32_permdi256:
4513   case X86::BI__builtin_ia32_permdf512:
4514   case X86::BI__builtin_ia32_permdi512:
4515   case X86::BI__builtin_ia32_vpermilps:
4516   case X86::BI__builtin_ia32_vpermilps256:
4517   case X86::BI__builtin_ia32_vpermilpd512:
4518   case X86::BI__builtin_ia32_vpermilps512:
4519   case X86::BI__builtin_ia32_pshufd:
4520   case X86::BI__builtin_ia32_pshufd256:
4521   case X86::BI__builtin_ia32_pshufd512:
4522   case X86::BI__builtin_ia32_pshufhw:
4523   case X86::BI__builtin_ia32_pshufhw256:
4524   case X86::BI__builtin_ia32_pshufhw512:
4525   case X86::BI__builtin_ia32_pshuflw:
4526   case X86::BI__builtin_ia32_pshuflw256:
4527   case X86::BI__builtin_ia32_pshuflw512:
4528   case X86::BI__builtin_ia32_vcvtps2ph:
4529   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4530   case X86::BI__builtin_ia32_vcvtps2ph256:
4531   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4532   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4533   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4534   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4535   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4536   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4537   case X86::BI__builtin_ia32_rndscaleps_mask:
4538   case X86::BI__builtin_ia32_rndscalepd_mask:
4539   case X86::BI__builtin_ia32_rndscaleph_mask:
4540   case X86::BI__builtin_ia32_reducepd128_mask:
4541   case X86::BI__builtin_ia32_reducepd256_mask:
4542   case X86::BI__builtin_ia32_reducepd512_mask:
4543   case X86::BI__builtin_ia32_reduceps128_mask:
4544   case X86::BI__builtin_ia32_reduceps256_mask:
4545   case X86::BI__builtin_ia32_reduceps512_mask:
4546   case X86::BI__builtin_ia32_reduceph128_mask:
4547   case X86::BI__builtin_ia32_reduceph256_mask:
4548   case X86::BI__builtin_ia32_reduceph512_mask:
4549   case X86::BI__builtin_ia32_prold512:
4550   case X86::BI__builtin_ia32_prolq512:
4551   case X86::BI__builtin_ia32_prold128:
4552   case X86::BI__builtin_ia32_prold256:
4553   case X86::BI__builtin_ia32_prolq128:
4554   case X86::BI__builtin_ia32_prolq256:
4555   case X86::BI__builtin_ia32_prord512:
4556   case X86::BI__builtin_ia32_prorq512:
4557   case X86::BI__builtin_ia32_prord128:
4558   case X86::BI__builtin_ia32_prord256:
4559   case X86::BI__builtin_ia32_prorq128:
4560   case X86::BI__builtin_ia32_prorq256:
4561   case X86::BI__builtin_ia32_fpclasspd128_mask:
4562   case X86::BI__builtin_ia32_fpclasspd256_mask:
4563   case X86::BI__builtin_ia32_fpclassps128_mask:
4564   case X86::BI__builtin_ia32_fpclassps256_mask:
4565   case X86::BI__builtin_ia32_fpclassps512_mask:
4566   case X86::BI__builtin_ia32_fpclasspd512_mask:
4567   case X86::BI__builtin_ia32_fpclassph128_mask:
4568   case X86::BI__builtin_ia32_fpclassph256_mask:
4569   case X86::BI__builtin_ia32_fpclassph512_mask:
4570   case X86::BI__builtin_ia32_fpclasssd_mask:
4571   case X86::BI__builtin_ia32_fpclassss_mask:
4572   case X86::BI__builtin_ia32_fpclasssh_mask:
4573   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4574   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4575   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4576   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4577   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4578   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4579   case X86::BI__builtin_ia32_kshiftliqi:
4580   case X86::BI__builtin_ia32_kshiftlihi:
4581   case X86::BI__builtin_ia32_kshiftlisi:
4582   case X86::BI__builtin_ia32_kshiftlidi:
4583   case X86::BI__builtin_ia32_kshiftriqi:
4584   case X86::BI__builtin_ia32_kshiftrihi:
4585   case X86::BI__builtin_ia32_kshiftrisi:
4586   case X86::BI__builtin_ia32_kshiftridi:
4587     i = 1; l = 0; u = 255;
4588     break;
4589   case X86::BI__builtin_ia32_vperm2f128_pd256:
4590   case X86::BI__builtin_ia32_vperm2f128_ps256:
4591   case X86::BI__builtin_ia32_vperm2f128_si256:
4592   case X86::BI__builtin_ia32_permti256:
4593   case X86::BI__builtin_ia32_pblendw128:
4594   case X86::BI__builtin_ia32_pblendw256:
4595   case X86::BI__builtin_ia32_blendps256:
4596   case X86::BI__builtin_ia32_pblendd256:
4597   case X86::BI__builtin_ia32_palignr128:
4598   case X86::BI__builtin_ia32_palignr256:
4599   case X86::BI__builtin_ia32_palignr512:
4600   case X86::BI__builtin_ia32_alignq512:
4601   case X86::BI__builtin_ia32_alignd512:
4602   case X86::BI__builtin_ia32_alignd128:
4603   case X86::BI__builtin_ia32_alignd256:
4604   case X86::BI__builtin_ia32_alignq128:
4605   case X86::BI__builtin_ia32_alignq256:
4606   case X86::BI__builtin_ia32_vcomisd:
4607   case X86::BI__builtin_ia32_vcomiss:
4608   case X86::BI__builtin_ia32_shuf_f32x4:
4609   case X86::BI__builtin_ia32_shuf_f64x2:
4610   case X86::BI__builtin_ia32_shuf_i32x4:
4611   case X86::BI__builtin_ia32_shuf_i64x2:
4612   case X86::BI__builtin_ia32_shufpd512:
4613   case X86::BI__builtin_ia32_shufps:
4614   case X86::BI__builtin_ia32_shufps256:
4615   case X86::BI__builtin_ia32_shufps512:
4616   case X86::BI__builtin_ia32_dbpsadbw128:
4617   case X86::BI__builtin_ia32_dbpsadbw256:
4618   case X86::BI__builtin_ia32_dbpsadbw512:
4619   case X86::BI__builtin_ia32_vpshldd128:
4620   case X86::BI__builtin_ia32_vpshldd256:
4621   case X86::BI__builtin_ia32_vpshldd512:
4622   case X86::BI__builtin_ia32_vpshldq128:
4623   case X86::BI__builtin_ia32_vpshldq256:
4624   case X86::BI__builtin_ia32_vpshldq512:
4625   case X86::BI__builtin_ia32_vpshldw128:
4626   case X86::BI__builtin_ia32_vpshldw256:
4627   case X86::BI__builtin_ia32_vpshldw512:
4628   case X86::BI__builtin_ia32_vpshrdd128:
4629   case X86::BI__builtin_ia32_vpshrdd256:
4630   case X86::BI__builtin_ia32_vpshrdd512:
4631   case X86::BI__builtin_ia32_vpshrdq128:
4632   case X86::BI__builtin_ia32_vpshrdq256:
4633   case X86::BI__builtin_ia32_vpshrdq512:
4634   case X86::BI__builtin_ia32_vpshrdw128:
4635   case X86::BI__builtin_ia32_vpshrdw256:
4636   case X86::BI__builtin_ia32_vpshrdw512:
4637     i = 2; l = 0; u = 255;
4638     break;
4639   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4640   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4641   case X86::BI__builtin_ia32_fixupimmps512_mask:
4642   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4643   case X86::BI__builtin_ia32_fixupimmsd_mask:
4644   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4645   case X86::BI__builtin_ia32_fixupimmss_mask:
4646   case X86::BI__builtin_ia32_fixupimmss_maskz:
4647   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4648   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4649   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4650   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4651   case X86::BI__builtin_ia32_fixupimmps128_mask:
4652   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4653   case X86::BI__builtin_ia32_fixupimmps256_mask:
4654   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4655   case X86::BI__builtin_ia32_pternlogd512_mask:
4656   case X86::BI__builtin_ia32_pternlogd512_maskz:
4657   case X86::BI__builtin_ia32_pternlogq512_mask:
4658   case X86::BI__builtin_ia32_pternlogq512_maskz:
4659   case X86::BI__builtin_ia32_pternlogd128_mask:
4660   case X86::BI__builtin_ia32_pternlogd128_maskz:
4661   case X86::BI__builtin_ia32_pternlogd256_mask:
4662   case X86::BI__builtin_ia32_pternlogd256_maskz:
4663   case X86::BI__builtin_ia32_pternlogq128_mask:
4664   case X86::BI__builtin_ia32_pternlogq128_maskz:
4665   case X86::BI__builtin_ia32_pternlogq256_mask:
4666   case X86::BI__builtin_ia32_pternlogq256_maskz:
4667     i = 3; l = 0; u = 255;
4668     break;
4669   case X86::BI__builtin_ia32_gatherpfdpd:
4670   case X86::BI__builtin_ia32_gatherpfdps:
4671   case X86::BI__builtin_ia32_gatherpfqpd:
4672   case X86::BI__builtin_ia32_gatherpfqps:
4673   case X86::BI__builtin_ia32_scatterpfdpd:
4674   case X86::BI__builtin_ia32_scatterpfdps:
4675   case X86::BI__builtin_ia32_scatterpfqpd:
4676   case X86::BI__builtin_ia32_scatterpfqps:
4677     i = 4; l = 2; u = 3;
4678     break;
4679   case X86::BI__builtin_ia32_reducesd_mask:
4680   case X86::BI__builtin_ia32_reducess_mask:
4681   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4682   case X86::BI__builtin_ia32_rndscaless_round_mask:
4683   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4684   case X86::BI__builtin_ia32_reducesh_mask:
4685     i = 4; l = 0; u = 255;
4686     break;
4687   }
4688 
4689   // Note that we don't force a hard error on the range check here, allowing
4690   // template-generated or macro-generated dead code to potentially have out-of-
4691   // range values. These need to code generate, but don't need to necessarily
4692   // make any sense. We use a warning that defaults to an error.
4693   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4694 }
4695 
4696 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4697 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4698 /// Returns true when the format fits the function and the FormatStringInfo has
4699 /// been populated.
4700 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4701                                FormatStringInfo *FSI) {
4702   FSI->HasVAListArg = Format->getFirstArg() == 0;
4703   FSI->FormatIdx = Format->getFormatIdx() - 1;
4704   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4705 
4706   // The way the format attribute works in GCC, the implicit this argument
4707   // of member functions is counted. However, it doesn't appear in our own
4708   // lists, so decrement format_idx in that case.
4709   if (IsCXXMember) {
4710     if(FSI->FormatIdx == 0)
4711       return false;
4712     --FSI->FormatIdx;
4713     if (FSI->FirstDataArg != 0)
4714       --FSI->FirstDataArg;
4715   }
4716   return true;
4717 }
4718 
4719 /// Checks if a the given expression evaluates to null.
4720 ///
4721 /// Returns true if the value evaluates to null.
4722 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4723   // If the expression has non-null type, it doesn't evaluate to null.
4724   if (auto nullability
4725         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4726     if (*nullability == NullabilityKind::NonNull)
4727       return false;
4728   }
4729 
4730   // As a special case, transparent unions initialized with zero are
4731   // considered null for the purposes of the nonnull attribute.
4732   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4733     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4734       if (const CompoundLiteralExpr *CLE =
4735           dyn_cast<CompoundLiteralExpr>(Expr))
4736         if (const InitListExpr *ILE =
4737             dyn_cast<InitListExpr>(CLE->getInitializer()))
4738           Expr = ILE->getInit(0);
4739   }
4740 
4741   bool Result;
4742   return (!Expr->isValueDependent() &&
4743           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4744           !Result);
4745 }
4746 
4747 static void CheckNonNullArgument(Sema &S,
4748                                  const Expr *ArgExpr,
4749                                  SourceLocation CallSiteLoc) {
4750   if (CheckNonNullExpr(S, ArgExpr))
4751     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4752                           S.PDiag(diag::warn_null_arg)
4753                               << ArgExpr->getSourceRange());
4754 }
4755 
4756 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4757   FormatStringInfo FSI;
4758   if ((GetFormatStringType(Format) == FST_NSString) &&
4759       getFormatStringInfo(Format, false, &FSI)) {
4760     Idx = FSI.FormatIdx;
4761     return true;
4762   }
4763   return false;
4764 }
4765 
4766 /// Diagnose use of %s directive in an NSString which is being passed
4767 /// as formatting string to formatting method.
4768 static void
4769 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4770                                         const NamedDecl *FDecl,
4771                                         Expr **Args,
4772                                         unsigned NumArgs) {
4773   unsigned Idx = 0;
4774   bool Format = false;
4775   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4776   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4777     Idx = 2;
4778     Format = true;
4779   }
4780   else
4781     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4782       if (S.GetFormatNSStringIdx(I, Idx)) {
4783         Format = true;
4784         break;
4785       }
4786     }
4787   if (!Format || NumArgs <= Idx)
4788     return;
4789   const Expr *FormatExpr = Args[Idx];
4790   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4791     FormatExpr = CSCE->getSubExpr();
4792   const StringLiteral *FormatString;
4793   if (const ObjCStringLiteral *OSL =
4794       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4795     FormatString = OSL->getString();
4796   else
4797     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4798   if (!FormatString)
4799     return;
4800   if (S.FormatStringHasSArg(FormatString)) {
4801     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4802       << "%s" << 1 << 1;
4803     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4804       << FDecl->getDeclName();
4805   }
4806 }
4807 
4808 /// Determine whether the given type has a non-null nullability annotation.
4809 static bool isNonNullType(ASTContext &ctx, QualType type) {
4810   if (auto nullability = type->getNullability(ctx))
4811     return *nullability == NullabilityKind::NonNull;
4812 
4813   return false;
4814 }
4815 
4816 static void CheckNonNullArguments(Sema &S,
4817                                   const NamedDecl *FDecl,
4818                                   const FunctionProtoType *Proto,
4819                                   ArrayRef<const Expr *> Args,
4820                                   SourceLocation CallSiteLoc) {
4821   assert((FDecl || Proto) && "Need a function declaration or prototype");
4822 
4823   // Already checked by by constant evaluator.
4824   if (S.isConstantEvaluated())
4825     return;
4826   // Check the attributes attached to the method/function itself.
4827   llvm::SmallBitVector NonNullArgs;
4828   if (FDecl) {
4829     // Handle the nonnull attribute on the function/method declaration itself.
4830     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4831       if (!NonNull->args_size()) {
4832         // Easy case: all pointer arguments are nonnull.
4833         for (const auto *Arg : Args)
4834           if (S.isValidPointerAttrType(Arg->getType()))
4835             CheckNonNullArgument(S, Arg, CallSiteLoc);
4836         return;
4837       }
4838 
4839       for (const ParamIdx &Idx : NonNull->args()) {
4840         unsigned IdxAST = Idx.getASTIndex();
4841         if (IdxAST >= Args.size())
4842           continue;
4843         if (NonNullArgs.empty())
4844           NonNullArgs.resize(Args.size());
4845         NonNullArgs.set(IdxAST);
4846       }
4847     }
4848   }
4849 
4850   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4851     // Handle the nonnull attribute on the parameters of the
4852     // function/method.
4853     ArrayRef<ParmVarDecl*> parms;
4854     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4855       parms = FD->parameters();
4856     else
4857       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4858 
4859     unsigned ParamIndex = 0;
4860     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4861          I != E; ++I, ++ParamIndex) {
4862       const ParmVarDecl *PVD = *I;
4863       if (PVD->hasAttr<NonNullAttr>() ||
4864           isNonNullType(S.Context, PVD->getType())) {
4865         if (NonNullArgs.empty())
4866           NonNullArgs.resize(Args.size());
4867 
4868         NonNullArgs.set(ParamIndex);
4869       }
4870     }
4871   } else {
4872     // If we have a non-function, non-method declaration but no
4873     // function prototype, try to dig out the function prototype.
4874     if (!Proto) {
4875       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4876         QualType type = VD->getType().getNonReferenceType();
4877         if (auto pointerType = type->getAs<PointerType>())
4878           type = pointerType->getPointeeType();
4879         else if (auto blockType = type->getAs<BlockPointerType>())
4880           type = blockType->getPointeeType();
4881         // FIXME: data member pointers?
4882 
4883         // Dig out the function prototype, if there is one.
4884         Proto = type->getAs<FunctionProtoType>();
4885       }
4886     }
4887 
4888     // Fill in non-null argument information from the nullability
4889     // information on the parameter types (if we have them).
4890     if (Proto) {
4891       unsigned Index = 0;
4892       for (auto paramType : Proto->getParamTypes()) {
4893         if (isNonNullType(S.Context, paramType)) {
4894           if (NonNullArgs.empty())
4895             NonNullArgs.resize(Args.size());
4896 
4897           NonNullArgs.set(Index);
4898         }
4899 
4900         ++Index;
4901       }
4902     }
4903   }
4904 
4905   // Check for non-null arguments.
4906   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4907        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4908     if (NonNullArgs[ArgIndex])
4909       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4910   }
4911 }
4912 
4913 /// Warn if a pointer or reference argument passed to a function points to an
4914 /// object that is less aligned than the parameter. This can happen when
4915 /// creating a typedef with a lower alignment than the original type and then
4916 /// calling functions defined in terms of the original type.
4917 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4918                              StringRef ParamName, QualType ArgTy,
4919                              QualType ParamTy) {
4920 
4921   // If a function accepts a pointer or reference type
4922   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4923     return;
4924 
4925   // If the parameter is a pointer type, get the pointee type for the
4926   // argument too. If the parameter is a reference type, don't try to get
4927   // the pointee type for the argument.
4928   if (ParamTy->isPointerType())
4929     ArgTy = ArgTy->getPointeeType();
4930 
4931   // Remove reference or pointer
4932   ParamTy = ParamTy->getPointeeType();
4933 
4934   // Find expected alignment, and the actual alignment of the passed object.
4935   // getTypeAlignInChars requires complete types
4936   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4937       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4938       ArgTy->isUndeducedType())
4939     return;
4940 
4941   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4942   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4943 
4944   // If the argument is less aligned than the parameter, there is a
4945   // potential alignment issue.
4946   if (ArgAlign < ParamAlign)
4947     Diag(Loc, diag::warn_param_mismatched_alignment)
4948         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4949         << ParamName << FDecl;
4950 }
4951 
4952 /// Handles the checks for format strings, non-POD arguments to vararg
4953 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4954 /// attributes.
4955 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4956                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4957                      bool IsMemberFunction, SourceLocation Loc,
4958                      SourceRange Range, VariadicCallType CallType) {
4959   // FIXME: We should check as much as we can in the template definition.
4960   if (CurContext->isDependentContext())
4961     return;
4962 
4963   // Printf and scanf checking.
4964   llvm::SmallBitVector CheckedVarArgs;
4965   if (FDecl) {
4966     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4967       // Only create vector if there are format attributes.
4968       CheckedVarArgs.resize(Args.size());
4969 
4970       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4971                            CheckedVarArgs);
4972     }
4973   }
4974 
4975   // Refuse POD arguments that weren't caught by the format string
4976   // checks above.
4977   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4978   if (CallType != VariadicDoesNotApply &&
4979       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4980     unsigned NumParams = Proto ? Proto->getNumParams()
4981                        : FDecl && isa<FunctionDecl>(FDecl)
4982                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4983                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4984                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4985                        : 0;
4986 
4987     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4988       // Args[ArgIdx] can be null in malformed code.
4989       if (const Expr *Arg = Args[ArgIdx]) {
4990         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4991           checkVariadicArgument(Arg, CallType);
4992       }
4993     }
4994   }
4995 
4996   if (FDecl || Proto) {
4997     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4998 
4999     // Type safety checking.
5000     if (FDecl) {
5001       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
5002         CheckArgumentWithTypeTag(I, Args, Loc);
5003     }
5004   }
5005 
5006   // Check that passed arguments match the alignment of original arguments.
5007   // Try to get the missing prototype from the declaration.
5008   if (!Proto && FDecl) {
5009     const auto *FT = FDecl->getFunctionType();
5010     if (isa_and_nonnull<FunctionProtoType>(FT))
5011       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
5012   }
5013   if (Proto) {
5014     // For variadic functions, we may have more args than parameters.
5015     // For some K&R functions, we may have less args than parameters.
5016     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
5017     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
5018       // Args[ArgIdx] can be null in malformed code.
5019       if (const Expr *Arg = Args[ArgIdx]) {
5020         if (Arg->containsErrors())
5021           continue;
5022 
5023         QualType ParamTy = Proto->getParamType(ArgIdx);
5024         QualType ArgTy = Arg->getType();
5025         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
5026                           ArgTy, ParamTy);
5027       }
5028     }
5029   }
5030 
5031   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
5032     auto *AA = FDecl->getAttr<AllocAlignAttr>();
5033     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
5034     if (!Arg->isValueDependent()) {
5035       Expr::EvalResult Align;
5036       if (Arg->EvaluateAsInt(Align, Context)) {
5037         const llvm::APSInt &I = Align.Val.getInt();
5038         if (!I.isPowerOf2())
5039           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
5040               << Arg->getSourceRange();
5041 
5042         if (I > Sema::MaximumAlignment)
5043           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5044               << Arg->getSourceRange() << Sema::MaximumAlignment;
5045       }
5046     }
5047   }
5048 
5049   if (FD)
5050     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5051 }
5052 
5053 /// CheckConstructorCall - Check a constructor call for correctness and safety
5054 /// properties not enforced by the C type system.
5055 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5056                                 ArrayRef<const Expr *> Args,
5057                                 const FunctionProtoType *Proto,
5058                                 SourceLocation Loc) {
5059   VariadicCallType CallType =
5060       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5061 
5062   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5063   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5064                     Context.getPointerType(Ctor->getThisObjectType()));
5065 
5066   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5067             Loc, SourceRange(), CallType);
5068 }
5069 
5070 /// CheckFunctionCall - Check a direct function call for various correctness
5071 /// and safety properties not strictly enforced by the C type system.
5072 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5073                              const FunctionProtoType *Proto) {
5074   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5075                               isa<CXXMethodDecl>(FDecl);
5076   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5077                           IsMemberOperatorCall;
5078   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5079                                                   TheCall->getCallee());
5080   Expr** Args = TheCall->getArgs();
5081   unsigned NumArgs = TheCall->getNumArgs();
5082 
5083   Expr *ImplicitThis = nullptr;
5084   if (IsMemberOperatorCall) {
5085     // If this is a call to a member operator, hide the first argument
5086     // from checkCall.
5087     // FIXME: Our choice of AST representation here is less than ideal.
5088     ImplicitThis = Args[0];
5089     ++Args;
5090     --NumArgs;
5091   } else if (IsMemberFunction)
5092     ImplicitThis =
5093         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5094 
5095   if (ImplicitThis) {
5096     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5097     // used.
5098     QualType ThisType = ImplicitThis->getType();
5099     if (!ThisType->isPointerType()) {
5100       assert(!ThisType->isReferenceType());
5101       ThisType = Context.getPointerType(ThisType);
5102     }
5103 
5104     QualType ThisTypeFromDecl =
5105         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5106 
5107     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5108                       ThisTypeFromDecl);
5109   }
5110 
5111   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5112             IsMemberFunction, TheCall->getRParenLoc(),
5113             TheCall->getCallee()->getSourceRange(), CallType);
5114 
5115   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5116   // None of the checks below are needed for functions that don't have
5117   // simple names (e.g., C++ conversion functions).
5118   if (!FnInfo)
5119     return false;
5120 
5121   CheckTCBEnforcement(TheCall, FDecl);
5122 
5123   CheckAbsoluteValueFunction(TheCall, FDecl);
5124   CheckMaxUnsignedZero(TheCall, FDecl);
5125 
5126   if (getLangOpts().ObjC)
5127     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5128 
5129   unsigned CMId = FDecl->getMemoryFunctionKind();
5130 
5131   // Handle memory setting and copying functions.
5132   switch (CMId) {
5133   case 0:
5134     return false;
5135   case Builtin::BIstrlcpy: // fallthrough
5136   case Builtin::BIstrlcat:
5137     CheckStrlcpycatArguments(TheCall, FnInfo);
5138     break;
5139   case Builtin::BIstrncat:
5140     CheckStrncatArguments(TheCall, FnInfo);
5141     break;
5142   case Builtin::BIfree:
5143     CheckFreeArguments(TheCall);
5144     break;
5145   default:
5146     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5147   }
5148 
5149   return false;
5150 }
5151 
5152 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5153                                ArrayRef<const Expr *> Args) {
5154   VariadicCallType CallType =
5155       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5156 
5157   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5158             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5159             CallType);
5160 
5161   return false;
5162 }
5163 
5164 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5165                             const FunctionProtoType *Proto) {
5166   QualType Ty;
5167   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5168     Ty = V->getType().getNonReferenceType();
5169   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5170     Ty = F->getType().getNonReferenceType();
5171   else
5172     return false;
5173 
5174   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5175       !Ty->isFunctionProtoType())
5176     return false;
5177 
5178   VariadicCallType CallType;
5179   if (!Proto || !Proto->isVariadic()) {
5180     CallType = VariadicDoesNotApply;
5181   } else if (Ty->isBlockPointerType()) {
5182     CallType = VariadicBlock;
5183   } else { // Ty->isFunctionPointerType()
5184     CallType = VariadicFunction;
5185   }
5186 
5187   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5188             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5189             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5190             TheCall->getCallee()->getSourceRange(), CallType);
5191 
5192   return false;
5193 }
5194 
5195 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5196 /// such as function pointers returned from functions.
5197 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5198   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5199                                                   TheCall->getCallee());
5200   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5201             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5202             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5203             TheCall->getCallee()->getSourceRange(), CallType);
5204 
5205   return false;
5206 }
5207 
5208 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5209   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5210     return false;
5211 
5212   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5213   switch (Op) {
5214   case AtomicExpr::AO__c11_atomic_init:
5215   case AtomicExpr::AO__opencl_atomic_init:
5216     llvm_unreachable("There is no ordering argument for an init");
5217 
5218   case AtomicExpr::AO__c11_atomic_load:
5219   case AtomicExpr::AO__opencl_atomic_load:
5220   case AtomicExpr::AO__atomic_load_n:
5221   case AtomicExpr::AO__atomic_load:
5222     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5223            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5224 
5225   case AtomicExpr::AO__c11_atomic_store:
5226   case AtomicExpr::AO__opencl_atomic_store:
5227   case AtomicExpr::AO__atomic_store:
5228   case AtomicExpr::AO__atomic_store_n:
5229     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5230            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5231            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5232 
5233   default:
5234     return true;
5235   }
5236 }
5237 
5238 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5239                                          AtomicExpr::AtomicOp Op) {
5240   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5241   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5242   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5243   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5244                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5245                          Op);
5246 }
5247 
5248 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5249                                  SourceLocation RParenLoc, MultiExprArg Args,
5250                                  AtomicExpr::AtomicOp Op,
5251                                  AtomicArgumentOrder ArgOrder) {
5252   // All the non-OpenCL operations take one of the following forms.
5253   // The OpenCL operations take the __c11 forms with one extra argument for
5254   // synchronization scope.
5255   enum {
5256     // C    __c11_atomic_init(A *, C)
5257     Init,
5258 
5259     // C    __c11_atomic_load(A *, int)
5260     Load,
5261 
5262     // void __atomic_load(A *, CP, int)
5263     LoadCopy,
5264 
5265     // void __atomic_store(A *, CP, int)
5266     Copy,
5267 
5268     // C    __c11_atomic_add(A *, M, int)
5269     Arithmetic,
5270 
5271     // C    __atomic_exchange_n(A *, CP, int)
5272     Xchg,
5273 
5274     // void __atomic_exchange(A *, C *, CP, int)
5275     GNUXchg,
5276 
5277     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5278     C11CmpXchg,
5279 
5280     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5281     GNUCmpXchg
5282   } Form = Init;
5283 
5284   const unsigned NumForm = GNUCmpXchg + 1;
5285   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5286   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5287   // where:
5288   //   C is an appropriate type,
5289   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5290   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5291   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5292   //   the int parameters are for orderings.
5293 
5294   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5295       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5296       "need to update code for modified forms");
5297   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5298                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5299                         AtomicExpr::AO__atomic_load,
5300                 "need to update code for modified C11 atomics");
5301   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5302                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5303   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5304                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5305                IsOpenCL;
5306   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5307              Op == AtomicExpr::AO__atomic_store_n ||
5308              Op == AtomicExpr::AO__atomic_exchange_n ||
5309              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5310   bool IsAddSub = false;
5311 
5312   switch (Op) {
5313   case AtomicExpr::AO__c11_atomic_init:
5314   case AtomicExpr::AO__opencl_atomic_init:
5315     Form = Init;
5316     break;
5317 
5318   case AtomicExpr::AO__c11_atomic_load:
5319   case AtomicExpr::AO__opencl_atomic_load:
5320   case AtomicExpr::AO__atomic_load_n:
5321     Form = Load;
5322     break;
5323 
5324   case AtomicExpr::AO__atomic_load:
5325     Form = LoadCopy;
5326     break;
5327 
5328   case AtomicExpr::AO__c11_atomic_store:
5329   case AtomicExpr::AO__opencl_atomic_store:
5330   case AtomicExpr::AO__atomic_store:
5331   case AtomicExpr::AO__atomic_store_n:
5332     Form = Copy;
5333     break;
5334 
5335   case AtomicExpr::AO__c11_atomic_fetch_add:
5336   case AtomicExpr::AO__c11_atomic_fetch_sub:
5337   case AtomicExpr::AO__opencl_atomic_fetch_add:
5338   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5339   case AtomicExpr::AO__atomic_fetch_add:
5340   case AtomicExpr::AO__atomic_fetch_sub:
5341   case AtomicExpr::AO__atomic_add_fetch:
5342   case AtomicExpr::AO__atomic_sub_fetch:
5343     IsAddSub = true;
5344     Form = Arithmetic;
5345     break;
5346   case AtomicExpr::AO__c11_atomic_fetch_and:
5347   case AtomicExpr::AO__c11_atomic_fetch_or:
5348   case AtomicExpr::AO__c11_atomic_fetch_xor:
5349   case AtomicExpr::AO__opencl_atomic_fetch_and:
5350   case AtomicExpr::AO__opencl_atomic_fetch_or:
5351   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5352   case AtomicExpr::AO__atomic_fetch_and:
5353   case AtomicExpr::AO__atomic_fetch_or:
5354   case AtomicExpr::AO__atomic_fetch_xor:
5355   case AtomicExpr::AO__atomic_fetch_nand:
5356   case AtomicExpr::AO__atomic_and_fetch:
5357   case AtomicExpr::AO__atomic_or_fetch:
5358   case AtomicExpr::AO__atomic_xor_fetch:
5359   case AtomicExpr::AO__atomic_nand_fetch:
5360     Form = Arithmetic;
5361     break;
5362   case AtomicExpr::AO__c11_atomic_fetch_min:
5363   case AtomicExpr::AO__c11_atomic_fetch_max:
5364   case AtomicExpr::AO__opencl_atomic_fetch_min:
5365   case AtomicExpr::AO__opencl_atomic_fetch_max:
5366   case AtomicExpr::AO__atomic_min_fetch:
5367   case AtomicExpr::AO__atomic_max_fetch:
5368   case AtomicExpr::AO__atomic_fetch_min:
5369   case AtomicExpr::AO__atomic_fetch_max:
5370     Form = Arithmetic;
5371     break;
5372 
5373   case AtomicExpr::AO__c11_atomic_exchange:
5374   case AtomicExpr::AO__opencl_atomic_exchange:
5375   case AtomicExpr::AO__atomic_exchange_n:
5376     Form = Xchg;
5377     break;
5378 
5379   case AtomicExpr::AO__atomic_exchange:
5380     Form = GNUXchg;
5381     break;
5382 
5383   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5384   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5385   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5386   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5387     Form = C11CmpXchg;
5388     break;
5389 
5390   case AtomicExpr::AO__atomic_compare_exchange:
5391   case AtomicExpr::AO__atomic_compare_exchange_n:
5392     Form = GNUCmpXchg;
5393     break;
5394   }
5395 
5396   unsigned AdjustedNumArgs = NumArgs[Form];
5397   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5398     ++AdjustedNumArgs;
5399   // Check we have the right number of arguments.
5400   if (Args.size() < AdjustedNumArgs) {
5401     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5402         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5403         << ExprRange;
5404     return ExprError();
5405   } else if (Args.size() > AdjustedNumArgs) {
5406     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5407          diag::err_typecheck_call_too_many_args)
5408         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5409         << ExprRange;
5410     return ExprError();
5411   }
5412 
5413   // Inspect the first argument of the atomic operation.
5414   Expr *Ptr = Args[0];
5415   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5416   if (ConvertedPtr.isInvalid())
5417     return ExprError();
5418 
5419   Ptr = ConvertedPtr.get();
5420   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5421   if (!pointerType) {
5422     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5423         << Ptr->getType() << Ptr->getSourceRange();
5424     return ExprError();
5425   }
5426 
5427   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5428   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5429   QualType ValType = AtomTy; // 'C'
5430   if (IsC11) {
5431     if (!AtomTy->isAtomicType()) {
5432       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5433           << Ptr->getType() << Ptr->getSourceRange();
5434       return ExprError();
5435     }
5436     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5437         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5438       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5439           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5440           << Ptr->getSourceRange();
5441       return ExprError();
5442     }
5443     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5444   } else if (Form != Load && Form != LoadCopy) {
5445     if (ValType.isConstQualified()) {
5446       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5447           << Ptr->getType() << Ptr->getSourceRange();
5448       return ExprError();
5449     }
5450   }
5451 
5452   // For an arithmetic operation, the implied arithmetic must be well-formed.
5453   if (Form == Arithmetic) {
5454     // gcc does not enforce these rules for GNU atomics, but we do so for
5455     // sanity.
5456     auto IsAllowedValueType = [&](QualType ValType) {
5457       if (ValType->isIntegerType())
5458         return true;
5459       if (ValType->isPointerType())
5460         return true;
5461       if (!ValType->isFloatingType())
5462         return false;
5463       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5464       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5465           &Context.getTargetInfo().getLongDoubleFormat() ==
5466               &llvm::APFloat::x87DoubleExtended())
5467         return false;
5468       return true;
5469     };
5470     if (IsAddSub && !IsAllowedValueType(ValType)) {
5471       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5472           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5473       return ExprError();
5474     }
5475     if (!IsAddSub && !ValType->isIntegerType()) {
5476       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5477           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5478       return ExprError();
5479     }
5480     if (IsC11 && ValType->isPointerType() &&
5481         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5482                             diag::err_incomplete_type)) {
5483       return ExprError();
5484     }
5485   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5486     // For __atomic_*_n operations, the value type must be a scalar integral or
5487     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5488     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5489         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5490     return ExprError();
5491   }
5492 
5493   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5494       !AtomTy->isScalarType()) {
5495     // For GNU atomics, require a trivially-copyable type. This is not part of
5496     // the GNU atomics specification, but we enforce it for sanity.
5497     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5498         << Ptr->getType() << Ptr->getSourceRange();
5499     return ExprError();
5500   }
5501 
5502   switch (ValType.getObjCLifetime()) {
5503   case Qualifiers::OCL_None:
5504   case Qualifiers::OCL_ExplicitNone:
5505     // okay
5506     break;
5507 
5508   case Qualifiers::OCL_Weak:
5509   case Qualifiers::OCL_Strong:
5510   case Qualifiers::OCL_Autoreleasing:
5511     // FIXME: Can this happen? By this point, ValType should be known
5512     // to be trivially copyable.
5513     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5514         << ValType << Ptr->getSourceRange();
5515     return ExprError();
5516   }
5517 
5518   // All atomic operations have an overload which takes a pointer to a volatile
5519   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5520   // into the result or the other operands. Similarly atomic_load takes a
5521   // pointer to a const 'A'.
5522   ValType.removeLocalVolatile();
5523   ValType.removeLocalConst();
5524   QualType ResultType = ValType;
5525   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5526       Form == Init)
5527     ResultType = Context.VoidTy;
5528   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5529     ResultType = Context.BoolTy;
5530 
5531   // The type of a parameter passed 'by value'. In the GNU atomics, such
5532   // arguments are actually passed as pointers.
5533   QualType ByValType = ValType; // 'CP'
5534   bool IsPassedByAddress = false;
5535   if (!IsC11 && !IsN) {
5536     ByValType = Ptr->getType();
5537     IsPassedByAddress = true;
5538   }
5539 
5540   SmallVector<Expr *, 5> APIOrderedArgs;
5541   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5542     APIOrderedArgs.push_back(Args[0]);
5543     switch (Form) {
5544     case Init:
5545     case Load:
5546       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5547       break;
5548     case LoadCopy:
5549     case Copy:
5550     case Arithmetic:
5551     case Xchg:
5552       APIOrderedArgs.push_back(Args[2]); // Val1
5553       APIOrderedArgs.push_back(Args[1]); // Order
5554       break;
5555     case GNUXchg:
5556       APIOrderedArgs.push_back(Args[2]); // Val1
5557       APIOrderedArgs.push_back(Args[3]); // Val2
5558       APIOrderedArgs.push_back(Args[1]); // Order
5559       break;
5560     case C11CmpXchg:
5561       APIOrderedArgs.push_back(Args[2]); // Val1
5562       APIOrderedArgs.push_back(Args[4]); // Val2
5563       APIOrderedArgs.push_back(Args[1]); // Order
5564       APIOrderedArgs.push_back(Args[3]); // OrderFail
5565       break;
5566     case GNUCmpXchg:
5567       APIOrderedArgs.push_back(Args[2]); // Val1
5568       APIOrderedArgs.push_back(Args[4]); // Val2
5569       APIOrderedArgs.push_back(Args[5]); // Weak
5570       APIOrderedArgs.push_back(Args[1]); // Order
5571       APIOrderedArgs.push_back(Args[3]); // OrderFail
5572       break;
5573     }
5574   } else
5575     APIOrderedArgs.append(Args.begin(), Args.end());
5576 
5577   // The first argument's non-CV pointer type is used to deduce the type of
5578   // subsequent arguments, except for:
5579   //  - weak flag (always converted to bool)
5580   //  - memory order (always converted to int)
5581   //  - scope  (always converted to int)
5582   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5583     QualType Ty;
5584     if (i < NumVals[Form] + 1) {
5585       switch (i) {
5586       case 0:
5587         // The first argument is always a pointer. It has a fixed type.
5588         // It is always dereferenced, a nullptr is undefined.
5589         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5590         // Nothing else to do: we already know all we want about this pointer.
5591         continue;
5592       case 1:
5593         // The second argument is the non-atomic operand. For arithmetic, this
5594         // is always passed by value, and for a compare_exchange it is always
5595         // passed by address. For the rest, GNU uses by-address and C11 uses
5596         // by-value.
5597         assert(Form != Load);
5598         if (Form == Arithmetic && ValType->isPointerType())
5599           Ty = Context.getPointerDiffType();
5600         else if (Form == Init || Form == Arithmetic)
5601           Ty = ValType;
5602         else if (Form == Copy || Form == Xchg) {
5603           if (IsPassedByAddress) {
5604             // The value pointer is always dereferenced, a nullptr is undefined.
5605             CheckNonNullArgument(*this, APIOrderedArgs[i],
5606                                  ExprRange.getBegin());
5607           }
5608           Ty = ByValType;
5609         } else {
5610           Expr *ValArg = APIOrderedArgs[i];
5611           // The value pointer is always dereferenced, a nullptr is undefined.
5612           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5613           LangAS AS = LangAS::Default;
5614           // Keep address space of non-atomic pointer type.
5615           if (const PointerType *PtrTy =
5616                   ValArg->getType()->getAs<PointerType>()) {
5617             AS = PtrTy->getPointeeType().getAddressSpace();
5618           }
5619           Ty = Context.getPointerType(
5620               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5621         }
5622         break;
5623       case 2:
5624         // The third argument to compare_exchange / GNU exchange is the desired
5625         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5626         if (IsPassedByAddress)
5627           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5628         Ty = ByValType;
5629         break;
5630       case 3:
5631         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5632         Ty = Context.BoolTy;
5633         break;
5634       }
5635     } else {
5636       // The order(s) and scope are always converted to int.
5637       Ty = Context.IntTy;
5638     }
5639 
5640     InitializedEntity Entity =
5641         InitializedEntity::InitializeParameter(Context, Ty, false);
5642     ExprResult Arg = APIOrderedArgs[i];
5643     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5644     if (Arg.isInvalid())
5645       return true;
5646     APIOrderedArgs[i] = Arg.get();
5647   }
5648 
5649   // Permute the arguments into a 'consistent' order.
5650   SmallVector<Expr*, 5> SubExprs;
5651   SubExprs.push_back(Ptr);
5652   switch (Form) {
5653   case Init:
5654     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5655     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5656     break;
5657   case Load:
5658     SubExprs.push_back(APIOrderedArgs[1]); // Order
5659     break;
5660   case LoadCopy:
5661   case Copy:
5662   case Arithmetic:
5663   case Xchg:
5664     SubExprs.push_back(APIOrderedArgs[2]); // Order
5665     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5666     break;
5667   case GNUXchg:
5668     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5669     SubExprs.push_back(APIOrderedArgs[3]); // Order
5670     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5671     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5672     break;
5673   case C11CmpXchg:
5674     SubExprs.push_back(APIOrderedArgs[3]); // Order
5675     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5676     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5677     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5678     break;
5679   case GNUCmpXchg:
5680     SubExprs.push_back(APIOrderedArgs[4]); // Order
5681     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5682     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5683     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5684     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5685     break;
5686   }
5687 
5688   if (SubExprs.size() >= 2 && Form != Init) {
5689     if (Optional<llvm::APSInt> Result =
5690             SubExprs[1]->getIntegerConstantExpr(Context))
5691       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5692         Diag(SubExprs[1]->getBeginLoc(),
5693              diag::warn_atomic_op_has_invalid_memory_order)
5694             << SubExprs[1]->getSourceRange();
5695   }
5696 
5697   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5698     auto *Scope = Args[Args.size() - 1];
5699     if (Optional<llvm::APSInt> Result =
5700             Scope->getIntegerConstantExpr(Context)) {
5701       if (!ScopeModel->isValid(Result->getZExtValue()))
5702         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5703             << Scope->getSourceRange();
5704     }
5705     SubExprs.push_back(Scope);
5706   }
5707 
5708   AtomicExpr *AE = new (Context)
5709       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5710 
5711   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5712        Op == AtomicExpr::AO__c11_atomic_store ||
5713        Op == AtomicExpr::AO__opencl_atomic_load ||
5714        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5715       Context.AtomicUsesUnsupportedLibcall(AE))
5716     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5717         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5718              Op == AtomicExpr::AO__opencl_atomic_load)
5719                 ? 0
5720                 : 1);
5721 
5722   if (ValType->isExtIntType()) {
5723     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5724     return ExprError();
5725   }
5726 
5727   return AE;
5728 }
5729 
5730 /// checkBuiltinArgument - Given a call to a builtin function, perform
5731 /// normal type-checking on the given argument, updating the call in
5732 /// place.  This is useful when a builtin function requires custom
5733 /// type-checking for some of its arguments but not necessarily all of
5734 /// them.
5735 ///
5736 /// Returns true on error.
5737 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5738   FunctionDecl *Fn = E->getDirectCallee();
5739   assert(Fn && "builtin call without direct callee!");
5740 
5741   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5742   InitializedEntity Entity =
5743     InitializedEntity::InitializeParameter(S.Context, Param);
5744 
5745   ExprResult Arg = E->getArg(0);
5746   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5747   if (Arg.isInvalid())
5748     return true;
5749 
5750   E->setArg(ArgIndex, Arg.get());
5751   return false;
5752 }
5753 
5754 /// We have a call to a function like __sync_fetch_and_add, which is an
5755 /// overloaded function based on the pointer type of its first argument.
5756 /// The main BuildCallExpr routines have already promoted the types of
5757 /// arguments because all of these calls are prototyped as void(...).
5758 ///
5759 /// This function goes through and does final semantic checking for these
5760 /// builtins, as well as generating any warnings.
5761 ExprResult
5762 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5763   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5764   Expr *Callee = TheCall->getCallee();
5765   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5766   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5767 
5768   // Ensure that we have at least one argument to do type inference from.
5769   if (TheCall->getNumArgs() < 1) {
5770     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5771         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5772     return ExprError();
5773   }
5774 
5775   // Inspect the first argument of the atomic builtin.  This should always be
5776   // a pointer type, whose element is an integral scalar or pointer type.
5777   // Because it is a pointer type, we don't have to worry about any implicit
5778   // casts here.
5779   // FIXME: We don't allow floating point scalars as input.
5780   Expr *FirstArg = TheCall->getArg(0);
5781   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5782   if (FirstArgResult.isInvalid())
5783     return ExprError();
5784   FirstArg = FirstArgResult.get();
5785   TheCall->setArg(0, FirstArg);
5786 
5787   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5788   if (!pointerType) {
5789     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5790         << FirstArg->getType() << FirstArg->getSourceRange();
5791     return ExprError();
5792   }
5793 
5794   QualType ValType = pointerType->getPointeeType();
5795   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5796       !ValType->isBlockPointerType()) {
5797     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5798         << FirstArg->getType() << FirstArg->getSourceRange();
5799     return ExprError();
5800   }
5801 
5802   if (ValType.isConstQualified()) {
5803     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5804         << FirstArg->getType() << FirstArg->getSourceRange();
5805     return ExprError();
5806   }
5807 
5808   switch (ValType.getObjCLifetime()) {
5809   case Qualifiers::OCL_None:
5810   case Qualifiers::OCL_ExplicitNone:
5811     // okay
5812     break;
5813 
5814   case Qualifiers::OCL_Weak:
5815   case Qualifiers::OCL_Strong:
5816   case Qualifiers::OCL_Autoreleasing:
5817     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5818         << ValType << FirstArg->getSourceRange();
5819     return ExprError();
5820   }
5821 
5822   // Strip any qualifiers off ValType.
5823   ValType = ValType.getUnqualifiedType();
5824 
5825   // The majority of builtins return a value, but a few have special return
5826   // types, so allow them to override appropriately below.
5827   QualType ResultType = ValType;
5828 
5829   // We need to figure out which concrete builtin this maps onto.  For example,
5830   // __sync_fetch_and_add with a 2 byte object turns into
5831   // __sync_fetch_and_add_2.
5832 #define BUILTIN_ROW(x) \
5833   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5834     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5835 
5836   static const unsigned BuiltinIndices[][5] = {
5837     BUILTIN_ROW(__sync_fetch_and_add),
5838     BUILTIN_ROW(__sync_fetch_and_sub),
5839     BUILTIN_ROW(__sync_fetch_and_or),
5840     BUILTIN_ROW(__sync_fetch_and_and),
5841     BUILTIN_ROW(__sync_fetch_and_xor),
5842     BUILTIN_ROW(__sync_fetch_and_nand),
5843 
5844     BUILTIN_ROW(__sync_add_and_fetch),
5845     BUILTIN_ROW(__sync_sub_and_fetch),
5846     BUILTIN_ROW(__sync_and_and_fetch),
5847     BUILTIN_ROW(__sync_or_and_fetch),
5848     BUILTIN_ROW(__sync_xor_and_fetch),
5849     BUILTIN_ROW(__sync_nand_and_fetch),
5850 
5851     BUILTIN_ROW(__sync_val_compare_and_swap),
5852     BUILTIN_ROW(__sync_bool_compare_and_swap),
5853     BUILTIN_ROW(__sync_lock_test_and_set),
5854     BUILTIN_ROW(__sync_lock_release),
5855     BUILTIN_ROW(__sync_swap)
5856   };
5857 #undef BUILTIN_ROW
5858 
5859   // Determine the index of the size.
5860   unsigned SizeIndex;
5861   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5862   case 1: SizeIndex = 0; break;
5863   case 2: SizeIndex = 1; break;
5864   case 4: SizeIndex = 2; break;
5865   case 8: SizeIndex = 3; break;
5866   case 16: SizeIndex = 4; break;
5867   default:
5868     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5869         << FirstArg->getType() << FirstArg->getSourceRange();
5870     return ExprError();
5871   }
5872 
5873   // Each of these builtins has one pointer argument, followed by some number of
5874   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5875   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5876   // as the number of fixed args.
5877   unsigned BuiltinID = FDecl->getBuiltinID();
5878   unsigned BuiltinIndex, NumFixed = 1;
5879   bool WarnAboutSemanticsChange = false;
5880   switch (BuiltinID) {
5881   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5882   case Builtin::BI__sync_fetch_and_add:
5883   case Builtin::BI__sync_fetch_and_add_1:
5884   case Builtin::BI__sync_fetch_and_add_2:
5885   case Builtin::BI__sync_fetch_and_add_4:
5886   case Builtin::BI__sync_fetch_and_add_8:
5887   case Builtin::BI__sync_fetch_and_add_16:
5888     BuiltinIndex = 0;
5889     break;
5890 
5891   case Builtin::BI__sync_fetch_and_sub:
5892   case Builtin::BI__sync_fetch_and_sub_1:
5893   case Builtin::BI__sync_fetch_and_sub_2:
5894   case Builtin::BI__sync_fetch_and_sub_4:
5895   case Builtin::BI__sync_fetch_and_sub_8:
5896   case Builtin::BI__sync_fetch_and_sub_16:
5897     BuiltinIndex = 1;
5898     break;
5899 
5900   case Builtin::BI__sync_fetch_and_or:
5901   case Builtin::BI__sync_fetch_and_or_1:
5902   case Builtin::BI__sync_fetch_and_or_2:
5903   case Builtin::BI__sync_fetch_and_or_4:
5904   case Builtin::BI__sync_fetch_and_or_8:
5905   case Builtin::BI__sync_fetch_and_or_16:
5906     BuiltinIndex = 2;
5907     break;
5908 
5909   case Builtin::BI__sync_fetch_and_and:
5910   case Builtin::BI__sync_fetch_and_and_1:
5911   case Builtin::BI__sync_fetch_and_and_2:
5912   case Builtin::BI__sync_fetch_and_and_4:
5913   case Builtin::BI__sync_fetch_and_and_8:
5914   case Builtin::BI__sync_fetch_and_and_16:
5915     BuiltinIndex = 3;
5916     break;
5917 
5918   case Builtin::BI__sync_fetch_and_xor:
5919   case Builtin::BI__sync_fetch_and_xor_1:
5920   case Builtin::BI__sync_fetch_and_xor_2:
5921   case Builtin::BI__sync_fetch_and_xor_4:
5922   case Builtin::BI__sync_fetch_and_xor_8:
5923   case Builtin::BI__sync_fetch_and_xor_16:
5924     BuiltinIndex = 4;
5925     break;
5926 
5927   case Builtin::BI__sync_fetch_and_nand:
5928   case Builtin::BI__sync_fetch_and_nand_1:
5929   case Builtin::BI__sync_fetch_and_nand_2:
5930   case Builtin::BI__sync_fetch_and_nand_4:
5931   case Builtin::BI__sync_fetch_and_nand_8:
5932   case Builtin::BI__sync_fetch_and_nand_16:
5933     BuiltinIndex = 5;
5934     WarnAboutSemanticsChange = true;
5935     break;
5936 
5937   case Builtin::BI__sync_add_and_fetch:
5938   case Builtin::BI__sync_add_and_fetch_1:
5939   case Builtin::BI__sync_add_and_fetch_2:
5940   case Builtin::BI__sync_add_and_fetch_4:
5941   case Builtin::BI__sync_add_and_fetch_8:
5942   case Builtin::BI__sync_add_and_fetch_16:
5943     BuiltinIndex = 6;
5944     break;
5945 
5946   case Builtin::BI__sync_sub_and_fetch:
5947   case Builtin::BI__sync_sub_and_fetch_1:
5948   case Builtin::BI__sync_sub_and_fetch_2:
5949   case Builtin::BI__sync_sub_and_fetch_4:
5950   case Builtin::BI__sync_sub_and_fetch_8:
5951   case Builtin::BI__sync_sub_and_fetch_16:
5952     BuiltinIndex = 7;
5953     break;
5954 
5955   case Builtin::BI__sync_and_and_fetch:
5956   case Builtin::BI__sync_and_and_fetch_1:
5957   case Builtin::BI__sync_and_and_fetch_2:
5958   case Builtin::BI__sync_and_and_fetch_4:
5959   case Builtin::BI__sync_and_and_fetch_8:
5960   case Builtin::BI__sync_and_and_fetch_16:
5961     BuiltinIndex = 8;
5962     break;
5963 
5964   case Builtin::BI__sync_or_and_fetch:
5965   case Builtin::BI__sync_or_and_fetch_1:
5966   case Builtin::BI__sync_or_and_fetch_2:
5967   case Builtin::BI__sync_or_and_fetch_4:
5968   case Builtin::BI__sync_or_and_fetch_8:
5969   case Builtin::BI__sync_or_and_fetch_16:
5970     BuiltinIndex = 9;
5971     break;
5972 
5973   case Builtin::BI__sync_xor_and_fetch:
5974   case Builtin::BI__sync_xor_and_fetch_1:
5975   case Builtin::BI__sync_xor_and_fetch_2:
5976   case Builtin::BI__sync_xor_and_fetch_4:
5977   case Builtin::BI__sync_xor_and_fetch_8:
5978   case Builtin::BI__sync_xor_and_fetch_16:
5979     BuiltinIndex = 10;
5980     break;
5981 
5982   case Builtin::BI__sync_nand_and_fetch:
5983   case Builtin::BI__sync_nand_and_fetch_1:
5984   case Builtin::BI__sync_nand_and_fetch_2:
5985   case Builtin::BI__sync_nand_and_fetch_4:
5986   case Builtin::BI__sync_nand_and_fetch_8:
5987   case Builtin::BI__sync_nand_and_fetch_16:
5988     BuiltinIndex = 11;
5989     WarnAboutSemanticsChange = true;
5990     break;
5991 
5992   case Builtin::BI__sync_val_compare_and_swap:
5993   case Builtin::BI__sync_val_compare_and_swap_1:
5994   case Builtin::BI__sync_val_compare_and_swap_2:
5995   case Builtin::BI__sync_val_compare_and_swap_4:
5996   case Builtin::BI__sync_val_compare_and_swap_8:
5997   case Builtin::BI__sync_val_compare_and_swap_16:
5998     BuiltinIndex = 12;
5999     NumFixed = 2;
6000     break;
6001 
6002   case Builtin::BI__sync_bool_compare_and_swap:
6003   case Builtin::BI__sync_bool_compare_and_swap_1:
6004   case Builtin::BI__sync_bool_compare_and_swap_2:
6005   case Builtin::BI__sync_bool_compare_and_swap_4:
6006   case Builtin::BI__sync_bool_compare_and_swap_8:
6007   case Builtin::BI__sync_bool_compare_and_swap_16:
6008     BuiltinIndex = 13;
6009     NumFixed = 2;
6010     ResultType = Context.BoolTy;
6011     break;
6012 
6013   case Builtin::BI__sync_lock_test_and_set:
6014   case Builtin::BI__sync_lock_test_and_set_1:
6015   case Builtin::BI__sync_lock_test_and_set_2:
6016   case Builtin::BI__sync_lock_test_and_set_4:
6017   case Builtin::BI__sync_lock_test_and_set_8:
6018   case Builtin::BI__sync_lock_test_and_set_16:
6019     BuiltinIndex = 14;
6020     break;
6021 
6022   case Builtin::BI__sync_lock_release:
6023   case Builtin::BI__sync_lock_release_1:
6024   case Builtin::BI__sync_lock_release_2:
6025   case Builtin::BI__sync_lock_release_4:
6026   case Builtin::BI__sync_lock_release_8:
6027   case Builtin::BI__sync_lock_release_16:
6028     BuiltinIndex = 15;
6029     NumFixed = 0;
6030     ResultType = Context.VoidTy;
6031     break;
6032 
6033   case Builtin::BI__sync_swap:
6034   case Builtin::BI__sync_swap_1:
6035   case Builtin::BI__sync_swap_2:
6036   case Builtin::BI__sync_swap_4:
6037   case Builtin::BI__sync_swap_8:
6038   case Builtin::BI__sync_swap_16:
6039     BuiltinIndex = 16;
6040     break;
6041   }
6042 
6043   // Now that we know how many fixed arguments we expect, first check that we
6044   // have at least that many.
6045   if (TheCall->getNumArgs() < 1+NumFixed) {
6046     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6047         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6048         << Callee->getSourceRange();
6049     return ExprError();
6050   }
6051 
6052   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6053       << Callee->getSourceRange();
6054 
6055   if (WarnAboutSemanticsChange) {
6056     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6057         << Callee->getSourceRange();
6058   }
6059 
6060   // Get the decl for the concrete builtin from this, we can tell what the
6061   // concrete integer type we should convert to is.
6062   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6063   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6064   FunctionDecl *NewBuiltinDecl;
6065   if (NewBuiltinID == BuiltinID)
6066     NewBuiltinDecl = FDecl;
6067   else {
6068     // Perform builtin lookup to avoid redeclaring it.
6069     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6070     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6071     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6072     assert(Res.getFoundDecl());
6073     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6074     if (!NewBuiltinDecl)
6075       return ExprError();
6076   }
6077 
6078   // The first argument --- the pointer --- has a fixed type; we
6079   // deduce the types of the rest of the arguments accordingly.  Walk
6080   // the remaining arguments, converting them to the deduced value type.
6081   for (unsigned i = 0; i != NumFixed; ++i) {
6082     ExprResult Arg = TheCall->getArg(i+1);
6083 
6084     // GCC does an implicit conversion to the pointer or integer ValType.  This
6085     // can fail in some cases (1i -> int**), check for this error case now.
6086     // Initialize the argument.
6087     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6088                                                    ValType, /*consume*/ false);
6089     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6090     if (Arg.isInvalid())
6091       return ExprError();
6092 
6093     // Okay, we have something that *can* be converted to the right type.  Check
6094     // to see if there is a potentially weird extension going on here.  This can
6095     // happen when you do an atomic operation on something like an char* and
6096     // pass in 42.  The 42 gets converted to char.  This is even more strange
6097     // for things like 45.123 -> char, etc.
6098     // FIXME: Do this check.
6099     TheCall->setArg(i+1, Arg.get());
6100   }
6101 
6102   // Create a new DeclRefExpr to refer to the new decl.
6103   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6104       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6105       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6106       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6107 
6108   // Set the callee in the CallExpr.
6109   // FIXME: This loses syntactic information.
6110   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6111   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6112                                               CK_BuiltinFnToFnPtr);
6113   TheCall->setCallee(PromotedCall.get());
6114 
6115   // Change the result type of the call to match the original value type. This
6116   // is arbitrary, but the codegen for these builtins ins design to handle it
6117   // gracefully.
6118   TheCall->setType(ResultType);
6119 
6120   // Prohibit use of _ExtInt with atomic builtins.
6121   // The arguments would have already been converted to the first argument's
6122   // type, so only need to check the first argument.
6123   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6124   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6125     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6126     return ExprError();
6127   }
6128 
6129   return TheCallResult;
6130 }
6131 
6132 /// SemaBuiltinNontemporalOverloaded - We have a call to
6133 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6134 /// overloaded function based on the pointer type of its last argument.
6135 ///
6136 /// This function goes through and does final semantic checking for these
6137 /// builtins.
6138 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6139   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6140   DeclRefExpr *DRE =
6141       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6142   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6143   unsigned BuiltinID = FDecl->getBuiltinID();
6144   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6145           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6146          "Unexpected nontemporal load/store builtin!");
6147   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6148   unsigned numArgs = isStore ? 2 : 1;
6149 
6150   // Ensure that we have the proper number of arguments.
6151   if (checkArgCount(*this, TheCall, numArgs))
6152     return ExprError();
6153 
6154   // Inspect the last argument of the nontemporal builtin.  This should always
6155   // be a pointer type, from which we imply the type of the memory access.
6156   // Because it is a pointer type, we don't have to worry about any implicit
6157   // casts here.
6158   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6159   ExprResult PointerArgResult =
6160       DefaultFunctionArrayLvalueConversion(PointerArg);
6161 
6162   if (PointerArgResult.isInvalid())
6163     return ExprError();
6164   PointerArg = PointerArgResult.get();
6165   TheCall->setArg(numArgs - 1, PointerArg);
6166 
6167   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6168   if (!pointerType) {
6169     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6170         << PointerArg->getType() << PointerArg->getSourceRange();
6171     return ExprError();
6172   }
6173 
6174   QualType ValType = pointerType->getPointeeType();
6175 
6176   // Strip any qualifiers off ValType.
6177   ValType = ValType.getUnqualifiedType();
6178   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6179       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6180       !ValType->isVectorType()) {
6181     Diag(DRE->getBeginLoc(),
6182          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6183         << PointerArg->getType() << PointerArg->getSourceRange();
6184     return ExprError();
6185   }
6186 
6187   if (!isStore) {
6188     TheCall->setType(ValType);
6189     return TheCallResult;
6190   }
6191 
6192   ExprResult ValArg = TheCall->getArg(0);
6193   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6194       Context, ValType, /*consume*/ false);
6195   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6196   if (ValArg.isInvalid())
6197     return ExprError();
6198 
6199   TheCall->setArg(0, ValArg.get());
6200   TheCall->setType(Context.VoidTy);
6201   return TheCallResult;
6202 }
6203 
6204 /// CheckObjCString - Checks that the argument to the builtin
6205 /// CFString constructor is correct
6206 /// Note: It might also make sense to do the UTF-16 conversion here (would
6207 /// simplify the backend).
6208 bool Sema::CheckObjCString(Expr *Arg) {
6209   Arg = Arg->IgnoreParenCasts();
6210   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6211 
6212   if (!Literal || !Literal->isAscii()) {
6213     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6214         << Arg->getSourceRange();
6215     return true;
6216   }
6217 
6218   if (Literal->containsNonAsciiOrNull()) {
6219     StringRef String = Literal->getString();
6220     unsigned NumBytes = String.size();
6221     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6222     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6223     llvm::UTF16 *ToPtr = &ToBuf[0];
6224 
6225     llvm::ConversionResult Result =
6226         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6227                                  ToPtr + NumBytes, llvm::strictConversion);
6228     // Check for conversion failure.
6229     if (Result != llvm::conversionOK)
6230       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6231           << Arg->getSourceRange();
6232   }
6233   return false;
6234 }
6235 
6236 /// CheckObjCString - Checks that the format string argument to the os_log()
6237 /// and os_trace() functions is correct, and converts it to const char *.
6238 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6239   Arg = Arg->IgnoreParenCasts();
6240   auto *Literal = dyn_cast<StringLiteral>(Arg);
6241   if (!Literal) {
6242     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6243       Literal = ObjcLiteral->getString();
6244     }
6245   }
6246 
6247   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6248     return ExprError(
6249         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6250         << Arg->getSourceRange());
6251   }
6252 
6253   ExprResult Result(Literal);
6254   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6255   InitializedEntity Entity =
6256       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6257   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6258   return Result;
6259 }
6260 
6261 /// Check that the user is calling the appropriate va_start builtin for the
6262 /// target and calling convention.
6263 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6264   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6265   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6266   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6267                     TT.getArch() == llvm::Triple::aarch64_32);
6268   bool IsWindows = TT.isOSWindows();
6269   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6270   if (IsX64 || IsAArch64) {
6271     CallingConv CC = CC_C;
6272     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6273       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6274     if (IsMSVAStart) {
6275       // Don't allow this in System V ABI functions.
6276       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6277         return S.Diag(Fn->getBeginLoc(),
6278                       diag::err_ms_va_start_used_in_sysv_function);
6279     } else {
6280       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6281       // On x64 Windows, don't allow this in System V ABI functions.
6282       // (Yes, that means there's no corresponding way to support variadic
6283       // System V ABI functions on Windows.)
6284       if ((IsWindows && CC == CC_X86_64SysV) ||
6285           (!IsWindows && CC == CC_Win64))
6286         return S.Diag(Fn->getBeginLoc(),
6287                       diag::err_va_start_used_in_wrong_abi_function)
6288                << !IsWindows;
6289     }
6290     return false;
6291   }
6292 
6293   if (IsMSVAStart)
6294     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6295   return false;
6296 }
6297 
6298 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6299                                              ParmVarDecl **LastParam = nullptr) {
6300   // Determine whether the current function, block, or obj-c method is variadic
6301   // and get its parameter list.
6302   bool IsVariadic = false;
6303   ArrayRef<ParmVarDecl *> Params;
6304   DeclContext *Caller = S.CurContext;
6305   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6306     IsVariadic = Block->isVariadic();
6307     Params = Block->parameters();
6308   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6309     IsVariadic = FD->isVariadic();
6310     Params = FD->parameters();
6311   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6312     IsVariadic = MD->isVariadic();
6313     // FIXME: This isn't correct for methods (results in bogus warning).
6314     Params = MD->parameters();
6315   } else if (isa<CapturedDecl>(Caller)) {
6316     // We don't support va_start in a CapturedDecl.
6317     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6318     return true;
6319   } else {
6320     // This must be some other declcontext that parses exprs.
6321     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6322     return true;
6323   }
6324 
6325   if (!IsVariadic) {
6326     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6327     return true;
6328   }
6329 
6330   if (LastParam)
6331     *LastParam = Params.empty() ? nullptr : Params.back();
6332 
6333   return false;
6334 }
6335 
6336 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6337 /// for validity.  Emit an error and return true on failure; return false
6338 /// on success.
6339 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6340   Expr *Fn = TheCall->getCallee();
6341 
6342   if (checkVAStartABI(*this, BuiltinID, Fn))
6343     return true;
6344 
6345   if (checkArgCount(*this, TheCall, 2))
6346     return true;
6347 
6348   // Type-check the first argument normally.
6349   if (checkBuiltinArgument(*this, TheCall, 0))
6350     return true;
6351 
6352   // Check that the current function is variadic, and get its last parameter.
6353   ParmVarDecl *LastParam;
6354   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6355     return true;
6356 
6357   // Verify that the second argument to the builtin is the last argument of the
6358   // current function or method.
6359   bool SecondArgIsLastNamedArgument = false;
6360   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6361 
6362   // These are valid if SecondArgIsLastNamedArgument is false after the next
6363   // block.
6364   QualType Type;
6365   SourceLocation ParamLoc;
6366   bool IsCRegister = false;
6367 
6368   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6369     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6370       SecondArgIsLastNamedArgument = PV == LastParam;
6371 
6372       Type = PV->getType();
6373       ParamLoc = PV->getLocation();
6374       IsCRegister =
6375           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6376     }
6377   }
6378 
6379   if (!SecondArgIsLastNamedArgument)
6380     Diag(TheCall->getArg(1)->getBeginLoc(),
6381          diag::warn_second_arg_of_va_start_not_last_named_param);
6382   else if (IsCRegister || Type->isReferenceType() ||
6383            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6384              // Promotable integers are UB, but enumerations need a bit of
6385              // extra checking to see what their promotable type actually is.
6386              if (!Type->isPromotableIntegerType())
6387                return false;
6388              if (!Type->isEnumeralType())
6389                return true;
6390              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6391              return !(ED &&
6392                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6393            }()) {
6394     unsigned Reason = 0;
6395     if (Type->isReferenceType())  Reason = 1;
6396     else if (IsCRegister)         Reason = 2;
6397     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6398     Diag(ParamLoc, diag::note_parameter_type) << Type;
6399   }
6400 
6401   TheCall->setType(Context.VoidTy);
6402   return false;
6403 }
6404 
6405 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6406   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6407   //                 const char *named_addr);
6408 
6409   Expr *Func = Call->getCallee();
6410 
6411   if (Call->getNumArgs() < 3)
6412     return Diag(Call->getEndLoc(),
6413                 diag::err_typecheck_call_too_few_args_at_least)
6414            << 0 /*function call*/ << 3 << Call->getNumArgs();
6415 
6416   // Type-check the first argument normally.
6417   if (checkBuiltinArgument(*this, Call, 0))
6418     return true;
6419 
6420   // Check that the current function is variadic.
6421   if (checkVAStartIsInVariadicFunction(*this, Func))
6422     return true;
6423 
6424   // __va_start on Windows does not validate the parameter qualifiers
6425 
6426   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6427   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6428 
6429   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6430   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6431 
6432   const QualType &ConstCharPtrTy =
6433       Context.getPointerType(Context.CharTy.withConst());
6434   if (!Arg1Ty->isPointerType() ||
6435       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6436     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6437         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6438         << 0                                      /* qualifier difference */
6439         << 3                                      /* parameter mismatch */
6440         << 2 << Arg1->getType() << ConstCharPtrTy;
6441 
6442   const QualType SizeTy = Context.getSizeType();
6443   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6444     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6445         << Arg2->getType() << SizeTy << 1 /* different class */
6446         << 0                              /* qualifier difference */
6447         << 3                              /* parameter mismatch */
6448         << 3 << Arg2->getType() << SizeTy;
6449 
6450   return false;
6451 }
6452 
6453 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6454 /// friends.  This is declared to take (...), so we have to check everything.
6455 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6456   if (checkArgCount(*this, TheCall, 2))
6457     return true;
6458 
6459   ExprResult OrigArg0 = TheCall->getArg(0);
6460   ExprResult OrigArg1 = TheCall->getArg(1);
6461 
6462   // Do standard promotions between the two arguments, returning their common
6463   // type.
6464   QualType Res = UsualArithmeticConversions(
6465       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6466   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6467     return true;
6468 
6469   // Make sure any conversions are pushed back into the call; this is
6470   // type safe since unordered compare builtins are declared as "_Bool
6471   // foo(...)".
6472   TheCall->setArg(0, OrigArg0.get());
6473   TheCall->setArg(1, OrigArg1.get());
6474 
6475   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6476     return false;
6477 
6478   // If the common type isn't a real floating type, then the arguments were
6479   // invalid for this operation.
6480   if (Res.isNull() || !Res->isRealFloatingType())
6481     return Diag(OrigArg0.get()->getBeginLoc(),
6482                 diag::err_typecheck_call_invalid_ordered_compare)
6483            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6484            << SourceRange(OrigArg0.get()->getBeginLoc(),
6485                           OrigArg1.get()->getEndLoc());
6486 
6487   return false;
6488 }
6489 
6490 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6491 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6492 /// to check everything. We expect the last argument to be a floating point
6493 /// value.
6494 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6495   if (checkArgCount(*this, TheCall, NumArgs))
6496     return true;
6497 
6498   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6499   // on all preceding parameters just being int.  Try all of those.
6500   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6501     Expr *Arg = TheCall->getArg(i);
6502 
6503     if (Arg->isTypeDependent())
6504       return false;
6505 
6506     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6507 
6508     if (Res.isInvalid())
6509       return true;
6510     TheCall->setArg(i, Res.get());
6511   }
6512 
6513   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6514 
6515   if (OrigArg->isTypeDependent())
6516     return false;
6517 
6518   // Usual Unary Conversions will convert half to float, which we want for
6519   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6520   // type how it is, but do normal L->Rvalue conversions.
6521   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6522     OrigArg = UsualUnaryConversions(OrigArg).get();
6523   else
6524     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6525   TheCall->setArg(NumArgs - 1, OrigArg);
6526 
6527   // This operation requires a non-_Complex floating-point number.
6528   if (!OrigArg->getType()->isRealFloatingType())
6529     return Diag(OrigArg->getBeginLoc(),
6530                 diag::err_typecheck_call_invalid_unary_fp)
6531            << OrigArg->getType() << OrigArg->getSourceRange();
6532 
6533   return false;
6534 }
6535 
6536 /// Perform semantic analysis for a call to __builtin_complex.
6537 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6538   if (checkArgCount(*this, TheCall, 2))
6539     return true;
6540 
6541   bool Dependent = false;
6542   for (unsigned I = 0; I != 2; ++I) {
6543     Expr *Arg = TheCall->getArg(I);
6544     QualType T = Arg->getType();
6545     if (T->isDependentType()) {
6546       Dependent = true;
6547       continue;
6548     }
6549 
6550     // Despite supporting _Complex int, GCC requires a real floating point type
6551     // for the operands of __builtin_complex.
6552     if (!T->isRealFloatingType()) {
6553       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6554              << Arg->getType() << Arg->getSourceRange();
6555     }
6556 
6557     ExprResult Converted = DefaultLvalueConversion(Arg);
6558     if (Converted.isInvalid())
6559       return true;
6560     TheCall->setArg(I, Converted.get());
6561   }
6562 
6563   if (Dependent) {
6564     TheCall->setType(Context.DependentTy);
6565     return false;
6566   }
6567 
6568   Expr *Real = TheCall->getArg(0);
6569   Expr *Imag = TheCall->getArg(1);
6570   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6571     return Diag(Real->getBeginLoc(),
6572                 diag::err_typecheck_call_different_arg_types)
6573            << Real->getType() << Imag->getType()
6574            << Real->getSourceRange() << Imag->getSourceRange();
6575   }
6576 
6577   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6578   // don't allow this builtin to form those types either.
6579   // FIXME: Should we allow these types?
6580   if (Real->getType()->isFloat16Type())
6581     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6582            << "_Float16";
6583   if (Real->getType()->isHalfType())
6584     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6585            << "half";
6586 
6587   TheCall->setType(Context.getComplexType(Real->getType()));
6588   return false;
6589 }
6590 
6591 // Customized Sema Checking for VSX builtins that have the following signature:
6592 // vector [...] builtinName(vector [...], vector [...], const int);
6593 // Which takes the same type of vectors (any legal vector type) for the first
6594 // two arguments and takes compile time constant for the third argument.
6595 // Example builtins are :
6596 // vector double vec_xxpermdi(vector double, vector double, int);
6597 // vector short vec_xxsldwi(vector short, vector short, int);
6598 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6599   unsigned ExpectedNumArgs = 3;
6600   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6601     return true;
6602 
6603   // Check the third argument is a compile time constant
6604   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6605     return Diag(TheCall->getBeginLoc(),
6606                 diag::err_vsx_builtin_nonconstant_argument)
6607            << 3 /* argument index */ << TheCall->getDirectCallee()
6608            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6609                           TheCall->getArg(2)->getEndLoc());
6610 
6611   QualType Arg1Ty = TheCall->getArg(0)->getType();
6612   QualType Arg2Ty = TheCall->getArg(1)->getType();
6613 
6614   // Check the type of argument 1 and argument 2 are vectors.
6615   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6616   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6617       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6618     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6619            << TheCall->getDirectCallee()
6620            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6621                           TheCall->getArg(1)->getEndLoc());
6622   }
6623 
6624   // Check the first two arguments are the same type.
6625   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6626     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6627            << TheCall->getDirectCallee()
6628            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6629                           TheCall->getArg(1)->getEndLoc());
6630   }
6631 
6632   // When default clang type checking is turned off and the customized type
6633   // checking is used, the returning type of the function must be explicitly
6634   // set. Otherwise it is _Bool by default.
6635   TheCall->setType(Arg1Ty);
6636 
6637   return false;
6638 }
6639 
6640 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6641 // This is declared to take (...), so we have to check everything.
6642 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6643   if (TheCall->getNumArgs() < 2)
6644     return ExprError(Diag(TheCall->getEndLoc(),
6645                           diag::err_typecheck_call_too_few_args_at_least)
6646                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6647                      << TheCall->getSourceRange());
6648 
6649   // Determine which of the following types of shufflevector we're checking:
6650   // 1) unary, vector mask: (lhs, mask)
6651   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6652   QualType resType = TheCall->getArg(0)->getType();
6653   unsigned numElements = 0;
6654 
6655   if (!TheCall->getArg(0)->isTypeDependent() &&
6656       !TheCall->getArg(1)->isTypeDependent()) {
6657     QualType LHSType = TheCall->getArg(0)->getType();
6658     QualType RHSType = TheCall->getArg(1)->getType();
6659 
6660     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6661       return ExprError(
6662           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6663           << TheCall->getDirectCallee()
6664           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6665                          TheCall->getArg(1)->getEndLoc()));
6666 
6667     numElements = LHSType->castAs<VectorType>()->getNumElements();
6668     unsigned numResElements = TheCall->getNumArgs() - 2;
6669 
6670     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6671     // with mask.  If so, verify that RHS is an integer vector type with the
6672     // same number of elts as lhs.
6673     if (TheCall->getNumArgs() == 2) {
6674       if (!RHSType->hasIntegerRepresentation() ||
6675           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6676         return ExprError(Diag(TheCall->getBeginLoc(),
6677                               diag::err_vec_builtin_incompatible_vector)
6678                          << TheCall->getDirectCallee()
6679                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6680                                         TheCall->getArg(1)->getEndLoc()));
6681     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6682       return ExprError(Diag(TheCall->getBeginLoc(),
6683                             diag::err_vec_builtin_incompatible_vector)
6684                        << TheCall->getDirectCallee()
6685                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6686                                       TheCall->getArg(1)->getEndLoc()));
6687     } else if (numElements != numResElements) {
6688       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6689       resType = Context.getVectorType(eltType, numResElements,
6690                                       VectorType::GenericVector);
6691     }
6692   }
6693 
6694   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6695     if (TheCall->getArg(i)->isTypeDependent() ||
6696         TheCall->getArg(i)->isValueDependent())
6697       continue;
6698 
6699     Optional<llvm::APSInt> Result;
6700     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6701       return ExprError(Diag(TheCall->getBeginLoc(),
6702                             diag::err_shufflevector_nonconstant_argument)
6703                        << TheCall->getArg(i)->getSourceRange());
6704 
6705     // Allow -1 which will be translated to undef in the IR.
6706     if (Result->isSigned() && Result->isAllOnesValue())
6707       continue;
6708 
6709     if (Result->getActiveBits() > 64 ||
6710         Result->getZExtValue() >= numElements * 2)
6711       return ExprError(Diag(TheCall->getBeginLoc(),
6712                             diag::err_shufflevector_argument_too_large)
6713                        << TheCall->getArg(i)->getSourceRange());
6714   }
6715 
6716   SmallVector<Expr*, 32> exprs;
6717 
6718   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6719     exprs.push_back(TheCall->getArg(i));
6720     TheCall->setArg(i, nullptr);
6721   }
6722 
6723   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6724                                          TheCall->getCallee()->getBeginLoc(),
6725                                          TheCall->getRParenLoc());
6726 }
6727 
6728 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6729 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6730                                        SourceLocation BuiltinLoc,
6731                                        SourceLocation RParenLoc) {
6732   ExprValueKind VK = VK_PRValue;
6733   ExprObjectKind OK = OK_Ordinary;
6734   QualType DstTy = TInfo->getType();
6735   QualType SrcTy = E->getType();
6736 
6737   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6738     return ExprError(Diag(BuiltinLoc,
6739                           diag::err_convertvector_non_vector)
6740                      << E->getSourceRange());
6741   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6742     return ExprError(Diag(BuiltinLoc,
6743                           diag::err_convertvector_non_vector_type));
6744 
6745   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6746     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6747     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6748     if (SrcElts != DstElts)
6749       return ExprError(Diag(BuiltinLoc,
6750                             diag::err_convertvector_incompatible_vector)
6751                        << E->getSourceRange());
6752   }
6753 
6754   return new (Context)
6755       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6756 }
6757 
6758 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6759 // This is declared to take (const void*, ...) and can take two
6760 // optional constant int args.
6761 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6762   unsigned NumArgs = TheCall->getNumArgs();
6763 
6764   if (NumArgs > 3)
6765     return Diag(TheCall->getEndLoc(),
6766                 diag::err_typecheck_call_too_many_args_at_most)
6767            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6768 
6769   // Argument 0 is checked for us and the remaining arguments must be
6770   // constant integers.
6771   for (unsigned i = 1; i != NumArgs; ++i)
6772     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6773       return true;
6774 
6775   return false;
6776 }
6777 
6778 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6779 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6780   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6781     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6782            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6783   if (checkArgCount(*this, TheCall, 1))
6784     return true;
6785   Expr *Arg = TheCall->getArg(0);
6786   if (Arg->isInstantiationDependent())
6787     return false;
6788 
6789   QualType ArgTy = Arg->getType();
6790   if (!ArgTy->hasFloatingRepresentation())
6791     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6792            << ArgTy;
6793   if (Arg->isLValue()) {
6794     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6795     TheCall->setArg(0, FirstArg.get());
6796   }
6797   TheCall->setType(TheCall->getArg(0)->getType());
6798   return false;
6799 }
6800 
6801 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6802 // __assume does not evaluate its arguments, and should warn if its argument
6803 // has side effects.
6804 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6805   Expr *Arg = TheCall->getArg(0);
6806   if (Arg->isInstantiationDependent()) return false;
6807 
6808   if (Arg->HasSideEffects(Context))
6809     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6810         << Arg->getSourceRange()
6811         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6812 
6813   return false;
6814 }
6815 
6816 /// Handle __builtin_alloca_with_align. This is declared
6817 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6818 /// than 8.
6819 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6820   // The alignment must be a constant integer.
6821   Expr *Arg = TheCall->getArg(1);
6822 
6823   // We can't check the value of a dependent argument.
6824   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6825     if (const auto *UE =
6826             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6827       if (UE->getKind() == UETT_AlignOf ||
6828           UE->getKind() == UETT_PreferredAlignOf)
6829         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6830             << Arg->getSourceRange();
6831 
6832     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6833 
6834     if (!Result.isPowerOf2())
6835       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6836              << Arg->getSourceRange();
6837 
6838     if (Result < Context.getCharWidth())
6839       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6840              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6841 
6842     if (Result > std::numeric_limits<int32_t>::max())
6843       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6844              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6845   }
6846 
6847   return false;
6848 }
6849 
6850 /// Handle __builtin_assume_aligned. This is declared
6851 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6852 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6853   unsigned NumArgs = TheCall->getNumArgs();
6854 
6855   if (NumArgs > 3)
6856     return Diag(TheCall->getEndLoc(),
6857                 diag::err_typecheck_call_too_many_args_at_most)
6858            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6859 
6860   // The alignment must be a constant integer.
6861   Expr *Arg = TheCall->getArg(1);
6862 
6863   // We can't check the value of a dependent argument.
6864   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6865     llvm::APSInt Result;
6866     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6867       return true;
6868 
6869     if (!Result.isPowerOf2())
6870       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6871              << Arg->getSourceRange();
6872 
6873     if (Result > Sema::MaximumAlignment)
6874       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6875           << Arg->getSourceRange() << Sema::MaximumAlignment;
6876   }
6877 
6878   if (NumArgs > 2) {
6879     ExprResult Arg(TheCall->getArg(2));
6880     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6881       Context.getSizeType(), false);
6882     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6883     if (Arg.isInvalid()) return true;
6884     TheCall->setArg(2, Arg.get());
6885   }
6886 
6887   return false;
6888 }
6889 
6890 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6891   unsigned BuiltinID =
6892       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6893   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6894 
6895   unsigned NumArgs = TheCall->getNumArgs();
6896   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6897   if (NumArgs < NumRequiredArgs) {
6898     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6899            << 0 /* function call */ << NumRequiredArgs << NumArgs
6900            << TheCall->getSourceRange();
6901   }
6902   if (NumArgs >= NumRequiredArgs + 0x100) {
6903     return Diag(TheCall->getEndLoc(),
6904                 diag::err_typecheck_call_too_many_args_at_most)
6905            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6906            << TheCall->getSourceRange();
6907   }
6908   unsigned i = 0;
6909 
6910   // For formatting call, check buffer arg.
6911   if (!IsSizeCall) {
6912     ExprResult Arg(TheCall->getArg(i));
6913     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6914         Context, Context.VoidPtrTy, false);
6915     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6916     if (Arg.isInvalid())
6917       return true;
6918     TheCall->setArg(i, Arg.get());
6919     i++;
6920   }
6921 
6922   // Check string literal arg.
6923   unsigned FormatIdx = i;
6924   {
6925     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6926     if (Arg.isInvalid())
6927       return true;
6928     TheCall->setArg(i, Arg.get());
6929     i++;
6930   }
6931 
6932   // Make sure variadic args are scalar.
6933   unsigned FirstDataArg = i;
6934   while (i < NumArgs) {
6935     ExprResult Arg = DefaultVariadicArgumentPromotion(
6936         TheCall->getArg(i), VariadicFunction, nullptr);
6937     if (Arg.isInvalid())
6938       return true;
6939     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6940     if (ArgSize.getQuantity() >= 0x100) {
6941       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6942              << i << (int)ArgSize.getQuantity() << 0xff
6943              << TheCall->getSourceRange();
6944     }
6945     TheCall->setArg(i, Arg.get());
6946     i++;
6947   }
6948 
6949   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6950   // call to avoid duplicate diagnostics.
6951   if (!IsSizeCall) {
6952     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6953     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6954     bool Success = CheckFormatArguments(
6955         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6956         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6957         CheckedVarArgs);
6958     if (!Success)
6959       return true;
6960   }
6961 
6962   if (IsSizeCall) {
6963     TheCall->setType(Context.getSizeType());
6964   } else {
6965     TheCall->setType(Context.VoidPtrTy);
6966   }
6967   return false;
6968 }
6969 
6970 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6971 /// TheCall is a constant expression.
6972 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6973                                   llvm::APSInt &Result) {
6974   Expr *Arg = TheCall->getArg(ArgNum);
6975   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6976   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6977 
6978   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6979 
6980   Optional<llvm::APSInt> R;
6981   if (!(R = Arg->getIntegerConstantExpr(Context)))
6982     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6983            << FDecl->getDeclName() << Arg->getSourceRange();
6984   Result = *R;
6985   return false;
6986 }
6987 
6988 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6989 /// TheCall is a constant expression in the range [Low, High].
6990 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6991                                        int Low, int High, bool RangeIsError) {
6992   if (isConstantEvaluated())
6993     return false;
6994   llvm::APSInt Result;
6995 
6996   // We can't check the value of a dependent argument.
6997   Expr *Arg = TheCall->getArg(ArgNum);
6998   if (Arg->isTypeDependent() || Arg->isValueDependent())
6999     return false;
7000 
7001   // Check constant-ness first.
7002   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7003     return true;
7004 
7005   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
7006     if (RangeIsError)
7007       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
7008              << toString(Result, 10) << Low << High << Arg->getSourceRange();
7009     else
7010       // Defer the warning until we know if the code will be emitted so that
7011       // dead code can ignore this.
7012       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
7013                           PDiag(diag::warn_argument_invalid_range)
7014                               << toString(Result, 10) << Low << High
7015                               << Arg->getSourceRange());
7016   }
7017 
7018   return false;
7019 }
7020 
7021 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
7022 /// TheCall is a constant expression is a multiple of Num..
7023 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
7024                                           unsigned Num) {
7025   llvm::APSInt Result;
7026 
7027   // We can't check the value of a dependent argument.
7028   Expr *Arg = TheCall->getArg(ArgNum);
7029   if (Arg->isTypeDependent() || Arg->isValueDependent())
7030     return false;
7031 
7032   // Check constant-ness first.
7033   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7034     return true;
7035 
7036   if (Result.getSExtValue() % Num != 0)
7037     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7038            << Num << Arg->getSourceRange();
7039 
7040   return false;
7041 }
7042 
7043 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7044 /// constant expression representing a power of 2.
7045 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7046   llvm::APSInt Result;
7047 
7048   // We can't check the value of a dependent argument.
7049   Expr *Arg = TheCall->getArg(ArgNum);
7050   if (Arg->isTypeDependent() || Arg->isValueDependent())
7051     return false;
7052 
7053   // Check constant-ness first.
7054   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7055     return true;
7056 
7057   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7058   // and only if x is a power of 2.
7059   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7060     return false;
7061 
7062   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7063          << Arg->getSourceRange();
7064 }
7065 
7066 static bool IsShiftedByte(llvm::APSInt Value) {
7067   if (Value.isNegative())
7068     return false;
7069 
7070   // Check if it's a shifted byte, by shifting it down
7071   while (true) {
7072     // If the value fits in the bottom byte, the check passes.
7073     if (Value < 0x100)
7074       return true;
7075 
7076     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7077     // fails.
7078     if ((Value & 0xFF) != 0)
7079       return false;
7080 
7081     // If the bottom 8 bits are all 0, but something above that is nonzero,
7082     // then shifting the value right by 8 bits won't affect whether it's a
7083     // shifted byte or not. So do that, and go round again.
7084     Value >>= 8;
7085   }
7086 }
7087 
7088 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7089 /// a constant expression representing an arbitrary byte value shifted left by
7090 /// a multiple of 8 bits.
7091 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7092                                              unsigned ArgBits) {
7093   llvm::APSInt Result;
7094 
7095   // We can't check the value of a dependent argument.
7096   Expr *Arg = TheCall->getArg(ArgNum);
7097   if (Arg->isTypeDependent() || Arg->isValueDependent())
7098     return false;
7099 
7100   // Check constant-ness first.
7101   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7102     return true;
7103 
7104   // Truncate to the given size.
7105   Result = Result.getLoBits(ArgBits);
7106   Result.setIsUnsigned(true);
7107 
7108   if (IsShiftedByte(Result))
7109     return false;
7110 
7111   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7112          << Arg->getSourceRange();
7113 }
7114 
7115 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7116 /// TheCall is a constant expression representing either a shifted byte value,
7117 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7118 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7119 /// Arm MVE intrinsics.
7120 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7121                                                    int ArgNum,
7122                                                    unsigned ArgBits) {
7123   llvm::APSInt Result;
7124 
7125   // We can't check the value of a dependent argument.
7126   Expr *Arg = TheCall->getArg(ArgNum);
7127   if (Arg->isTypeDependent() || Arg->isValueDependent())
7128     return false;
7129 
7130   // Check constant-ness first.
7131   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7132     return true;
7133 
7134   // Truncate to the given size.
7135   Result = Result.getLoBits(ArgBits);
7136   Result.setIsUnsigned(true);
7137 
7138   // Check to see if it's in either of the required forms.
7139   if (IsShiftedByte(Result) ||
7140       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7141     return false;
7142 
7143   return Diag(TheCall->getBeginLoc(),
7144               diag::err_argument_not_shifted_byte_or_xxff)
7145          << Arg->getSourceRange();
7146 }
7147 
7148 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7149 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7150   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7151     if (checkArgCount(*this, TheCall, 2))
7152       return true;
7153     Expr *Arg0 = TheCall->getArg(0);
7154     Expr *Arg1 = TheCall->getArg(1);
7155 
7156     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7157     if (FirstArg.isInvalid())
7158       return true;
7159     QualType FirstArgType = FirstArg.get()->getType();
7160     if (!FirstArgType->isAnyPointerType())
7161       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7162                << "first" << FirstArgType << Arg0->getSourceRange();
7163     TheCall->setArg(0, FirstArg.get());
7164 
7165     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7166     if (SecArg.isInvalid())
7167       return true;
7168     QualType SecArgType = SecArg.get()->getType();
7169     if (!SecArgType->isIntegerType())
7170       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7171                << "second" << SecArgType << Arg1->getSourceRange();
7172 
7173     // Derive the return type from the pointer argument.
7174     TheCall->setType(FirstArgType);
7175     return false;
7176   }
7177 
7178   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7179     if (checkArgCount(*this, TheCall, 2))
7180       return true;
7181 
7182     Expr *Arg0 = TheCall->getArg(0);
7183     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7184     if (FirstArg.isInvalid())
7185       return true;
7186     QualType FirstArgType = FirstArg.get()->getType();
7187     if (!FirstArgType->isAnyPointerType())
7188       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7189                << "first" << FirstArgType << Arg0->getSourceRange();
7190     TheCall->setArg(0, FirstArg.get());
7191 
7192     // Derive the return type from the pointer argument.
7193     TheCall->setType(FirstArgType);
7194 
7195     // Second arg must be an constant in range [0,15]
7196     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7197   }
7198 
7199   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7200     if (checkArgCount(*this, TheCall, 2))
7201       return true;
7202     Expr *Arg0 = TheCall->getArg(0);
7203     Expr *Arg1 = TheCall->getArg(1);
7204 
7205     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7206     if (FirstArg.isInvalid())
7207       return true;
7208     QualType FirstArgType = FirstArg.get()->getType();
7209     if (!FirstArgType->isAnyPointerType())
7210       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7211                << "first" << FirstArgType << Arg0->getSourceRange();
7212 
7213     QualType SecArgType = Arg1->getType();
7214     if (!SecArgType->isIntegerType())
7215       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7216                << "second" << SecArgType << Arg1->getSourceRange();
7217     TheCall->setType(Context.IntTy);
7218     return false;
7219   }
7220 
7221   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7222       BuiltinID == AArch64::BI__builtin_arm_stg) {
7223     if (checkArgCount(*this, TheCall, 1))
7224       return true;
7225     Expr *Arg0 = TheCall->getArg(0);
7226     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7227     if (FirstArg.isInvalid())
7228       return true;
7229 
7230     QualType FirstArgType = FirstArg.get()->getType();
7231     if (!FirstArgType->isAnyPointerType())
7232       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7233                << "first" << FirstArgType << Arg0->getSourceRange();
7234     TheCall->setArg(0, FirstArg.get());
7235 
7236     // Derive the return type from the pointer argument.
7237     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7238       TheCall->setType(FirstArgType);
7239     return false;
7240   }
7241 
7242   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7243     Expr *ArgA = TheCall->getArg(0);
7244     Expr *ArgB = TheCall->getArg(1);
7245 
7246     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7247     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7248 
7249     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7250       return true;
7251 
7252     QualType ArgTypeA = ArgExprA.get()->getType();
7253     QualType ArgTypeB = ArgExprB.get()->getType();
7254 
7255     auto isNull = [&] (Expr *E) -> bool {
7256       return E->isNullPointerConstant(
7257                         Context, Expr::NPC_ValueDependentIsNotNull); };
7258 
7259     // argument should be either a pointer or null
7260     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7261       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7262         << "first" << ArgTypeA << ArgA->getSourceRange();
7263 
7264     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7265       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7266         << "second" << ArgTypeB << ArgB->getSourceRange();
7267 
7268     // Ensure Pointee types are compatible
7269     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7270         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7271       QualType pointeeA = ArgTypeA->getPointeeType();
7272       QualType pointeeB = ArgTypeB->getPointeeType();
7273       if (!Context.typesAreCompatible(
7274              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7275              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7276         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7277           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7278           << ArgB->getSourceRange();
7279       }
7280     }
7281 
7282     // at least one argument should be pointer type
7283     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7284       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7285         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7286 
7287     if (isNull(ArgA)) // adopt type of the other pointer
7288       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7289 
7290     if (isNull(ArgB))
7291       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7292 
7293     TheCall->setArg(0, ArgExprA.get());
7294     TheCall->setArg(1, ArgExprB.get());
7295     TheCall->setType(Context.LongLongTy);
7296     return false;
7297   }
7298   assert(false && "Unhandled ARM MTE intrinsic");
7299   return true;
7300 }
7301 
7302 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7303 /// TheCall is an ARM/AArch64 special register string literal.
7304 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7305                                     int ArgNum, unsigned ExpectedFieldNum,
7306                                     bool AllowName) {
7307   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7308                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7309                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7310                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7311                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7312                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7313   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7314                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7315                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7316                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7317                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7318                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7319   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7320 
7321   // We can't check the value of a dependent argument.
7322   Expr *Arg = TheCall->getArg(ArgNum);
7323   if (Arg->isTypeDependent() || Arg->isValueDependent())
7324     return false;
7325 
7326   // Check if the argument is a string literal.
7327   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7328     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7329            << Arg->getSourceRange();
7330 
7331   // Check the type of special register given.
7332   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7333   SmallVector<StringRef, 6> Fields;
7334   Reg.split(Fields, ":");
7335 
7336   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7337     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7338            << Arg->getSourceRange();
7339 
7340   // If the string is the name of a register then we cannot check that it is
7341   // valid here but if the string is of one the forms described in ACLE then we
7342   // can check that the supplied fields are integers and within the valid
7343   // ranges.
7344   if (Fields.size() > 1) {
7345     bool FiveFields = Fields.size() == 5;
7346 
7347     bool ValidString = true;
7348     if (IsARMBuiltin) {
7349       ValidString &= Fields[0].startswith_insensitive("cp") ||
7350                      Fields[0].startswith_insensitive("p");
7351       if (ValidString)
7352         Fields[0] = Fields[0].drop_front(
7353             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7354 
7355       ValidString &= Fields[2].startswith_insensitive("c");
7356       if (ValidString)
7357         Fields[2] = Fields[2].drop_front(1);
7358 
7359       if (FiveFields) {
7360         ValidString &= Fields[3].startswith_insensitive("c");
7361         if (ValidString)
7362           Fields[3] = Fields[3].drop_front(1);
7363       }
7364     }
7365 
7366     SmallVector<int, 5> Ranges;
7367     if (FiveFields)
7368       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7369     else
7370       Ranges.append({15, 7, 15});
7371 
7372     for (unsigned i=0; i<Fields.size(); ++i) {
7373       int IntField;
7374       ValidString &= !Fields[i].getAsInteger(10, IntField);
7375       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7376     }
7377 
7378     if (!ValidString)
7379       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7380              << Arg->getSourceRange();
7381   } else if (IsAArch64Builtin && Fields.size() == 1) {
7382     // If the register name is one of those that appear in the condition below
7383     // and the special register builtin being used is one of the write builtins,
7384     // then we require that the argument provided for writing to the register
7385     // is an integer constant expression. This is because it will be lowered to
7386     // an MSR (immediate) instruction, so we need to know the immediate at
7387     // compile time.
7388     if (TheCall->getNumArgs() != 2)
7389       return false;
7390 
7391     std::string RegLower = Reg.lower();
7392     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7393         RegLower != "pan" && RegLower != "uao")
7394       return false;
7395 
7396     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7397   }
7398 
7399   return false;
7400 }
7401 
7402 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7403 /// Emit an error and return true on failure; return false on success.
7404 /// TypeStr is a string containing the type descriptor of the value returned by
7405 /// the builtin and the descriptors of the expected type of the arguments.
7406 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7407 
7408   assert((TypeStr[0] != '\0') &&
7409          "Invalid types in PPC MMA builtin declaration");
7410 
7411   unsigned Mask = 0;
7412   unsigned ArgNum = 0;
7413 
7414   // The first type in TypeStr is the type of the value returned by the
7415   // builtin. So we first read that type and change the type of TheCall.
7416   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7417   TheCall->setType(type);
7418 
7419   while (*TypeStr != '\0') {
7420     Mask = 0;
7421     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7422     if (ArgNum >= TheCall->getNumArgs()) {
7423       ArgNum++;
7424       break;
7425     }
7426 
7427     Expr *Arg = TheCall->getArg(ArgNum);
7428     QualType ArgType = Arg->getType();
7429 
7430     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7431         (!ExpectedType->isVoidPointerType() &&
7432            ArgType.getCanonicalType() != ExpectedType))
7433       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7434              << ArgType << ExpectedType << 1 << 0 << 0;
7435 
7436     // If the value of the Mask is not 0, we have a constraint in the size of
7437     // the integer argument so here we ensure the argument is a constant that
7438     // is in the valid range.
7439     if (Mask != 0 &&
7440         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7441       return true;
7442 
7443     ArgNum++;
7444   }
7445 
7446   // In case we exited early from the previous loop, there are other types to
7447   // read from TypeStr. So we need to read them all to ensure we have the right
7448   // number of arguments in TheCall and if it is not the case, to display a
7449   // better error message.
7450   while (*TypeStr != '\0') {
7451     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7452     ArgNum++;
7453   }
7454   if (checkArgCount(*this, TheCall, ArgNum))
7455     return true;
7456 
7457   return false;
7458 }
7459 
7460 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7461 /// This checks that the target supports __builtin_longjmp and
7462 /// that val is a constant 1.
7463 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7464   if (!Context.getTargetInfo().hasSjLjLowering())
7465     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7466            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7467 
7468   Expr *Arg = TheCall->getArg(1);
7469   llvm::APSInt Result;
7470 
7471   // TODO: This is less than ideal. Overload this to take a value.
7472   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7473     return true;
7474 
7475   if (Result != 1)
7476     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7477            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7478 
7479   return false;
7480 }
7481 
7482 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7483 /// This checks that the target supports __builtin_setjmp.
7484 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7485   if (!Context.getTargetInfo().hasSjLjLowering())
7486     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7487            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7488   return false;
7489 }
7490 
7491 namespace {
7492 
7493 class UncoveredArgHandler {
7494   enum { Unknown = -1, AllCovered = -2 };
7495 
7496   signed FirstUncoveredArg = Unknown;
7497   SmallVector<const Expr *, 4> DiagnosticExprs;
7498 
7499 public:
7500   UncoveredArgHandler() = default;
7501 
7502   bool hasUncoveredArg() const {
7503     return (FirstUncoveredArg >= 0);
7504   }
7505 
7506   unsigned getUncoveredArg() const {
7507     assert(hasUncoveredArg() && "no uncovered argument");
7508     return FirstUncoveredArg;
7509   }
7510 
7511   void setAllCovered() {
7512     // A string has been found with all arguments covered, so clear out
7513     // the diagnostics.
7514     DiagnosticExprs.clear();
7515     FirstUncoveredArg = AllCovered;
7516   }
7517 
7518   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7519     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7520 
7521     // Don't update if a previous string covers all arguments.
7522     if (FirstUncoveredArg == AllCovered)
7523       return;
7524 
7525     // UncoveredArgHandler tracks the highest uncovered argument index
7526     // and with it all the strings that match this index.
7527     if (NewFirstUncoveredArg == FirstUncoveredArg)
7528       DiagnosticExprs.push_back(StrExpr);
7529     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7530       DiagnosticExprs.clear();
7531       DiagnosticExprs.push_back(StrExpr);
7532       FirstUncoveredArg = NewFirstUncoveredArg;
7533     }
7534   }
7535 
7536   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7537 };
7538 
7539 enum StringLiteralCheckType {
7540   SLCT_NotALiteral,
7541   SLCT_UncheckedLiteral,
7542   SLCT_CheckedLiteral
7543 };
7544 
7545 } // namespace
7546 
7547 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7548                                      BinaryOperatorKind BinOpKind,
7549                                      bool AddendIsRight) {
7550   unsigned BitWidth = Offset.getBitWidth();
7551   unsigned AddendBitWidth = Addend.getBitWidth();
7552   // There might be negative interim results.
7553   if (Addend.isUnsigned()) {
7554     Addend = Addend.zext(++AddendBitWidth);
7555     Addend.setIsSigned(true);
7556   }
7557   // Adjust the bit width of the APSInts.
7558   if (AddendBitWidth > BitWidth) {
7559     Offset = Offset.sext(AddendBitWidth);
7560     BitWidth = AddendBitWidth;
7561   } else if (BitWidth > AddendBitWidth) {
7562     Addend = Addend.sext(BitWidth);
7563   }
7564 
7565   bool Ov = false;
7566   llvm::APSInt ResOffset = Offset;
7567   if (BinOpKind == BO_Add)
7568     ResOffset = Offset.sadd_ov(Addend, Ov);
7569   else {
7570     assert(AddendIsRight && BinOpKind == BO_Sub &&
7571            "operator must be add or sub with addend on the right");
7572     ResOffset = Offset.ssub_ov(Addend, Ov);
7573   }
7574 
7575   // We add an offset to a pointer here so we should support an offset as big as
7576   // possible.
7577   if (Ov) {
7578     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7579            "index (intermediate) result too big");
7580     Offset = Offset.sext(2 * BitWidth);
7581     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7582     return;
7583   }
7584 
7585   Offset = ResOffset;
7586 }
7587 
7588 namespace {
7589 
7590 // This is a wrapper class around StringLiteral to support offsetted string
7591 // literals as format strings. It takes the offset into account when returning
7592 // the string and its length or the source locations to display notes correctly.
7593 class FormatStringLiteral {
7594   const StringLiteral *FExpr;
7595   int64_t Offset;
7596 
7597  public:
7598   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7599       : FExpr(fexpr), Offset(Offset) {}
7600 
7601   StringRef getString() const {
7602     return FExpr->getString().drop_front(Offset);
7603   }
7604 
7605   unsigned getByteLength() const {
7606     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7607   }
7608 
7609   unsigned getLength() const { return FExpr->getLength() - Offset; }
7610   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7611 
7612   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7613 
7614   QualType getType() const { return FExpr->getType(); }
7615 
7616   bool isAscii() const { return FExpr->isAscii(); }
7617   bool isWide() const { return FExpr->isWide(); }
7618   bool isUTF8() const { return FExpr->isUTF8(); }
7619   bool isUTF16() const { return FExpr->isUTF16(); }
7620   bool isUTF32() const { return FExpr->isUTF32(); }
7621   bool isPascal() const { return FExpr->isPascal(); }
7622 
7623   SourceLocation getLocationOfByte(
7624       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7625       const TargetInfo &Target, unsigned *StartToken = nullptr,
7626       unsigned *StartTokenByteOffset = nullptr) const {
7627     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7628                                     StartToken, StartTokenByteOffset);
7629   }
7630 
7631   SourceLocation getBeginLoc() const LLVM_READONLY {
7632     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7633   }
7634 
7635   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7636 };
7637 
7638 }  // namespace
7639 
7640 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7641                               const Expr *OrigFormatExpr,
7642                               ArrayRef<const Expr *> Args,
7643                               bool HasVAListArg, unsigned format_idx,
7644                               unsigned firstDataArg,
7645                               Sema::FormatStringType Type,
7646                               bool inFunctionCall,
7647                               Sema::VariadicCallType CallType,
7648                               llvm::SmallBitVector &CheckedVarArgs,
7649                               UncoveredArgHandler &UncoveredArg,
7650                               bool IgnoreStringsWithoutSpecifiers);
7651 
7652 // Determine if an expression is a string literal or constant string.
7653 // If this function returns false on the arguments to a function expecting a
7654 // format string, we will usually need to emit a warning.
7655 // True string literals are then checked by CheckFormatString.
7656 static StringLiteralCheckType
7657 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7658                       bool HasVAListArg, unsigned format_idx,
7659                       unsigned firstDataArg, Sema::FormatStringType Type,
7660                       Sema::VariadicCallType CallType, bool InFunctionCall,
7661                       llvm::SmallBitVector &CheckedVarArgs,
7662                       UncoveredArgHandler &UncoveredArg,
7663                       llvm::APSInt Offset,
7664                       bool IgnoreStringsWithoutSpecifiers = false) {
7665   if (S.isConstantEvaluated())
7666     return SLCT_NotALiteral;
7667  tryAgain:
7668   assert(Offset.isSigned() && "invalid offset");
7669 
7670   if (E->isTypeDependent() || E->isValueDependent())
7671     return SLCT_NotALiteral;
7672 
7673   E = E->IgnoreParenCasts();
7674 
7675   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7676     // Technically -Wformat-nonliteral does not warn about this case.
7677     // The behavior of printf and friends in this case is implementation
7678     // dependent.  Ideally if the format string cannot be null then
7679     // it should have a 'nonnull' attribute in the function prototype.
7680     return SLCT_UncheckedLiteral;
7681 
7682   switch (E->getStmtClass()) {
7683   case Stmt::BinaryConditionalOperatorClass:
7684   case Stmt::ConditionalOperatorClass: {
7685     // The expression is a literal if both sub-expressions were, and it was
7686     // completely checked only if both sub-expressions were checked.
7687     const AbstractConditionalOperator *C =
7688         cast<AbstractConditionalOperator>(E);
7689 
7690     // Determine whether it is necessary to check both sub-expressions, for
7691     // example, because the condition expression is a constant that can be
7692     // evaluated at compile time.
7693     bool CheckLeft = true, CheckRight = true;
7694 
7695     bool Cond;
7696     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7697                                                  S.isConstantEvaluated())) {
7698       if (Cond)
7699         CheckRight = false;
7700       else
7701         CheckLeft = false;
7702     }
7703 
7704     // We need to maintain the offsets for the right and the left hand side
7705     // separately to check if every possible indexed expression is a valid
7706     // string literal. They might have different offsets for different string
7707     // literals in the end.
7708     StringLiteralCheckType Left;
7709     if (!CheckLeft)
7710       Left = SLCT_UncheckedLiteral;
7711     else {
7712       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7713                                    HasVAListArg, format_idx, firstDataArg,
7714                                    Type, CallType, InFunctionCall,
7715                                    CheckedVarArgs, UncoveredArg, Offset,
7716                                    IgnoreStringsWithoutSpecifiers);
7717       if (Left == SLCT_NotALiteral || !CheckRight) {
7718         return Left;
7719       }
7720     }
7721 
7722     StringLiteralCheckType Right = checkFormatStringExpr(
7723         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7724         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7725         IgnoreStringsWithoutSpecifiers);
7726 
7727     return (CheckLeft && Left < Right) ? Left : Right;
7728   }
7729 
7730   case Stmt::ImplicitCastExprClass:
7731     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7732     goto tryAgain;
7733 
7734   case Stmt::OpaqueValueExprClass:
7735     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7736       E = src;
7737       goto tryAgain;
7738     }
7739     return SLCT_NotALiteral;
7740 
7741   case Stmt::PredefinedExprClass:
7742     // While __func__, etc., are technically not string literals, they
7743     // cannot contain format specifiers and thus are not a security
7744     // liability.
7745     return SLCT_UncheckedLiteral;
7746 
7747   case Stmt::DeclRefExprClass: {
7748     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7749 
7750     // As an exception, do not flag errors for variables binding to
7751     // const string literals.
7752     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7753       bool isConstant = false;
7754       QualType T = DR->getType();
7755 
7756       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7757         isConstant = AT->getElementType().isConstant(S.Context);
7758       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7759         isConstant = T.isConstant(S.Context) &&
7760                      PT->getPointeeType().isConstant(S.Context);
7761       } else if (T->isObjCObjectPointerType()) {
7762         // In ObjC, there is usually no "const ObjectPointer" type,
7763         // so don't check if the pointee type is constant.
7764         isConstant = T.isConstant(S.Context);
7765       }
7766 
7767       if (isConstant) {
7768         if (const Expr *Init = VD->getAnyInitializer()) {
7769           // Look through initializers like const char c[] = { "foo" }
7770           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7771             if (InitList->isStringLiteralInit())
7772               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7773           }
7774           return checkFormatStringExpr(S, Init, Args,
7775                                        HasVAListArg, format_idx,
7776                                        firstDataArg, Type, CallType,
7777                                        /*InFunctionCall*/ false, CheckedVarArgs,
7778                                        UncoveredArg, Offset);
7779         }
7780       }
7781 
7782       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7783       // special check to see if the format string is a function parameter
7784       // of the function calling the printf function.  If the function
7785       // has an attribute indicating it is a printf-like function, then we
7786       // should suppress warnings concerning non-literals being used in a call
7787       // to a vprintf function.  For example:
7788       //
7789       // void
7790       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7791       //      va_list ap;
7792       //      va_start(ap, fmt);
7793       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7794       //      ...
7795       // }
7796       if (HasVAListArg) {
7797         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7798           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7799             int PVIndex = PV->getFunctionScopeIndex() + 1;
7800             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7801               // adjust for implicit parameter
7802               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7803                 if (MD->isInstance())
7804                   ++PVIndex;
7805               // We also check if the formats are compatible.
7806               // We can't pass a 'scanf' string to a 'printf' function.
7807               if (PVIndex == PVFormat->getFormatIdx() &&
7808                   Type == S.GetFormatStringType(PVFormat))
7809                 return SLCT_UncheckedLiteral;
7810             }
7811           }
7812         }
7813       }
7814     }
7815 
7816     return SLCT_NotALiteral;
7817   }
7818 
7819   case Stmt::CallExprClass:
7820   case Stmt::CXXMemberCallExprClass: {
7821     const CallExpr *CE = cast<CallExpr>(E);
7822     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7823       bool IsFirst = true;
7824       StringLiteralCheckType CommonResult;
7825       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7826         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7827         StringLiteralCheckType Result = checkFormatStringExpr(
7828             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7829             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7830             IgnoreStringsWithoutSpecifiers);
7831         if (IsFirst) {
7832           CommonResult = Result;
7833           IsFirst = false;
7834         }
7835       }
7836       if (!IsFirst)
7837         return CommonResult;
7838 
7839       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7840         unsigned BuiltinID = FD->getBuiltinID();
7841         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7842             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7843           const Expr *Arg = CE->getArg(0);
7844           return checkFormatStringExpr(S, Arg, Args,
7845                                        HasVAListArg, format_idx,
7846                                        firstDataArg, Type, CallType,
7847                                        InFunctionCall, CheckedVarArgs,
7848                                        UncoveredArg, Offset,
7849                                        IgnoreStringsWithoutSpecifiers);
7850         }
7851       }
7852     }
7853 
7854     return SLCT_NotALiteral;
7855   }
7856   case Stmt::ObjCMessageExprClass: {
7857     const auto *ME = cast<ObjCMessageExpr>(E);
7858     if (const auto *MD = ME->getMethodDecl()) {
7859       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7860         // As a special case heuristic, if we're using the method -[NSBundle
7861         // localizedStringForKey:value:table:], ignore any key strings that lack
7862         // format specifiers. The idea is that if the key doesn't have any
7863         // format specifiers then its probably just a key to map to the
7864         // localized strings. If it does have format specifiers though, then its
7865         // likely that the text of the key is the format string in the
7866         // programmer's language, and should be checked.
7867         const ObjCInterfaceDecl *IFace;
7868         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7869             IFace->getIdentifier()->isStr("NSBundle") &&
7870             MD->getSelector().isKeywordSelector(
7871                 {"localizedStringForKey", "value", "table"})) {
7872           IgnoreStringsWithoutSpecifiers = true;
7873         }
7874 
7875         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7876         return checkFormatStringExpr(
7877             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7878             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7879             IgnoreStringsWithoutSpecifiers);
7880       }
7881     }
7882 
7883     return SLCT_NotALiteral;
7884   }
7885   case Stmt::ObjCStringLiteralClass:
7886   case Stmt::StringLiteralClass: {
7887     const StringLiteral *StrE = nullptr;
7888 
7889     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7890       StrE = ObjCFExpr->getString();
7891     else
7892       StrE = cast<StringLiteral>(E);
7893 
7894     if (StrE) {
7895       if (Offset.isNegative() || Offset > StrE->getLength()) {
7896         // TODO: It would be better to have an explicit warning for out of
7897         // bounds literals.
7898         return SLCT_NotALiteral;
7899       }
7900       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7901       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7902                         firstDataArg, Type, InFunctionCall, CallType,
7903                         CheckedVarArgs, UncoveredArg,
7904                         IgnoreStringsWithoutSpecifiers);
7905       return SLCT_CheckedLiteral;
7906     }
7907 
7908     return SLCT_NotALiteral;
7909   }
7910   case Stmt::BinaryOperatorClass: {
7911     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7912 
7913     // A string literal + an int offset is still a string literal.
7914     if (BinOp->isAdditiveOp()) {
7915       Expr::EvalResult LResult, RResult;
7916 
7917       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7918           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7919       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7920           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7921 
7922       if (LIsInt != RIsInt) {
7923         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7924 
7925         if (LIsInt) {
7926           if (BinOpKind == BO_Add) {
7927             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7928             E = BinOp->getRHS();
7929             goto tryAgain;
7930           }
7931         } else {
7932           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7933           E = BinOp->getLHS();
7934           goto tryAgain;
7935         }
7936       }
7937     }
7938 
7939     return SLCT_NotALiteral;
7940   }
7941   case Stmt::UnaryOperatorClass: {
7942     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7943     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7944     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7945       Expr::EvalResult IndexResult;
7946       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7947                                        Expr::SE_NoSideEffects,
7948                                        S.isConstantEvaluated())) {
7949         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7950                    /*RHS is int*/ true);
7951         E = ASE->getBase();
7952         goto tryAgain;
7953       }
7954     }
7955 
7956     return SLCT_NotALiteral;
7957   }
7958 
7959   default:
7960     return SLCT_NotALiteral;
7961   }
7962 }
7963 
7964 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7965   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7966       .Case("scanf", FST_Scanf)
7967       .Cases("printf", "printf0", FST_Printf)
7968       .Cases("NSString", "CFString", FST_NSString)
7969       .Case("strftime", FST_Strftime)
7970       .Case("strfmon", FST_Strfmon)
7971       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7972       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7973       .Case("os_trace", FST_OSLog)
7974       .Case("os_log", FST_OSLog)
7975       .Default(FST_Unknown);
7976 }
7977 
7978 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7979 /// functions) for correct use of format strings.
7980 /// Returns true if a format string has been fully checked.
7981 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7982                                 ArrayRef<const Expr *> Args,
7983                                 bool IsCXXMember,
7984                                 VariadicCallType CallType,
7985                                 SourceLocation Loc, SourceRange Range,
7986                                 llvm::SmallBitVector &CheckedVarArgs) {
7987   FormatStringInfo FSI;
7988   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7989     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7990                                 FSI.FirstDataArg, GetFormatStringType(Format),
7991                                 CallType, Loc, Range, CheckedVarArgs);
7992   return false;
7993 }
7994 
7995 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7996                                 bool HasVAListArg, unsigned format_idx,
7997                                 unsigned firstDataArg, FormatStringType Type,
7998                                 VariadicCallType CallType,
7999                                 SourceLocation Loc, SourceRange Range,
8000                                 llvm::SmallBitVector &CheckedVarArgs) {
8001   // CHECK: printf/scanf-like function is called with no format string.
8002   if (format_idx >= Args.size()) {
8003     Diag(Loc, diag::warn_missing_format_string) << Range;
8004     return false;
8005   }
8006 
8007   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8008 
8009   // CHECK: format string is not a string literal.
8010   //
8011   // Dynamically generated format strings are difficult to
8012   // automatically vet at compile time.  Requiring that format strings
8013   // are string literals: (1) permits the checking of format strings by
8014   // the compiler and thereby (2) can practically remove the source of
8015   // many format string exploits.
8016 
8017   // Format string can be either ObjC string (e.g. @"%d") or
8018   // C string (e.g. "%d")
8019   // ObjC string uses the same format specifiers as C string, so we can use
8020   // the same format string checking logic for both ObjC and C strings.
8021   UncoveredArgHandler UncoveredArg;
8022   StringLiteralCheckType CT =
8023       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8024                             format_idx, firstDataArg, Type, CallType,
8025                             /*IsFunctionCall*/ true, CheckedVarArgs,
8026                             UncoveredArg,
8027                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8028 
8029   // Generate a diagnostic where an uncovered argument is detected.
8030   if (UncoveredArg.hasUncoveredArg()) {
8031     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8032     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8033     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8034   }
8035 
8036   if (CT != SLCT_NotALiteral)
8037     // Literal format string found, check done!
8038     return CT == SLCT_CheckedLiteral;
8039 
8040   // Strftime is particular as it always uses a single 'time' argument,
8041   // so it is safe to pass a non-literal string.
8042   if (Type == FST_Strftime)
8043     return false;
8044 
8045   // Do not emit diag when the string param is a macro expansion and the
8046   // format is either NSString or CFString. This is a hack to prevent
8047   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8048   // which are usually used in place of NS and CF string literals.
8049   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8050   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8051     return false;
8052 
8053   // If there are no arguments specified, warn with -Wformat-security, otherwise
8054   // warn only with -Wformat-nonliteral.
8055   if (Args.size() == firstDataArg) {
8056     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8057       << OrigFormatExpr->getSourceRange();
8058     switch (Type) {
8059     default:
8060       break;
8061     case FST_Kprintf:
8062     case FST_FreeBSDKPrintf:
8063     case FST_Printf:
8064       Diag(FormatLoc, diag::note_format_security_fixit)
8065         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8066       break;
8067     case FST_NSString:
8068       Diag(FormatLoc, diag::note_format_security_fixit)
8069         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8070       break;
8071     }
8072   } else {
8073     Diag(FormatLoc, diag::warn_format_nonliteral)
8074       << OrigFormatExpr->getSourceRange();
8075   }
8076   return false;
8077 }
8078 
8079 namespace {
8080 
8081 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8082 protected:
8083   Sema &S;
8084   const FormatStringLiteral *FExpr;
8085   const Expr *OrigFormatExpr;
8086   const Sema::FormatStringType FSType;
8087   const unsigned FirstDataArg;
8088   const unsigned NumDataArgs;
8089   const char *Beg; // Start of format string.
8090   const bool HasVAListArg;
8091   ArrayRef<const Expr *> Args;
8092   unsigned FormatIdx;
8093   llvm::SmallBitVector CoveredArgs;
8094   bool usesPositionalArgs = false;
8095   bool atFirstArg = true;
8096   bool inFunctionCall;
8097   Sema::VariadicCallType CallType;
8098   llvm::SmallBitVector &CheckedVarArgs;
8099   UncoveredArgHandler &UncoveredArg;
8100 
8101 public:
8102   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8103                      const Expr *origFormatExpr,
8104                      const Sema::FormatStringType type, unsigned firstDataArg,
8105                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8106                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8107                      bool inFunctionCall, Sema::VariadicCallType callType,
8108                      llvm::SmallBitVector &CheckedVarArgs,
8109                      UncoveredArgHandler &UncoveredArg)
8110       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8111         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8112         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8113         inFunctionCall(inFunctionCall), CallType(callType),
8114         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8115     CoveredArgs.resize(numDataArgs);
8116     CoveredArgs.reset();
8117   }
8118 
8119   void DoneProcessing();
8120 
8121   void HandleIncompleteSpecifier(const char *startSpecifier,
8122                                  unsigned specifierLen) override;
8123 
8124   void HandleInvalidLengthModifier(
8125                            const analyze_format_string::FormatSpecifier &FS,
8126                            const analyze_format_string::ConversionSpecifier &CS,
8127                            const char *startSpecifier, unsigned specifierLen,
8128                            unsigned DiagID);
8129 
8130   void HandleNonStandardLengthModifier(
8131                     const analyze_format_string::FormatSpecifier &FS,
8132                     const char *startSpecifier, unsigned specifierLen);
8133 
8134   void HandleNonStandardConversionSpecifier(
8135                     const analyze_format_string::ConversionSpecifier &CS,
8136                     const char *startSpecifier, unsigned specifierLen);
8137 
8138   void HandlePosition(const char *startPos, unsigned posLen) override;
8139 
8140   void HandleInvalidPosition(const char *startSpecifier,
8141                              unsigned specifierLen,
8142                              analyze_format_string::PositionContext p) override;
8143 
8144   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8145 
8146   void HandleNullChar(const char *nullCharacter) override;
8147 
8148   template <typename Range>
8149   static void
8150   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8151                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8152                        bool IsStringLocation, Range StringRange,
8153                        ArrayRef<FixItHint> Fixit = None);
8154 
8155 protected:
8156   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8157                                         const char *startSpec,
8158                                         unsigned specifierLen,
8159                                         const char *csStart, unsigned csLen);
8160 
8161   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8162                                          const char *startSpec,
8163                                          unsigned specifierLen);
8164 
8165   SourceRange getFormatStringRange();
8166   CharSourceRange getSpecifierRange(const char *startSpecifier,
8167                                     unsigned specifierLen);
8168   SourceLocation getLocationOfByte(const char *x);
8169 
8170   const Expr *getDataArg(unsigned i) const;
8171 
8172   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8173                     const analyze_format_string::ConversionSpecifier &CS,
8174                     const char *startSpecifier, unsigned specifierLen,
8175                     unsigned argIndex);
8176 
8177   template <typename Range>
8178   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8179                             bool IsStringLocation, Range StringRange,
8180                             ArrayRef<FixItHint> Fixit = None);
8181 };
8182 
8183 } // namespace
8184 
8185 SourceRange CheckFormatHandler::getFormatStringRange() {
8186   return OrigFormatExpr->getSourceRange();
8187 }
8188 
8189 CharSourceRange CheckFormatHandler::
8190 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8191   SourceLocation Start = getLocationOfByte(startSpecifier);
8192   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8193 
8194   // Advance the end SourceLocation by one due to half-open ranges.
8195   End = End.getLocWithOffset(1);
8196 
8197   return CharSourceRange::getCharRange(Start, End);
8198 }
8199 
8200 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8201   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8202                                   S.getLangOpts(), S.Context.getTargetInfo());
8203 }
8204 
8205 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8206                                                    unsigned specifierLen){
8207   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8208                        getLocationOfByte(startSpecifier),
8209                        /*IsStringLocation*/true,
8210                        getSpecifierRange(startSpecifier, specifierLen));
8211 }
8212 
8213 void CheckFormatHandler::HandleInvalidLengthModifier(
8214     const analyze_format_string::FormatSpecifier &FS,
8215     const analyze_format_string::ConversionSpecifier &CS,
8216     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8217   using namespace analyze_format_string;
8218 
8219   const LengthModifier &LM = FS.getLengthModifier();
8220   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8221 
8222   // See if we know how to fix this length modifier.
8223   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8224   if (FixedLM) {
8225     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8226                          getLocationOfByte(LM.getStart()),
8227                          /*IsStringLocation*/true,
8228                          getSpecifierRange(startSpecifier, specifierLen));
8229 
8230     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8231       << FixedLM->toString()
8232       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8233 
8234   } else {
8235     FixItHint Hint;
8236     if (DiagID == diag::warn_format_nonsensical_length)
8237       Hint = FixItHint::CreateRemoval(LMRange);
8238 
8239     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8240                          getLocationOfByte(LM.getStart()),
8241                          /*IsStringLocation*/true,
8242                          getSpecifierRange(startSpecifier, specifierLen),
8243                          Hint);
8244   }
8245 }
8246 
8247 void CheckFormatHandler::HandleNonStandardLengthModifier(
8248     const analyze_format_string::FormatSpecifier &FS,
8249     const char *startSpecifier, unsigned specifierLen) {
8250   using namespace analyze_format_string;
8251 
8252   const LengthModifier &LM = FS.getLengthModifier();
8253   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8254 
8255   // See if we know how to fix this length modifier.
8256   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8257   if (FixedLM) {
8258     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8259                            << LM.toString() << 0,
8260                          getLocationOfByte(LM.getStart()),
8261                          /*IsStringLocation*/true,
8262                          getSpecifierRange(startSpecifier, specifierLen));
8263 
8264     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8265       << FixedLM->toString()
8266       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8267 
8268   } else {
8269     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8270                            << LM.toString() << 0,
8271                          getLocationOfByte(LM.getStart()),
8272                          /*IsStringLocation*/true,
8273                          getSpecifierRange(startSpecifier, specifierLen));
8274   }
8275 }
8276 
8277 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8278     const analyze_format_string::ConversionSpecifier &CS,
8279     const char *startSpecifier, unsigned specifierLen) {
8280   using namespace analyze_format_string;
8281 
8282   // See if we know how to fix this conversion specifier.
8283   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8284   if (FixedCS) {
8285     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8286                           << CS.toString() << /*conversion specifier*/1,
8287                          getLocationOfByte(CS.getStart()),
8288                          /*IsStringLocation*/true,
8289                          getSpecifierRange(startSpecifier, specifierLen));
8290 
8291     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8292     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8293       << FixedCS->toString()
8294       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8295   } else {
8296     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8297                           << CS.toString() << /*conversion specifier*/1,
8298                          getLocationOfByte(CS.getStart()),
8299                          /*IsStringLocation*/true,
8300                          getSpecifierRange(startSpecifier, specifierLen));
8301   }
8302 }
8303 
8304 void CheckFormatHandler::HandlePosition(const char *startPos,
8305                                         unsigned posLen) {
8306   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8307                                getLocationOfByte(startPos),
8308                                /*IsStringLocation*/true,
8309                                getSpecifierRange(startPos, posLen));
8310 }
8311 
8312 void
8313 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8314                                      analyze_format_string::PositionContext p) {
8315   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8316                          << (unsigned) p,
8317                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8318                        getSpecifierRange(startPos, posLen));
8319 }
8320 
8321 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8322                                             unsigned posLen) {
8323   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8324                                getLocationOfByte(startPos),
8325                                /*IsStringLocation*/true,
8326                                getSpecifierRange(startPos, posLen));
8327 }
8328 
8329 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8330   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8331     // The presence of a null character is likely an error.
8332     EmitFormatDiagnostic(
8333       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8334       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8335       getFormatStringRange());
8336   }
8337 }
8338 
8339 // Note that this may return NULL if there was an error parsing or building
8340 // one of the argument expressions.
8341 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8342   return Args[FirstDataArg + i];
8343 }
8344 
8345 void CheckFormatHandler::DoneProcessing() {
8346   // Does the number of data arguments exceed the number of
8347   // format conversions in the format string?
8348   if (!HasVAListArg) {
8349       // Find any arguments that weren't covered.
8350     CoveredArgs.flip();
8351     signed notCoveredArg = CoveredArgs.find_first();
8352     if (notCoveredArg >= 0) {
8353       assert((unsigned)notCoveredArg < NumDataArgs);
8354       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8355     } else {
8356       UncoveredArg.setAllCovered();
8357     }
8358   }
8359 }
8360 
8361 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8362                                    const Expr *ArgExpr) {
8363   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8364          "Invalid state");
8365 
8366   if (!ArgExpr)
8367     return;
8368 
8369   SourceLocation Loc = ArgExpr->getBeginLoc();
8370 
8371   if (S.getSourceManager().isInSystemMacro(Loc))
8372     return;
8373 
8374   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8375   for (auto E : DiagnosticExprs)
8376     PDiag << E->getSourceRange();
8377 
8378   CheckFormatHandler::EmitFormatDiagnostic(
8379                                   S, IsFunctionCall, DiagnosticExprs[0],
8380                                   PDiag, Loc, /*IsStringLocation*/false,
8381                                   DiagnosticExprs[0]->getSourceRange());
8382 }
8383 
8384 bool
8385 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8386                                                      SourceLocation Loc,
8387                                                      const char *startSpec,
8388                                                      unsigned specifierLen,
8389                                                      const char *csStart,
8390                                                      unsigned csLen) {
8391   bool keepGoing = true;
8392   if (argIndex < NumDataArgs) {
8393     // Consider the argument coverered, even though the specifier doesn't
8394     // make sense.
8395     CoveredArgs.set(argIndex);
8396   }
8397   else {
8398     // If argIndex exceeds the number of data arguments we
8399     // don't issue a warning because that is just a cascade of warnings (and
8400     // they may have intended '%%' anyway). We don't want to continue processing
8401     // the format string after this point, however, as we will like just get
8402     // gibberish when trying to match arguments.
8403     keepGoing = false;
8404   }
8405 
8406   StringRef Specifier(csStart, csLen);
8407 
8408   // If the specifier in non-printable, it could be the first byte of a UTF-8
8409   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8410   // hex value.
8411   std::string CodePointStr;
8412   if (!llvm::sys::locale::isPrint(*csStart)) {
8413     llvm::UTF32 CodePoint;
8414     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8415     const llvm::UTF8 *E =
8416         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8417     llvm::ConversionResult Result =
8418         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8419 
8420     if (Result != llvm::conversionOK) {
8421       unsigned char FirstChar = *csStart;
8422       CodePoint = (llvm::UTF32)FirstChar;
8423     }
8424 
8425     llvm::raw_string_ostream OS(CodePointStr);
8426     if (CodePoint < 256)
8427       OS << "\\x" << llvm::format("%02x", CodePoint);
8428     else if (CodePoint <= 0xFFFF)
8429       OS << "\\u" << llvm::format("%04x", CodePoint);
8430     else
8431       OS << "\\U" << llvm::format("%08x", CodePoint);
8432     OS.flush();
8433     Specifier = CodePointStr;
8434   }
8435 
8436   EmitFormatDiagnostic(
8437       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8438       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8439 
8440   return keepGoing;
8441 }
8442 
8443 void
8444 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8445                                                       const char *startSpec,
8446                                                       unsigned specifierLen) {
8447   EmitFormatDiagnostic(
8448     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8449     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8450 }
8451 
8452 bool
8453 CheckFormatHandler::CheckNumArgs(
8454   const analyze_format_string::FormatSpecifier &FS,
8455   const analyze_format_string::ConversionSpecifier &CS,
8456   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8457 
8458   if (argIndex >= NumDataArgs) {
8459     PartialDiagnostic PDiag = FS.usesPositionalArg()
8460       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8461            << (argIndex+1) << NumDataArgs)
8462       : S.PDiag(diag::warn_printf_insufficient_data_args);
8463     EmitFormatDiagnostic(
8464       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8465       getSpecifierRange(startSpecifier, specifierLen));
8466 
8467     // Since more arguments than conversion tokens are given, by extension
8468     // all arguments are covered, so mark this as so.
8469     UncoveredArg.setAllCovered();
8470     return false;
8471   }
8472   return true;
8473 }
8474 
8475 template<typename Range>
8476 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8477                                               SourceLocation Loc,
8478                                               bool IsStringLocation,
8479                                               Range StringRange,
8480                                               ArrayRef<FixItHint> FixIt) {
8481   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8482                        Loc, IsStringLocation, StringRange, FixIt);
8483 }
8484 
8485 /// If the format string is not within the function call, emit a note
8486 /// so that the function call and string are in diagnostic messages.
8487 ///
8488 /// \param InFunctionCall if true, the format string is within the function
8489 /// call and only one diagnostic message will be produced.  Otherwise, an
8490 /// extra note will be emitted pointing to location of the format string.
8491 ///
8492 /// \param ArgumentExpr the expression that is passed as the format string
8493 /// argument in the function call.  Used for getting locations when two
8494 /// diagnostics are emitted.
8495 ///
8496 /// \param PDiag the callee should already have provided any strings for the
8497 /// diagnostic message.  This function only adds locations and fixits
8498 /// to diagnostics.
8499 ///
8500 /// \param Loc primary location for diagnostic.  If two diagnostics are
8501 /// required, one will be at Loc and a new SourceLocation will be created for
8502 /// the other one.
8503 ///
8504 /// \param IsStringLocation if true, Loc points to the format string should be
8505 /// used for the note.  Otherwise, Loc points to the argument list and will
8506 /// be used with PDiag.
8507 ///
8508 /// \param StringRange some or all of the string to highlight.  This is
8509 /// templated so it can accept either a CharSourceRange or a SourceRange.
8510 ///
8511 /// \param FixIt optional fix it hint for the format string.
8512 template <typename Range>
8513 void CheckFormatHandler::EmitFormatDiagnostic(
8514     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8515     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8516     Range StringRange, ArrayRef<FixItHint> FixIt) {
8517   if (InFunctionCall) {
8518     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8519     D << StringRange;
8520     D << FixIt;
8521   } else {
8522     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8523       << ArgumentExpr->getSourceRange();
8524 
8525     const Sema::SemaDiagnosticBuilder &Note =
8526       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8527              diag::note_format_string_defined);
8528 
8529     Note << StringRange;
8530     Note << FixIt;
8531   }
8532 }
8533 
8534 //===--- CHECK: Printf format string checking ------------------------------===//
8535 
8536 namespace {
8537 
8538 class CheckPrintfHandler : public CheckFormatHandler {
8539 public:
8540   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8541                      const Expr *origFormatExpr,
8542                      const Sema::FormatStringType type, unsigned firstDataArg,
8543                      unsigned numDataArgs, bool isObjC, const char *beg,
8544                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8545                      unsigned formatIdx, bool inFunctionCall,
8546                      Sema::VariadicCallType CallType,
8547                      llvm::SmallBitVector &CheckedVarArgs,
8548                      UncoveredArgHandler &UncoveredArg)
8549       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8550                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8551                            inFunctionCall, CallType, CheckedVarArgs,
8552                            UncoveredArg) {}
8553 
8554   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8555 
8556   /// Returns true if '%@' specifiers are allowed in the format string.
8557   bool allowsObjCArg() const {
8558     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8559            FSType == Sema::FST_OSTrace;
8560   }
8561 
8562   bool HandleInvalidPrintfConversionSpecifier(
8563                                       const analyze_printf::PrintfSpecifier &FS,
8564                                       const char *startSpecifier,
8565                                       unsigned specifierLen) override;
8566 
8567   void handleInvalidMaskType(StringRef MaskType) override;
8568 
8569   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8570                              const char *startSpecifier,
8571                              unsigned specifierLen) override;
8572   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8573                        const char *StartSpecifier,
8574                        unsigned SpecifierLen,
8575                        const Expr *E);
8576 
8577   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8578                     const char *startSpecifier, unsigned specifierLen);
8579   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8580                            const analyze_printf::OptionalAmount &Amt,
8581                            unsigned type,
8582                            const char *startSpecifier, unsigned specifierLen);
8583   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8584                   const analyze_printf::OptionalFlag &flag,
8585                   const char *startSpecifier, unsigned specifierLen);
8586   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8587                          const analyze_printf::OptionalFlag &ignoredFlag,
8588                          const analyze_printf::OptionalFlag &flag,
8589                          const char *startSpecifier, unsigned specifierLen);
8590   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8591                            const Expr *E);
8592 
8593   void HandleEmptyObjCModifierFlag(const char *startFlag,
8594                                    unsigned flagLen) override;
8595 
8596   void HandleInvalidObjCModifierFlag(const char *startFlag,
8597                                             unsigned flagLen) override;
8598 
8599   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8600                                            const char *flagsEnd,
8601                                            const char *conversionPosition)
8602                                              override;
8603 };
8604 
8605 } // namespace
8606 
8607 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8608                                       const analyze_printf::PrintfSpecifier &FS,
8609                                       const char *startSpecifier,
8610                                       unsigned specifierLen) {
8611   const analyze_printf::PrintfConversionSpecifier &CS =
8612     FS.getConversionSpecifier();
8613 
8614   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8615                                           getLocationOfByte(CS.getStart()),
8616                                           startSpecifier, specifierLen,
8617                                           CS.getStart(), CS.getLength());
8618 }
8619 
8620 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8621   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8622 }
8623 
8624 bool CheckPrintfHandler::HandleAmount(
8625                                const analyze_format_string::OptionalAmount &Amt,
8626                                unsigned k, const char *startSpecifier,
8627                                unsigned specifierLen) {
8628   if (Amt.hasDataArgument()) {
8629     if (!HasVAListArg) {
8630       unsigned argIndex = Amt.getArgIndex();
8631       if (argIndex >= NumDataArgs) {
8632         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8633                                << k,
8634                              getLocationOfByte(Amt.getStart()),
8635                              /*IsStringLocation*/true,
8636                              getSpecifierRange(startSpecifier, specifierLen));
8637         // Don't do any more checking.  We will just emit
8638         // spurious errors.
8639         return false;
8640       }
8641 
8642       // Type check the data argument.  It should be an 'int'.
8643       // Although not in conformance with C99, we also allow the argument to be
8644       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8645       // doesn't emit a warning for that case.
8646       CoveredArgs.set(argIndex);
8647       const Expr *Arg = getDataArg(argIndex);
8648       if (!Arg)
8649         return false;
8650 
8651       QualType T = Arg->getType();
8652 
8653       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8654       assert(AT.isValid());
8655 
8656       if (!AT.matchesType(S.Context, T)) {
8657         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8658                                << k << AT.getRepresentativeTypeName(S.Context)
8659                                << T << Arg->getSourceRange(),
8660                              getLocationOfByte(Amt.getStart()),
8661                              /*IsStringLocation*/true,
8662                              getSpecifierRange(startSpecifier, specifierLen));
8663         // Don't do any more checking.  We will just emit
8664         // spurious errors.
8665         return false;
8666       }
8667     }
8668   }
8669   return true;
8670 }
8671 
8672 void CheckPrintfHandler::HandleInvalidAmount(
8673                                       const analyze_printf::PrintfSpecifier &FS,
8674                                       const analyze_printf::OptionalAmount &Amt,
8675                                       unsigned type,
8676                                       const char *startSpecifier,
8677                                       unsigned specifierLen) {
8678   const analyze_printf::PrintfConversionSpecifier &CS =
8679     FS.getConversionSpecifier();
8680 
8681   FixItHint fixit =
8682     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8683       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8684                                  Amt.getConstantLength()))
8685       : FixItHint();
8686 
8687   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8688                          << type << CS.toString(),
8689                        getLocationOfByte(Amt.getStart()),
8690                        /*IsStringLocation*/true,
8691                        getSpecifierRange(startSpecifier, specifierLen),
8692                        fixit);
8693 }
8694 
8695 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8696                                     const analyze_printf::OptionalFlag &flag,
8697                                     const char *startSpecifier,
8698                                     unsigned specifierLen) {
8699   // Warn about pointless flag with a fixit removal.
8700   const analyze_printf::PrintfConversionSpecifier &CS =
8701     FS.getConversionSpecifier();
8702   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8703                          << flag.toString() << CS.toString(),
8704                        getLocationOfByte(flag.getPosition()),
8705                        /*IsStringLocation*/true,
8706                        getSpecifierRange(startSpecifier, specifierLen),
8707                        FixItHint::CreateRemoval(
8708                          getSpecifierRange(flag.getPosition(), 1)));
8709 }
8710 
8711 void CheckPrintfHandler::HandleIgnoredFlag(
8712                                 const analyze_printf::PrintfSpecifier &FS,
8713                                 const analyze_printf::OptionalFlag &ignoredFlag,
8714                                 const analyze_printf::OptionalFlag &flag,
8715                                 const char *startSpecifier,
8716                                 unsigned specifierLen) {
8717   // Warn about ignored flag with a fixit removal.
8718   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8719                          << ignoredFlag.toString() << flag.toString(),
8720                        getLocationOfByte(ignoredFlag.getPosition()),
8721                        /*IsStringLocation*/true,
8722                        getSpecifierRange(startSpecifier, specifierLen),
8723                        FixItHint::CreateRemoval(
8724                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8725 }
8726 
8727 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8728                                                      unsigned flagLen) {
8729   // Warn about an empty flag.
8730   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8731                        getLocationOfByte(startFlag),
8732                        /*IsStringLocation*/true,
8733                        getSpecifierRange(startFlag, flagLen));
8734 }
8735 
8736 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8737                                                        unsigned flagLen) {
8738   // Warn about an invalid flag.
8739   auto Range = getSpecifierRange(startFlag, flagLen);
8740   StringRef flag(startFlag, flagLen);
8741   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8742                       getLocationOfByte(startFlag),
8743                       /*IsStringLocation*/true,
8744                       Range, FixItHint::CreateRemoval(Range));
8745 }
8746 
8747 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8748     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8749     // Warn about using '[...]' without a '@' conversion.
8750     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8751     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8752     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8753                          getLocationOfByte(conversionPosition),
8754                          /*IsStringLocation*/true,
8755                          Range, FixItHint::CreateRemoval(Range));
8756 }
8757 
8758 // Determines if the specified is a C++ class or struct containing
8759 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8760 // "c_str()").
8761 template<typename MemberKind>
8762 static llvm::SmallPtrSet<MemberKind*, 1>
8763 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8764   const RecordType *RT = Ty->getAs<RecordType>();
8765   llvm::SmallPtrSet<MemberKind*, 1> Results;
8766 
8767   if (!RT)
8768     return Results;
8769   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8770   if (!RD || !RD->getDefinition())
8771     return Results;
8772 
8773   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8774                  Sema::LookupMemberName);
8775   R.suppressDiagnostics();
8776 
8777   // We just need to include all members of the right kind turned up by the
8778   // filter, at this point.
8779   if (S.LookupQualifiedName(R, RT->getDecl()))
8780     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8781       NamedDecl *decl = (*I)->getUnderlyingDecl();
8782       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8783         Results.insert(FK);
8784     }
8785   return Results;
8786 }
8787 
8788 /// Check if we could call '.c_str()' on an object.
8789 ///
8790 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8791 /// allow the call, or if it would be ambiguous).
8792 bool Sema::hasCStrMethod(const Expr *E) {
8793   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8794 
8795   MethodSet Results =
8796       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8797   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8798        MI != ME; ++MI)
8799     if ((*MI)->getMinRequiredArguments() == 0)
8800       return true;
8801   return false;
8802 }
8803 
8804 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8805 // better diagnostic if so. AT is assumed to be valid.
8806 // Returns true when a c_str() conversion method is found.
8807 bool CheckPrintfHandler::checkForCStrMembers(
8808     const analyze_printf::ArgType &AT, const Expr *E) {
8809   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8810 
8811   MethodSet Results =
8812       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8813 
8814   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8815        MI != ME; ++MI) {
8816     const CXXMethodDecl *Method = *MI;
8817     if (Method->getMinRequiredArguments() == 0 &&
8818         AT.matchesType(S.Context, Method->getReturnType())) {
8819       // FIXME: Suggest parens if the expression needs them.
8820       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8821       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8822           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8823       return true;
8824     }
8825   }
8826 
8827   return false;
8828 }
8829 
8830 bool
8831 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8832                                             &FS,
8833                                           const char *startSpecifier,
8834                                           unsigned specifierLen) {
8835   using namespace analyze_format_string;
8836   using namespace analyze_printf;
8837 
8838   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8839 
8840   if (FS.consumesDataArgument()) {
8841     if (atFirstArg) {
8842         atFirstArg = false;
8843         usesPositionalArgs = FS.usesPositionalArg();
8844     }
8845     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8846       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8847                                         startSpecifier, specifierLen);
8848       return false;
8849     }
8850   }
8851 
8852   // First check if the field width, precision, and conversion specifier
8853   // have matching data arguments.
8854   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8855                     startSpecifier, specifierLen)) {
8856     return false;
8857   }
8858 
8859   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8860                     startSpecifier, specifierLen)) {
8861     return false;
8862   }
8863 
8864   if (!CS.consumesDataArgument()) {
8865     // FIXME: Technically specifying a precision or field width here
8866     // makes no sense.  Worth issuing a warning at some point.
8867     return true;
8868   }
8869 
8870   // Consume the argument.
8871   unsigned argIndex = FS.getArgIndex();
8872   if (argIndex < NumDataArgs) {
8873     // The check to see if the argIndex is valid will come later.
8874     // We set the bit here because we may exit early from this
8875     // function if we encounter some other error.
8876     CoveredArgs.set(argIndex);
8877   }
8878 
8879   // FreeBSD kernel extensions.
8880   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8881       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8882     // We need at least two arguments.
8883     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8884       return false;
8885 
8886     // Claim the second argument.
8887     CoveredArgs.set(argIndex + 1);
8888 
8889     // Type check the first argument (int for %b, pointer for %D)
8890     const Expr *Ex = getDataArg(argIndex);
8891     const analyze_printf::ArgType &AT =
8892       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8893         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8894     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8895       EmitFormatDiagnostic(
8896           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8897               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8898               << false << Ex->getSourceRange(),
8899           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8900           getSpecifierRange(startSpecifier, specifierLen));
8901 
8902     // Type check the second argument (char * for both %b and %D)
8903     Ex = getDataArg(argIndex + 1);
8904     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8905     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8906       EmitFormatDiagnostic(
8907           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8908               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8909               << false << Ex->getSourceRange(),
8910           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8911           getSpecifierRange(startSpecifier, specifierLen));
8912 
8913      return true;
8914   }
8915 
8916   // Check for using an Objective-C specific conversion specifier
8917   // in a non-ObjC literal.
8918   if (!allowsObjCArg() && CS.isObjCArg()) {
8919     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8920                                                   specifierLen);
8921   }
8922 
8923   // %P can only be used with os_log.
8924   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8925     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8926                                                   specifierLen);
8927   }
8928 
8929   // %n is not allowed with os_log.
8930   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8931     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8932                          getLocationOfByte(CS.getStart()),
8933                          /*IsStringLocation*/ false,
8934                          getSpecifierRange(startSpecifier, specifierLen));
8935 
8936     return true;
8937   }
8938 
8939   // Only scalars are allowed for os_trace.
8940   if (FSType == Sema::FST_OSTrace &&
8941       (CS.getKind() == ConversionSpecifier::PArg ||
8942        CS.getKind() == ConversionSpecifier::sArg ||
8943        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8944     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8945                                                   specifierLen);
8946   }
8947 
8948   // Check for use of public/private annotation outside of os_log().
8949   if (FSType != Sema::FST_OSLog) {
8950     if (FS.isPublic().isSet()) {
8951       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8952                                << "public",
8953                            getLocationOfByte(FS.isPublic().getPosition()),
8954                            /*IsStringLocation*/ false,
8955                            getSpecifierRange(startSpecifier, specifierLen));
8956     }
8957     if (FS.isPrivate().isSet()) {
8958       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8959                                << "private",
8960                            getLocationOfByte(FS.isPrivate().getPosition()),
8961                            /*IsStringLocation*/ false,
8962                            getSpecifierRange(startSpecifier, specifierLen));
8963     }
8964   }
8965 
8966   // Check for invalid use of field width
8967   if (!FS.hasValidFieldWidth()) {
8968     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8969         startSpecifier, specifierLen);
8970   }
8971 
8972   // Check for invalid use of precision
8973   if (!FS.hasValidPrecision()) {
8974     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8975         startSpecifier, specifierLen);
8976   }
8977 
8978   // Precision is mandatory for %P specifier.
8979   if (CS.getKind() == ConversionSpecifier::PArg &&
8980       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8981     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8982                          getLocationOfByte(startSpecifier),
8983                          /*IsStringLocation*/ false,
8984                          getSpecifierRange(startSpecifier, specifierLen));
8985   }
8986 
8987   // Check each flag does not conflict with any other component.
8988   if (!FS.hasValidThousandsGroupingPrefix())
8989     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8990   if (!FS.hasValidLeadingZeros())
8991     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8992   if (!FS.hasValidPlusPrefix())
8993     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8994   if (!FS.hasValidSpacePrefix())
8995     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8996   if (!FS.hasValidAlternativeForm())
8997     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8998   if (!FS.hasValidLeftJustified())
8999     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9000 
9001   // Check that flags are not ignored by another flag
9002   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9003     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9004         startSpecifier, specifierLen);
9005   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9006     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9007             startSpecifier, specifierLen);
9008 
9009   // Check the length modifier is valid with the given conversion specifier.
9010   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9011                                  S.getLangOpts()))
9012     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9013                                 diag::warn_format_nonsensical_length);
9014   else if (!FS.hasStandardLengthModifier())
9015     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9016   else if (!FS.hasStandardLengthConversionCombination())
9017     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9018                                 diag::warn_format_non_standard_conversion_spec);
9019 
9020   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9021     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9022 
9023   // The remaining checks depend on the data arguments.
9024   if (HasVAListArg)
9025     return true;
9026 
9027   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9028     return false;
9029 
9030   const Expr *Arg = getDataArg(argIndex);
9031   if (!Arg)
9032     return true;
9033 
9034   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9035 }
9036 
9037 static bool requiresParensToAddCast(const Expr *E) {
9038   // FIXME: We should have a general way to reason about operator
9039   // precedence and whether parens are actually needed here.
9040   // Take care of a few common cases where they aren't.
9041   const Expr *Inside = E->IgnoreImpCasts();
9042   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9043     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9044 
9045   switch (Inside->getStmtClass()) {
9046   case Stmt::ArraySubscriptExprClass:
9047   case Stmt::CallExprClass:
9048   case Stmt::CharacterLiteralClass:
9049   case Stmt::CXXBoolLiteralExprClass:
9050   case Stmt::DeclRefExprClass:
9051   case Stmt::FloatingLiteralClass:
9052   case Stmt::IntegerLiteralClass:
9053   case Stmt::MemberExprClass:
9054   case Stmt::ObjCArrayLiteralClass:
9055   case Stmt::ObjCBoolLiteralExprClass:
9056   case Stmt::ObjCBoxedExprClass:
9057   case Stmt::ObjCDictionaryLiteralClass:
9058   case Stmt::ObjCEncodeExprClass:
9059   case Stmt::ObjCIvarRefExprClass:
9060   case Stmt::ObjCMessageExprClass:
9061   case Stmt::ObjCPropertyRefExprClass:
9062   case Stmt::ObjCStringLiteralClass:
9063   case Stmt::ObjCSubscriptRefExprClass:
9064   case Stmt::ParenExprClass:
9065   case Stmt::StringLiteralClass:
9066   case Stmt::UnaryOperatorClass:
9067     return false;
9068   default:
9069     return true;
9070   }
9071 }
9072 
9073 static std::pair<QualType, StringRef>
9074 shouldNotPrintDirectly(const ASTContext &Context,
9075                        QualType IntendedTy,
9076                        const Expr *E) {
9077   // Use a 'while' to peel off layers of typedefs.
9078   QualType TyTy = IntendedTy;
9079   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9080     StringRef Name = UserTy->getDecl()->getName();
9081     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9082       .Case("CFIndex", Context.getNSIntegerType())
9083       .Case("NSInteger", Context.getNSIntegerType())
9084       .Case("NSUInteger", Context.getNSUIntegerType())
9085       .Case("SInt32", Context.IntTy)
9086       .Case("UInt32", Context.UnsignedIntTy)
9087       .Default(QualType());
9088 
9089     if (!CastTy.isNull())
9090       return std::make_pair(CastTy, Name);
9091 
9092     TyTy = UserTy->desugar();
9093   }
9094 
9095   // Strip parens if necessary.
9096   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9097     return shouldNotPrintDirectly(Context,
9098                                   PE->getSubExpr()->getType(),
9099                                   PE->getSubExpr());
9100 
9101   // If this is a conditional expression, then its result type is constructed
9102   // via usual arithmetic conversions and thus there might be no necessary
9103   // typedef sugar there.  Recurse to operands to check for NSInteger &
9104   // Co. usage condition.
9105   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9106     QualType TrueTy, FalseTy;
9107     StringRef TrueName, FalseName;
9108 
9109     std::tie(TrueTy, TrueName) =
9110       shouldNotPrintDirectly(Context,
9111                              CO->getTrueExpr()->getType(),
9112                              CO->getTrueExpr());
9113     std::tie(FalseTy, FalseName) =
9114       shouldNotPrintDirectly(Context,
9115                              CO->getFalseExpr()->getType(),
9116                              CO->getFalseExpr());
9117 
9118     if (TrueTy == FalseTy)
9119       return std::make_pair(TrueTy, TrueName);
9120     else if (TrueTy.isNull())
9121       return std::make_pair(FalseTy, FalseName);
9122     else if (FalseTy.isNull())
9123       return std::make_pair(TrueTy, TrueName);
9124   }
9125 
9126   return std::make_pair(QualType(), StringRef());
9127 }
9128 
9129 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9130 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9131 /// type do not count.
9132 static bool
9133 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9134   QualType From = ICE->getSubExpr()->getType();
9135   QualType To = ICE->getType();
9136   // It's an integer promotion if the destination type is the promoted
9137   // source type.
9138   if (ICE->getCastKind() == CK_IntegralCast &&
9139       From->isPromotableIntegerType() &&
9140       S.Context.getPromotedIntegerType(From) == To)
9141     return true;
9142   // Look through vector types, since we do default argument promotion for
9143   // those in OpenCL.
9144   if (const auto *VecTy = From->getAs<ExtVectorType>())
9145     From = VecTy->getElementType();
9146   if (const auto *VecTy = To->getAs<ExtVectorType>())
9147     To = VecTy->getElementType();
9148   // It's a floating promotion if the source type is a lower rank.
9149   return ICE->getCastKind() == CK_FloatingCast &&
9150          S.Context.getFloatingTypeOrder(From, To) < 0;
9151 }
9152 
9153 bool
9154 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9155                                     const char *StartSpecifier,
9156                                     unsigned SpecifierLen,
9157                                     const Expr *E) {
9158   using namespace analyze_format_string;
9159   using namespace analyze_printf;
9160 
9161   // Now type check the data expression that matches the
9162   // format specifier.
9163   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9164   if (!AT.isValid())
9165     return true;
9166 
9167   QualType ExprTy = E->getType();
9168   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9169     ExprTy = TET->getUnderlyingExpr()->getType();
9170   }
9171 
9172   // Diagnose attempts to print a boolean value as a character. Unlike other
9173   // -Wformat diagnostics, this is fine from a type perspective, but it still
9174   // doesn't make sense.
9175   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9176       E->isKnownToHaveBooleanValue()) {
9177     const CharSourceRange &CSR =
9178         getSpecifierRange(StartSpecifier, SpecifierLen);
9179     SmallString<4> FSString;
9180     llvm::raw_svector_ostream os(FSString);
9181     FS.toString(os);
9182     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9183                              << FSString,
9184                          E->getExprLoc(), false, CSR);
9185     return true;
9186   }
9187 
9188   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9189   if (Match == analyze_printf::ArgType::Match)
9190     return true;
9191 
9192   // Look through argument promotions for our error message's reported type.
9193   // This includes the integral and floating promotions, but excludes array
9194   // and function pointer decay (seeing that an argument intended to be a
9195   // string has type 'char [6]' is probably more confusing than 'char *') and
9196   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9197   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9198     if (isArithmeticArgumentPromotion(S, ICE)) {
9199       E = ICE->getSubExpr();
9200       ExprTy = E->getType();
9201 
9202       // Check if we didn't match because of an implicit cast from a 'char'
9203       // or 'short' to an 'int'.  This is done because printf is a varargs
9204       // function.
9205       if (ICE->getType() == S.Context.IntTy ||
9206           ICE->getType() == S.Context.UnsignedIntTy) {
9207         // All further checking is done on the subexpression
9208         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9209             AT.matchesType(S.Context, ExprTy);
9210         if (ImplicitMatch == analyze_printf::ArgType::Match)
9211           return true;
9212         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9213             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9214           Match = ImplicitMatch;
9215       }
9216     }
9217   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9218     // Special case for 'a', which has type 'int' in C.
9219     // Note, however, that we do /not/ want to treat multibyte constants like
9220     // 'MooV' as characters! This form is deprecated but still exists. In
9221     // addition, don't treat expressions as of type 'char' if one byte length
9222     // modifier is provided.
9223     if (ExprTy == S.Context.IntTy &&
9224         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9225       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9226         ExprTy = S.Context.CharTy;
9227   }
9228 
9229   // Look through enums to their underlying type.
9230   bool IsEnum = false;
9231   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9232     ExprTy = EnumTy->getDecl()->getIntegerType();
9233     IsEnum = true;
9234   }
9235 
9236   // %C in an Objective-C context prints a unichar, not a wchar_t.
9237   // If the argument is an integer of some kind, believe the %C and suggest
9238   // a cast instead of changing the conversion specifier.
9239   QualType IntendedTy = ExprTy;
9240   if (isObjCContext() &&
9241       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9242     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9243         !ExprTy->isCharType()) {
9244       // 'unichar' is defined as a typedef of unsigned short, but we should
9245       // prefer using the typedef if it is visible.
9246       IntendedTy = S.Context.UnsignedShortTy;
9247 
9248       // While we are here, check if the value is an IntegerLiteral that happens
9249       // to be within the valid range.
9250       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9251         const llvm::APInt &V = IL->getValue();
9252         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9253           return true;
9254       }
9255 
9256       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9257                           Sema::LookupOrdinaryName);
9258       if (S.LookupName(Result, S.getCurScope())) {
9259         NamedDecl *ND = Result.getFoundDecl();
9260         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9261           if (TD->getUnderlyingType() == IntendedTy)
9262             IntendedTy = S.Context.getTypedefType(TD);
9263       }
9264     }
9265   }
9266 
9267   // Special-case some of Darwin's platform-independence types by suggesting
9268   // casts to primitive types that are known to be large enough.
9269   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9270   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9271     QualType CastTy;
9272     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9273     if (!CastTy.isNull()) {
9274       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9275       // (long in ASTContext). Only complain to pedants.
9276       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9277           (AT.isSizeT() || AT.isPtrdiffT()) &&
9278           AT.matchesType(S.Context, CastTy))
9279         Match = ArgType::NoMatchPedantic;
9280       IntendedTy = CastTy;
9281       ShouldNotPrintDirectly = true;
9282     }
9283   }
9284 
9285   // We may be able to offer a FixItHint if it is a supported type.
9286   PrintfSpecifier fixedFS = FS;
9287   bool Success =
9288       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9289 
9290   if (Success) {
9291     // Get the fix string from the fixed format specifier
9292     SmallString<16> buf;
9293     llvm::raw_svector_ostream os(buf);
9294     fixedFS.toString(os);
9295 
9296     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9297 
9298     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9299       unsigned Diag;
9300       switch (Match) {
9301       case ArgType::Match: llvm_unreachable("expected non-matching");
9302       case ArgType::NoMatchPedantic:
9303         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9304         break;
9305       case ArgType::NoMatchTypeConfusion:
9306         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9307         break;
9308       case ArgType::NoMatch:
9309         Diag = diag::warn_format_conversion_argument_type_mismatch;
9310         break;
9311       }
9312 
9313       // In this case, the specifier is wrong and should be changed to match
9314       // the argument.
9315       EmitFormatDiagnostic(S.PDiag(Diag)
9316                                << AT.getRepresentativeTypeName(S.Context)
9317                                << IntendedTy << IsEnum << E->getSourceRange(),
9318                            E->getBeginLoc(),
9319                            /*IsStringLocation*/ false, SpecRange,
9320                            FixItHint::CreateReplacement(SpecRange, os.str()));
9321     } else {
9322       // The canonical type for formatting this value is different from the
9323       // actual type of the expression. (This occurs, for example, with Darwin's
9324       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9325       // should be printed as 'long' for 64-bit compatibility.)
9326       // Rather than emitting a normal format/argument mismatch, we want to
9327       // add a cast to the recommended type (and correct the format string
9328       // if necessary).
9329       SmallString<16> CastBuf;
9330       llvm::raw_svector_ostream CastFix(CastBuf);
9331       CastFix << "(";
9332       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9333       CastFix << ")";
9334 
9335       SmallVector<FixItHint,4> Hints;
9336       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9337         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9338 
9339       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9340         // If there's already a cast present, just replace it.
9341         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9342         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9343 
9344       } else if (!requiresParensToAddCast(E)) {
9345         // If the expression has high enough precedence,
9346         // just write the C-style cast.
9347         Hints.push_back(
9348             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9349       } else {
9350         // Otherwise, add parens around the expression as well as the cast.
9351         CastFix << "(";
9352         Hints.push_back(
9353             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9354 
9355         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9356         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9357       }
9358 
9359       if (ShouldNotPrintDirectly) {
9360         // The expression has a type that should not be printed directly.
9361         // We extract the name from the typedef because we don't want to show
9362         // the underlying type in the diagnostic.
9363         StringRef Name;
9364         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9365           Name = TypedefTy->getDecl()->getName();
9366         else
9367           Name = CastTyName;
9368         unsigned Diag = Match == ArgType::NoMatchPedantic
9369                             ? diag::warn_format_argument_needs_cast_pedantic
9370                             : diag::warn_format_argument_needs_cast;
9371         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9372                                            << E->getSourceRange(),
9373                              E->getBeginLoc(), /*IsStringLocation=*/false,
9374                              SpecRange, Hints);
9375       } else {
9376         // In this case, the expression could be printed using a different
9377         // specifier, but we've decided that the specifier is probably correct
9378         // and we should cast instead. Just use the normal warning message.
9379         EmitFormatDiagnostic(
9380             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9381                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9382                 << E->getSourceRange(),
9383             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9384       }
9385     }
9386   } else {
9387     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9388                                                    SpecifierLen);
9389     // Since the warning for passing non-POD types to variadic functions
9390     // was deferred until now, we emit a warning for non-POD
9391     // arguments here.
9392     switch (S.isValidVarArgType(ExprTy)) {
9393     case Sema::VAK_Valid:
9394     case Sema::VAK_ValidInCXX11: {
9395       unsigned Diag;
9396       switch (Match) {
9397       case ArgType::Match: llvm_unreachable("expected non-matching");
9398       case ArgType::NoMatchPedantic:
9399         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9400         break;
9401       case ArgType::NoMatchTypeConfusion:
9402         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9403         break;
9404       case ArgType::NoMatch:
9405         Diag = diag::warn_format_conversion_argument_type_mismatch;
9406         break;
9407       }
9408 
9409       EmitFormatDiagnostic(
9410           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9411                         << IsEnum << CSR << E->getSourceRange(),
9412           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9413       break;
9414     }
9415     case Sema::VAK_Undefined:
9416     case Sema::VAK_MSVCUndefined:
9417       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9418                                << S.getLangOpts().CPlusPlus11 << ExprTy
9419                                << CallType
9420                                << AT.getRepresentativeTypeName(S.Context) << CSR
9421                                << E->getSourceRange(),
9422                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9423       checkForCStrMembers(AT, E);
9424       break;
9425 
9426     case Sema::VAK_Invalid:
9427       if (ExprTy->isObjCObjectType())
9428         EmitFormatDiagnostic(
9429             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9430                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9431                 << AT.getRepresentativeTypeName(S.Context) << CSR
9432                 << E->getSourceRange(),
9433             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9434       else
9435         // FIXME: If this is an initializer list, suggest removing the braces
9436         // or inserting a cast to the target type.
9437         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9438             << isa<InitListExpr>(E) << ExprTy << CallType
9439             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9440       break;
9441     }
9442 
9443     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9444            "format string specifier index out of range");
9445     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9446   }
9447 
9448   return true;
9449 }
9450 
9451 //===--- CHECK: Scanf format string checking ------------------------------===//
9452 
9453 namespace {
9454 
9455 class CheckScanfHandler : public CheckFormatHandler {
9456 public:
9457   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9458                     const Expr *origFormatExpr, Sema::FormatStringType type,
9459                     unsigned firstDataArg, unsigned numDataArgs,
9460                     const char *beg, bool hasVAListArg,
9461                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9462                     bool inFunctionCall, Sema::VariadicCallType CallType,
9463                     llvm::SmallBitVector &CheckedVarArgs,
9464                     UncoveredArgHandler &UncoveredArg)
9465       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9466                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9467                            inFunctionCall, CallType, CheckedVarArgs,
9468                            UncoveredArg) {}
9469 
9470   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9471                             const char *startSpecifier,
9472                             unsigned specifierLen) override;
9473 
9474   bool HandleInvalidScanfConversionSpecifier(
9475           const analyze_scanf::ScanfSpecifier &FS,
9476           const char *startSpecifier,
9477           unsigned specifierLen) override;
9478 
9479   void HandleIncompleteScanList(const char *start, const char *end) override;
9480 };
9481 
9482 } // namespace
9483 
9484 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9485                                                  const char *end) {
9486   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9487                        getLocationOfByte(end), /*IsStringLocation*/true,
9488                        getSpecifierRange(start, end - start));
9489 }
9490 
9491 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9492                                         const analyze_scanf::ScanfSpecifier &FS,
9493                                         const char *startSpecifier,
9494                                         unsigned specifierLen) {
9495   const analyze_scanf::ScanfConversionSpecifier &CS =
9496     FS.getConversionSpecifier();
9497 
9498   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9499                                           getLocationOfByte(CS.getStart()),
9500                                           startSpecifier, specifierLen,
9501                                           CS.getStart(), CS.getLength());
9502 }
9503 
9504 bool CheckScanfHandler::HandleScanfSpecifier(
9505                                        const analyze_scanf::ScanfSpecifier &FS,
9506                                        const char *startSpecifier,
9507                                        unsigned specifierLen) {
9508   using namespace analyze_scanf;
9509   using namespace analyze_format_string;
9510 
9511   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9512 
9513   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9514   // be used to decide if we are using positional arguments consistently.
9515   if (FS.consumesDataArgument()) {
9516     if (atFirstArg) {
9517       atFirstArg = false;
9518       usesPositionalArgs = FS.usesPositionalArg();
9519     }
9520     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9521       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9522                                         startSpecifier, specifierLen);
9523       return false;
9524     }
9525   }
9526 
9527   // Check if the field with is non-zero.
9528   const OptionalAmount &Amt = FS.getFieldWidth();
9529   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9530     if (Amt.getConstantAmount() == 0) {
9531       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9532                                                    Amt.getConstantLength());
9533       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9534                            getLocationOfByte(Amt.getStart()),
9535                            /*IsStringLocation*/true, R,
9536                            FixItHint::CreateRemoval(R));
9537     }
9538   }
9539 
9540   if (!FS.consumesDataArgument()) {
9541     // FIXME: Technically specifying a precision or field width here
9542     // makes no sense.  Worth issuing a warning at some point.
9543     return true;
9544   }
9545 
9546   // Consume the argument.
9547   unsigned argIndex = FS.getArgIndex();
9548   if (argIndex < NumDataArgs) {
9549       // The check to see if the argIndex is valid will come later.
9550       // We set the bit here because we may exit early from this
9551       // function if we encounter some other error.
9552     CoveredArgs.set(argIndex);
9553   }
9554 
9555   // Check the length modifier is valid with the given conversion specifier.
9556   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9557                                  S.getLangOpts()))
9558     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9559                                 diag::warn_format_nonsensical_length);
9560   else if (!FS.hasStandardLengthModifier())
9561     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9562   else if (!FS.hasStandardLengthConversionCombination())
9563     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9564                                 diag::warn_format_non_standard_conversion_spec);
9565 
9566   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9567     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9568 
9569   // The remaining checks depend on the data arguments.
9570   if (HasVAListArg)
9571     return true;
9572 
9573   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9574     return false;
9575 
9576   // Check that the argument type matches the format specifier.
9577   const Expr *Ex = getDataArg(argIndex);
9578   if (!Ex)
9579     return true;
9580 
9581   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9582 
9583   if (!AT.isValid()) {
9584     return true;
9585   }
9586 
9587   analyze_format_string::ArgType::MatchKind Match =
9588       AT.matchesType(S.Context, Ex->getType());
9589   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9590   if (Match == analyze_format_string::ArgType::Match)
9591     return true;
9592 
9593   ScanfSpecifier fixedFS = FS;
9594   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9595                                  S.getLangOpts(), S.Context);
9596 
9597   unsigned Diag =
9598       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9599                : diag::warn_format_conversion_argument_type_mismatch;
9600 
9601   if (Success) {
9602     // Get the fix string from the fixed format specifier.
9603     SmallString<128> buf;
9604     llvm::raw_svector_ostream os(buf);
9605     fixedFS.toString(os);
9606 
9607     EmitFormatDiagnostic(
9608         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9609                       << Ex->getType() << false << Ex->getSourceRange(),
9610         Ex->getBeginLoc(),
9611         /*IsStringLocation*/ false,
9612         getSpecifierRange(startSpecifier, specifierLen),
9613         FixItHint::CreateReplacement(
9614             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9615   } else {
9616     EmitFormatDiagnostic(S.PDiag(Diag)
9617                              << AT.getRepresentativeTypeName(S.Context)
9618                              << Ex->getType() << false << Ex->getSourceRange(),
9619                          Ex->getBeginLoc(),
9620                          /*IsStringLocation*/ false,
9621                          getSpecifierRange(startSpecifier, specifierLen));
9622   }
9623 
9624   return true;
9625 }
9626 
9627 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9628                               const Expr *OrigFormatExpr,
9629                               ArrayRef<const Expr *> Args,
9630                               bool HasVAListArg, unsigned format_idx,
9631                               unsigned firstDataArg,
9632                               Sema::FormatStringType Type,
9633                               bool inFunctionCall,
9634                               Sema::VariadicCallType CallType,
9635                               llvm::SmallBitVector &CheckedVarArgs,
9636                               UncoveredArgHandler &UncoveredArg,
9637                               bool IgnoreStringsWithoutSpecifiers) {
9638   // CHECK: is the format string a wide literal?
9639   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9640     CheckFormatHandler::EmitFormatDiagnostic(
9641         S, inFunctionCall, Args[format_idx],
9642         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9643         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9644     return;
9645   }
9646 
9647   // Str - The format string.  NOTE: this is NOT null-terminated!
9648   StringRef StrRef = FExpr->getString();
9649   const char *Str = StrRef.data();
9650   // Account for cases where the string literal is truncated in a declaration.
9651   const ConstantArrayType *T =
9652     S.Context.getAsConstantArrayType(FExpr->getType());
9653   assert(T && "String literal not of constant array type!");
9654   size_t TypeSize = T->getSize().getZExtValue();
9655   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9656   const unsigned numDataArgs = Args.size() - firstDataArg;
9657 
9658   if (IgnoreStringsWithoutSpecifiers &&
9659       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9660           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9661     return;
9662 
9663   // Emit a warning if the string literal is truncated and does not contain an
9664   // embedded null character.
9665   if (TypeSize <= StrRef.size() &&
9666       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9667     CheckFormatHandler::EmitFormatDiagnostic(
9668         S, inFunctionCall, Args[format_idx],
9669         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9670         FExpr->getBeginLoc(),
9671         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9672     return;
9673   }
9674 
9675   // CHECK: empty format string?
9676   if (StrLen == 0 && numDataArgs > 0) {
9677     CheckFormatHandler::EmitFormatDiagnostic(
9678         S, inFunctionCall, Args[format_idx],
9679         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9680         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9681     return;
9682   }
9683 
9684   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9685       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9686       Type == Sema::FST_OSTrace) {
9687     CheckPrintfHandler H(
9688         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9689         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9690         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9691         CheckedVarArgs, UncoveredArg);
9692 
9693     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9694                                                   S.getLangOpts(),
9695                                                   S.Context.getTargetInfo(),
9696                                             Type == Sema::FST_FreeBSDKPrintf))
9697       H.DoneProcessing();
9698   } else if (Type == Sema::FST_Scanf) {
9699     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9700                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9701                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9702 
9703     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9704                                                  S.getLangOpts(),
9705                                                  S.Context.getTargetInfo()))
9706       H.DoneProcessing();
9707   } // TODO: handle other formats
9708 }
9709 
9710 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9711   // Str - The format string.  NOTE: this is NOT null-terminated!
9712   StringRef StrRef = FExpr->getString();
9713   const char *Str = StrRef.data();
9714   // Account for cases where the string literal is truncated in a declaration.
9715   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9716   assert(T && "String literal not of constant array type!");
9717   size_t TypeSize = T->getSize().getZExtValue();
9718   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9719   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9720                                                          getLangOpts(),
9721                                                          Context.getTargetInfo());
9722 }
9723 
9724 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9725 
9726 // Returns the related absolute value function that is larger, of 0 if one
9727 // does not exist.
9728 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9729   switch (AbsFunction) {
9730   default:
9731     return 0;
9732 
9733   case Builtin::BI__builtin_abs:
9734     return Builtin::BI__builtin_labs;
9735   case Builtin::BI__builtin_labs:
9736     return Builtin::BI__builtin_llabs;
9737   case Builtin::BI__builtin_llabs:
9738     return 0;
9739 
9740   case Builtin::BI__builtin_fabsf:
9741     return Builtin::BI__builtin_fabs;
9742   case Builtin::BI__builtin_fabs:
9743     return Builtin::BI__builtin_fabsl;
9744   case Builtin::BI__builtin_fabsl:
9745     return 0;
9746 
9747   case Builtin::BI__builtin_cabsf:
9748     return Builtin::BI__builtin_cabs;
9749   case Builtin::BI__builtin_cabs:
9750     return Builtin::BI__builtin_cabsl;
9751   case Builtin::BI__builtin_cabsl:
9752     return 0;
9753 
9754   case Builtin::BIabs:
9755     return Builtin::BIlabs;
9756   case Builtin::BIlabs:
9757     return Builtin::BIllabs;
9758   case Builtin::BIllabs:
9759     return 0;
9760 
9761   case Builtin::BIfabsf:
9762     return Builtin::BIfabs;
9763   case Builtin::BIfabs:
9764     return Builtin::BIfabsl;
9765   case Builtin::BIfabsl:
9766     return 0;
9767 
9768   case Builtin::BIcabsf:
9769    return Builtin::BIcabs;
9770   case Builtin::BIcabs:
9771     return Builtin::BIcabsl;
9772   case Builtin::BIcabsl:
9773     return 0;
9774   }
9775 }
9776 
9777 // Returns the argument type of the absolute value function.
9778 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9779                                              unsigned AbsType) {
9780   if (AbsType == 0)
9781     return QualType();
9782 
9783   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9784   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9785   if (Error != ASTContext::GE_None)
9786     return QualType();
9787 
9788   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9789   if (!FT)
9790     return QualType();
9791 
9792   if (FT->getNumParams() != 1)
9793     return QualType();
9794 
9795   return FT->getParamType(0);
9796 }
9797 
9798 // Returns the best absolute value function, or zero, based on type and
9799 // current absolute value function.
9800 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9801                                    unsigned AbsFunctionKind) {
9802   unsigned BestKind = 0;
9803   uint64_t ArgSize = Context.getTypeSize(ArgType);
9804   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9805        Kind = getLargerAbsoluteValueFunction(Kind)) {
9806     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9807     if (Context.getTypeSize(ParamType) >= ArgSize) {
9808       if (BestKind == 0)
9809         BestKind = Kind;
9810       else if (Context.hasSameType(ParamType, ArgType)) {
9811         BestKind = Kind;
9812         break;
9813       }
9814     }
9815   }
9816   return BestKind;
9817 }
9818 
9819 enum AbsoluteValueKind {
9820   AVK_Integer,
9821   AVK_Floating,
9822   AVK_Complex
9823 };
9824 
9825 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9826   if (T->isIntegralOrEnumerationType())
9827     return AVK_Integer;
9828   if (T->isRealFloatingType())
9829     return AVK_Floating;
9830   if (T->isAnyComplexType())
9831     return AVK_Complex;
9832 
9833   llvm_unreachable("Type not integer, floating, or complex");
9834 }
9835 
9836 // Changes the absolute value function to a different type.  Preserves whether
9837 // the function is a builtin.
9838 static unsigned changeAbsFunction(unsigned AbsKind,
9839                                   AbsoluteValueKind ValueKind) {
9840   switch (ValueKind) {
9841   case AVK_Integer:
9842     switch (AbsKind) {
9843     default:
9844       return 0;
9845     case Builtin::BI__builtin_fabsf:
9846     case Builtin::BI__builtin_fabs:
9847     case Builtin::BI__builtin_fabsl:
9848     case Builtin::BI__builtin_cabsf:
9849     case Builtin::BI__builtin_cabs:
9850     case Builtin::BI__builtin_cabsl:
9851       return Builtin::BI__builtin_abs;
9852     case Builtin::BIfabsf:
9853     case Builtin::BIfabs:
9854     case Builtin::BIfabsl:
9855     case Builtin::BIcabsf:
9856     case Builtin::BIcabs:
9857     case Builtin::BIcabsl:
9858       return Builtin::BIabs;
9859     }
9860   case AVK_Floating:
9861     switch (AbsKind) {
9862     default:
9863       return 0;
9864     case Builtin::BI__builtin_abs:
9865     case Builtin::BI__builtin_labs:
9866     case Builtin::BI__builtin_llabs:
9867     case Builtin::BI__builtin_cabsf:
9868     case Builtin::BI__builtin_cabs:
9869     case Builtin::BI__builtin_cabsl:
9870       return Builtin::BI__builtin_fabsf;
9871     case Builtin::BIabs:
9872     case Builtin::BIlabs:
9873     case Builtin::BIllabs:
9874     case Builtin::BIcabsf:
9875     case Builtin::BIcabs:
9876     case Builtin::BIcabsl:
9877       return Builtin::BIfabsf;
9878     }
9879   case AVK_Complex:
9880     switch (AbsKind) {
9881     default:
9882       return 0;
9883     case Builtin::BI__builtin_abs:
9884     case Builtin::BI__builtin_labs:
9885     case Builtin::BI__builtin_llabs:
9886     case Builtin::BI__builtin_fabsf:
9887     case Builtin::BI__builtin_fabs:
9888     case Builtin::BI__builtin_fabsl:
9889       return Builtin::BI__builtin_cabsf;
9890     case Builtin::BIabs:
9891     case Builtin::BIlabs:
9892     case Builtin::BIllabs:
9893     case Builtin::BIfabsf:
9894     case Builtin::BIfabs:
9895     case Builtin::BIfabsl:
9896       return Builtin::BIcabsf;
9897     }
9898   }
9899   llvm_unreachable("Unable to convert function");
9900 }
9901 
9902 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9903   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9904   if (!FnInfo)
9905     return 0;
9906 
9907   switch (FDecl->getBuiltinID()) {
9908   default:
9909     return 0;
9910   case Builtin::BI__builtin_abs:
9911   case Builtin::BI__builtin_fabs:
9912   case Builtin::BI__builtin_fabsf:
9913   case Builtin::BI__builtin_fabsl:
9914   case Builtin::BI__builtin_labs:
9915   case Builtin::BI__builtin_llabs:
9916   case Builtin::BI__builtin_cabs:
9917   case Builtin::BI__builtin_cabsf:
9918   case Builtin::BI__builtin_cabsl:
9919   case Builtin::BIabs:
9920   case Builtin::BIlabs:
9921   case Builtin::BIllabs:
9922   case Builtin::BIfabs:
9923   case Builtin::BIfabsf:
9924   case Builtin::BIfabsl:
9925   case Builtin::BIcabs:
9926   case Builtin::BIcabsf:
9927   case Builtin::BIcabsl:
9928     return FDecl->getBuiltinID();
9929   }
9930   llvm_unreachable("Unknown Builtin type");
9931 }
9932 
9933 // If the replacement is valid, emit a note with replacement function.
9934 // Additionally, suggest including the proper header if not already included.
9935 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9936                             unsigned AbsKind, QualType ArgType) {
9937   bool EmitHeaderHint = true;
9938   const char *HeaderName = nullptr;
9939   const char *FunctionName = nullptr;
9940   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9941     FunctionName = "std::abs";
9942     if (ArgType->isIntegralOrEnumerationType()) {
9943       HeaderName = "cstdlib";
9944     } else if (ArgType->isRealFloatingType()) {
9945       HeaderName = "cmath";
9946     } else {
9947       llvm_unreachable("Invalid Type");
9948     }
9949 
9950     // Lookup all std::abs
9951     if (NamespaceDecl *Std = S.getStdNamespace()) {
9952       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9953       R.suppressDiagnostics();
9954       S.LookupQualifiedName(R, Std);
9955 
9956       for (const auto *I : R) {
9957         const FunctionDecl *FDecl = nullptr;
9958         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9959           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9960         } else {
9961           FDecl = dyn_cast<FunctionDecl>(I);
9962         }
9963         if (!FDecl)
9964           continue;
9965 
9966         // Found std::abs(), check that they are the right ones.
9967         if (FDecl->getNumParams() != 1)
9968           continue;
9969 
9970         // Check that the parameter type can handle the argument.
9971         QualType ParamType = FDecl->getParamDecl(0)->getType();
9972         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9973             S.Context.getTypeSize(ArgType) <=
9974                 S.Context.getTypeSize(ParamType)) {
9975           // Found a function, don't need the header hint.
9976           EmitHeaderHint = false;
9977           break;
9978         }
9979       }
9980     }
9981   } else {
9982     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9983     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9984 
9985     if (HeaderName) {
9986       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9987       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9988       R.suppressDiagnostics();
9989       S.LookupName(R, S.getCurScope());
9990 
9991       if (R.isSingleResult()) {
9992         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9993         if (FD && FD->getBuiltinID() == AbsKind) {
9994           EmitHeaderHint = false;
9995         } else {
9996           return;
9997         }
9998       } else if (!R.empty()) {
9999         return;
10000       }
10001     }
10002   }
10003 
10004   S.Diag(Loc, diag::note_replace_abs_function)
10005       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10006 
10007   if (!HeaderName)
10008     return;
10009 
10010   if (!EmitHeaderHint)
10011     return;
10012 
10013   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10014                                                     << FunctionName;
10015 }
10016 
10017 template <std::size_t StrLen>
10018 static bool IsStdFunction(const FunctionDecl *FDecl,
10019                           const char (&Str)[StrLen]) {
10020   if (!FDecl)
10021     return false;
10022   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10023     return false;
10024   if (!FDecl->isInStdNamespace())
10025     return false;
10026 
10027   return true;
10028 }
10029 
10030 // Warn when using the wrong abs() function.
10031 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10032                                       const FunctionDecl *FDecl) {
10033   if (Call->getNumArgs() != 1)
10034     return;
10035 
10036   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10037   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10038   if (AbsKind == 0 && !IsStdAbs)
10039     return;
10040 
10041   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10042   QualType ParamType = Call->getArg(0)->getType();
10043 
10044   // Unsigned types cannot be negative.  Suggest removing the absolute value
10045   // function call.
10046   if (ArgType->isUnsignedIntegerType()) {
10047     const char *FunctionName =
10048         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10049     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10050     Diag(Call->getExprLoc(), diag::note_remove_abs)
10051         << FunctionName
10052         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10053     return;
10054   }
10055 
10056   // Taking the absolute value of a pointer is very suspicious, they probably
10057   // wanted to index into an array, dereference a pointer, call a function, etc.
10058   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10059     unsigned DiagType = 0;
10060     if (ArgType->isFunctionType())
10061       DiagType = 1;
10062     else if (ArgType->isArrayType())
10063       DiagType = 2;
10064 
10065     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10066     return;
10067   }
10068 
10069   // std::abs has overloads which prevent most of the absolute value problems
10070   // from occurring.
10071   if (IsStdAbs)
10072     return;
10073 
10074   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10075   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10076 
10077   // The argument and parameter are the same kind.  Check if they are the right
10078   // size.
10079   if (ArgValueKind == ParamValueKind) {
10080     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10081       return;
10082 
10083     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10084     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10085         << FDecl << ArgType << ParamType;
10086 
10087     if (NewAbsKind == 0)
10088       return;
10089 
10090     emitReplacement(*this, Call->getExprLoc(),
10091                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10092     return;
10093   }
10094 
10095   // ArgValueKind != ParamValueKind
10096   // The wrong type of absolute value function was used.  Attempt to find the
10097   // proper one.
10098   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10099   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10100   if (NewAbsKind == 0)
10101     return;
10102 
10103   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10104       << FDecl << ParamValueKind << ArgValueKind;
10105 
10106   emitReplacement(*this, Call->getExprLoc(),
10107                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10108 }
10109 
10110 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10111 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10112                                 const FunctionDecl *FDecl) {
10113   if (!Call || !FDecl) return;
10114 
10115   // Ignore template specializations and macros.
10116   if (inTemplateInstantiation()) return;
10117   if (Call->getExprLoc().isMacroID()) return;
10118 
10119   // Only care about the one template argument, two function parameter std::max
10120   if (Call->getNumArgs() != 2) return;
10121   if (!IsStdFunction(FDecl, "max")) return;
10122   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10123   if (!ArgList) return;
10124   if (ArgList->size() != 1) return;
10125 
10126   // Check that template type argument is unsigned integer.
10127   const auto& TA = ArgList->get(0);
10128   if (TA.getKind() != TemplateArgument::Type) return;
10129   QualType ArgType = TA.getAsType();
10130   if (!ArgType->isUnsignedIntegerType()) return;
10131 
10132   // See if either argument is a literal zero.
10133   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10134     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10135     if (!MTE) return false;
10136     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10137     if (!Num) return false;
10138     if (Num->getValue() != 0) return false;
10139     return true;
10140   };
10141 
10142   const Expr *FirstArg = Call->getArg(0);
10143   const Expr *SecondArg = Call->getArg(1);
10144   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10145   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10146 
10147   // Only warn when exactly one argument is zero.
10148   if (IsFirstArgZero == IsSecondArgZero) return;
10149 
10150   SourceRange FirstRange = FirstArg->getSourceRange();
10151   SourceRange SecondRange = SecondArg->getSourceRange();
10152 
10153   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10154 
10155   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10156       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10157 
10158   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10159   SourceRange RemovalRange;
10160   if (IsFirstArgZero) {
10161     RemovalRange = SourceRange(FirstRange.getBegin(),
10162                                SecondRange.getBegin().getLocWithOffset(-1));
10163   } else {
10164     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10165                                SecondRange.getEnd());
10166   }
10167 
10168   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10169         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10170         << FixItHint::CreateRemoval(RemovalRange);
10171 }
10172 
10173 //===--- CHECK: Standard memory functions ---------------------------------===//
10174 
10175 /// Takes the expression passed to the size_t parameter of functions
10176 /// such as memcmp, strncat, etc and warns if it's a comparison.
10177 ///
10178 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10179 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10180                                            IdentifierInfo *FnName,
10181                                            SourceLocation FnLoc,
10182                                            SourceLocation RParenLoc) {
10183   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10184   if (!Size)
10185     return false;
10186 
10187   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10188   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10189     return false;
10190 
10191   SourceRange SizeRange = Size->getSourceRange();
10192   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10193       << SizeRange << FnName;
10194   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10195       << FnName
10196       << FixItHint::CreateInsertion(
10197              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10198       << FixItHint::CreateRemoval(RParenLoc);
10199   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10200       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10201       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10202                                     ")");
10203 
10204   return true;
10205 }
10206 
10207 /// Determine whether the given type is or contains a dynamic class type
10208 /// (e.g., whether it has a vtable).
10209 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10210                                                      bool &IsContained) {
10211   // Look through array types while ignoring qualifiers.
10212   const Type *Ty = T->getBaseElementTypeUnsafe();
10213   IsContained = false;
10214 
10215   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10216   RD = RD ? RD->getDefinition() : nullptr;
10217   if (!RD || RD->isInvalidDecl())
10218     return nullptr;
10219 
10220   if (RD->isDynamicClass())
10221     return RD;
10222 
10223   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10224   // It's impossible for a class to transitively contain itself by value, so
10225   // infinite recursion is impossible.
10226   for (auto *FD : RD->fields()) {
10227     bool SubContained;
10228     if (const CXXRecordDecl *ContainedRD =
10229             getContainedDynamicClass(FD->getType(), SubContained)) {
10230       IsContained = true;
10231       return ContainedRD;
10232     }
10233   }
10234 
10235   return nullptr;
10236 }
10237 
10238 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10239   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10240     if (Unary->getKind() == UETT_SizeOf)
10241       return Unary;
10242   return nullptr;
10243 }
10244 
10245 /// If E is a sizeof expression, returns its argument expression,
10246 /// otherwise returns NULL.
10247 static const Expr *getSizeOfExprArg(const Expr *E) {
10248   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10249     if (!SizeOf->isArgumentType())
10250       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10251   return nullptr;
10252 }
10253 
10254 /// If E is a sizeof expression, returns its argument type.
10255 static QualType getSizeOfArgType(const Expr *E) {
10256   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10257     return SizeOf->getTypeOfArgument();
10258   return QualType();
10259 }
10260 
10261 namespace {
10262 
10263 struct SearchNonTrivialToInitializeField
10264     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10265   using Super =
10266       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10267 
10268   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10269 
10270   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10271                      SourceLocation SL) {
10272     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10273       asDerived().visitArray(PDIK, AT, SL);
10274       return;
10275     }
10276 
10277     Super::visitWithKind(PDIK, FT, SL);
10278   }
10279 
10280   void visitARCStrong(QualType FT, SourceLocation SL) {
10281     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10282   }
10283   void visitARCWeak(QualType FT, SourceLocation SL) {
10284     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10285   }
10286   void visitStruct(QualType FT, SourceLocation SL) {
10287     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10288       visit(FD->getType(), FD->getLocation());
10289   }
10290   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10291                   const ArrayType *AT, SourceLocation SL) {
10292     visit(getContext().getBaseElementType(AT), SL);
10293   }
10294   void visitTrivial(QualType FT, SourceLocation SL) {}
10295 
10296   static void diag(QualType RT, const Expr *E, Sema &S) {
10297     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10298   }
10299 
10300   ASTContext &getContext() { return S.getASTContext(); }
10301 
10302   const Expr *E;
10303   Sema &S;
10304 };
10305 
10306 struct SearchNonTrivialToCopyField
10307     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10308   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10309 
10310   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10311 
10312   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10313                      SourceLocation SL) {
10314     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10315       asDerived().visitArray(PCK, AT, SL);
10316       return;
10317     }
10318 
10319     Super::visitWithKind(PCK, FT, SL);
10320   }
10321 
10322   void visitARCStrong(QualType FT, SourceLocation SL) {
10323     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10324   }
10325   void visitARCWeak(QualType FT, SourceLocation SL) {
10326     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10327   }
10328   void visitStruct(QualType FT, SourceLocation SL) {
10329     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10330       visit(FD->getType(), FD->getLocation());
10331   }
10332   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10333                   SourceLocation SL) {
10334     visit(getContext().getBaseElementType(AT), SL);
10335   }
10336   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10337                 SourceLocation SL) {}
10338   void visitTrivial(QualType FT, SourceLocation SL) {}
10339   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10340 
10341   static void diag(QualType RT, const Expr *E, Sema &S) {
10342     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10343   }
10344 
10345   ASTContext &getContext() { return S.getASTContext(); }
10346 
10347   const Expr *E;
10348   Sema &S;
10349 };
10350 
10351 }
10352 
10353 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10354 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10355   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10356 
10357   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10358     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10359       return false;
10360 
10361     return doesExprLikelyComputeSize(BO->getLHS()) ||
10362            doesExprLikelyComputeSize(BO->getRHS());
10363   }
10364 
10365   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10366 }
10367 
10368 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10369 ///
10370 /// \code
10371 ///   #define MACRO 0
10372 ///   foo(MACRO);
10373 ///   foo(0);
10374 /// \endcode
10375 ///
10376 /// This should return true for the first call to foo, but not for the second
10377 /// (regardless of whether foo is a macro or function).
10378 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10379                                         SourceLocation CallLoc,
10380                                         SourceLocation ArgLoc) {
10381   if (!CallLoc.isMacroID())
10382     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10383 
10384   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10385          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10386 }
10387 
10388 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10389 /// last two arguments transposed.
10390 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10391   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10392     return;
10393 
10394   const Expr *SizeArg =
10395     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10396 
10397   auto isLiteralZero = [](const Expr *E) {
10398     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10399   };
10400 
10401   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10402   SourceLocation CallLoc = Call->getRParenLoc();
10403   SourceManager &SM = S.getSourceManager();
10404   if (isLiteralZero(SizeArg) &&
10405       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10406 
10407     SourceLocation DiagLoc = SizeArg->getExprLoc();
10408 
10409     // Some platforms #define bzero to __builtin_memset. See if this is the
10410     // case, and if so, emit a better diagnostic.
10411     if (BId == Builtin::BIbzero ||
10412         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10413                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10414       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10415       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10416     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10417       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10418       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10419     }
10420     return;
10421   }
10422 
10423   // If the second argument to a memset is a sizeof expression and the third
10424   // isn't, this is also likely an error. This should catch
10425   // 'memset(buf, sizeof(buf), 0xff)'.
10426   if (BId == Builtin::BImemset &&
10427       doesExprLikelyComputeSize(Call->getArg(1)) &&
10428       !doesExprLikelyComputeSize(Call->getArg(2))) {
10429     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10430     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10431     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10432     return;
10433   }
10434 }
10435 
10436 /// Check for dangerous or invalid arguments to memset().
10437 ///
10438 /// This issues warnings on known problematic, dangerous or unspecified
10439 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10440 /// function calls.
10441 ///
10442 /// \param Call The call expression to diagnose.
10443 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10444                                    unsigned BId,
10445                                    IdentifierInfo *FnName) {
10446   assert(BId != 0);
10447 
10448   // It is possible to have a non-standard definition of memset.  Validate
10449   // we have enough arguments, and if not, abort further checking.
10450   unsigned ExpectedNumArgs =
10451       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10452   if (Call->getNumArgs() < ExpectedNumArgs)
10453     return;
10454 
10455   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10456                       BId == Builtin::BIstrndup ? 1 : 2);
10457   unsigned LenArg =
10458       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10459   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10460 
10461   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10462                                      Call->getBeginLoc(), Call->getRParenLoc()))
10463     return;
10464 
10465   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10466   CheckMemaccessSize(*this, BId, Call);
10467 
10468   // We have special checking when the length is a sizeof expression.
10469   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10470   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10471   llvm::FoldingSetNodeID SizeOfArgID;
10472 
10473   // Although widely used, 'bzero' is not a standard function. Be more strict
10474   // with the argument types before allowing diagnostics and only allow the
10475   // form bzero(ptr, sizeof(...)).
10476   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10477   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10478     return;
10479 
10480   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10481     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10482     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10483 
10484     QualType DestTy = Dest->getType();
10485     QualType PointeeTy;
10486     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10487       PointeeTy = DestPtrTy->getPointeeType();
10488 
10489       // Never warn about void type pointers. This can be used to suppress
10490       // false positives.
10491       if (PointeeTy->isVoidType())
10492         continue;
10493 
10494       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10495       // actually comparing the expressions for equality. Because computing the
10496       // expression IDs can be expensive, we only do this if the diagnostic is
10497       // enabled.
10498       if (SizeOfArg &&
10499           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10500                            SizeOfArg->getExprLoc())) {
10501         // We only compute IDs for expressions if the warning is enabled, and
10502         // cache the sizeof arg's ID.
10503         if (SizeOfArgID == llvm::FoldingSetNodeID())
10504           SizeOfArg->Profile(SizeOfArgID, Context, true);
10505         llvm::FoldingSetNodeID DestID;
10506         Dest->Profile(DestID, Context, true);
10507         if (DestID == SizeOfArgID) {
10508           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10509           //       over sizeof(src) as well.
10510           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10511           StringRef ReadableName = FnName->getName();
10512 
10513           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10514             if (UnaryOp->getOpcode() == UO_AddrOf)
10515               ActionIdx = 1; // If its an address-of operator, just remove it.
10516           if (!PointeeTy->isIncompleteType() &&
10517               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10518             ActionIdx = 2; // If the pointee's size is sizeof(char),
10519                            // suggest an explicit length.
10520 
10521           // If the function is defined as a builtin macro, do not show macro
10522           // expansion.
10523           SourceLocation SL = SizeOfArg->getExprLoc();
10524           SourceRange DSR = Dest->getSourceRange();
10525           SourceRange SSR = SizeOfArg->getSourceRange();
10526           SourceManager &SM = getSourceManager();
10527 
10528           if (SM.isMacroArgExpansion(SL)) {
10529             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10530             SL = SM.getSpellingLoc(SL);
10531             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10532                              SM.getSpellingLoc(DSR.getEnd()));
10533             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10534                              SM.getSpellingLoc(SSR.getEnd()));
10535           }
10536 
10537           DiagRuntimeBehavior(SL, SizeOfArg,
10538                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10539                                 << ReadableName
10540                                 << PointeeTy
10541                                 << DestTy
10542                                 << DSR
10543                                 << SSR);
10544           DiagRuntimeBehavior(SL, SizeOfArg,
10545                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10546                                 << ActionIdx
10547                                 << SSR);
10548 
10549           break;
10550         }
10551       }
10552 
10553       // Also check for cases where the sizeof argument is the exact same
10554       // type as the memory argument, and where it points to a user-defined
10555       // record type.
10556       if (SizeOfArgTy != QualType()) {
10557         if (PointeeTy->isRecordType() &&
10558             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10559           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10560                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10561                                 << FnName << SizeOfArgTy << ArgIdx
10562                                 << PointeeTy << Dest->getSourceRange()
10563                                 << LenExpr->getSourceRange());
10564           break;
10565         }
10566       }
10567     } else if (DestTy->isArrayType()) {
10568       PointeeTy = DestTy;
10569     }
10570 
10571     if (PointeeTy == QualType())
10572       continue;
10573 
10574     // Always complain about dynamic classes.
10575     bool IsContained;
10576     if (const CXXRecordDecl *ContainedRD =
10577             getContainedDynamicClass(PointeeTy, IsContained)) {
10578 
10579       unsigned OperationType = 0;
10580       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10581       // "overwritten" if we're warning about the destination for any call
10582       // but memcmp; otherwise a verb appropriate to the call.
10583       if (ArgIdx != 0 || IsCmp) {
10584         if (BId == Builtin::BImemcpy)
10585           OperationType = 1;
10586         else if(BId == Builtin::BImemmove)
10587           OperationType = 2;
10588         else if (IsCmp)
10589           OperationType = 3;
10590       }
10591 
10592       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10593                           PDiag(diag::warn_dyn_class_memaccess)
10594                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10595                               << IsContained << ContainedRD << OperationType
10596                               << Call->getCallee()->getSourceRange());
10597     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10598              BId != Builtin::BImemset)
10599       DiagRuntimeBehavior(
10600         Dest->getExprLoc(), Dest,
10601         PDiag(diag::warn_arc_object_memaccess)
10602           << ArgIdx << FnName << PointeeTy
10603           << Call->getCallee()->getSourceRange());
10604     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10605       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10606           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10607         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10608                             PDiag(diag::warn_cstruct_memaccess)
10609                                 << ArgIdx << FnName << PointeeTy << 0);
10610         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10611       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10612                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10613         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10614                             PDiag(diag::warn_cstruct_memaccess)
10615                                 << ArgIdx << FnName << PointeeTy << 1);
10616         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10617       } else {
10618         continue;
10619       }
10620     } else
10621       continue;
10622 
10623     DiagRuntimeBehavior(
10624       Dest->getExprLoc(), Dest,
10625       PDiag(diag::note_bad_memaccess_silence)
10626         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10627     break;
10628   }
10629 }
10630 
10631 // A little helper routine: ignore addition and subtraction of integer literals.
10632 // This intentionally does not ignore all integer constant expressions because
10633 // we don't want to remove sizeof().
10634 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10635   Ex = Ex->IgnoreParenCasts();
10636 
10637   while (true) {
10638     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10639     if (!BO || !BO->isAdditiveOp())
10640       break;
10641 
10642     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10643     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10644 
10645     if (isa<IntegerLiteral>(RHS))
10646       Ex = LHS;
10647     else if (isa<IntegerLiteral>(LHS))
10648       Ex = RHS;
10649     else
10650       break;
10651   }
10652 
10653   return Ex;
10654 }
10655 
10656 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10657                                                       ASTContext &Context) {
10658   // Only handle constant-sized or VLAs, but not flexible members.
10659   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10660     // Only issue the FIXIT for arrays of size > 1.
10661     if (CAT->getSize().getSExtValue() <= 1)
10662       return false;
10663   } else if (!Ty->isVariableArrayType()) {
10664     return false;
10665   }
10666   return true;
10667 }
10668 
10669 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10670 // be the size of the source, instead of the destination.
10671 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10672                                     IdentifierInfo *FnName) {
10673 
10674   // Don't crash if the user has the wrong number of arguments
10675   unsigned NumArgs = Call->getNumArgs();
10676   if ((NumArgs != 3) && (NumArgs != 4))
10677     return;
10678 
10679   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10680   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10681   const Expr *CompareWithSrc = nullptr;
10682 
10683   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10684                                      Call->getBeginLoc(), Call->getRParenLoc()))
10685     return;
10686 
10687   // Look for 'strlcpy(dst, x, sizeof(x))'
10688   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10689     CompareWithSrc = Ex;
10690   else {
10691     // Look for 'strlcpy(dst, x, strlen(x))'
10692     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10693       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10694           SizeCall->getNumArgs() == 1)
10695         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10696     }
10697   }
10698 
10699   if (!CompareWithSrc)
10700     return;
10701 
10702   // Determine if the argument to sizeof/strlen is equal to the source
10703   // argument.  In principle there's all kinds of things you could do
10704   // here, for instance creating an == expression and evaluating it with
10705   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10706   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10707   if (!SrcArgDRE)
10708     return;
10709 
10710   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10711   if (!CompareWithSrcDRE ||
10712       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10713     return;
10714 
10715   const Expr *OriginalSizeArg = Call->getArg(2);
10716   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10717       << OriginalSizeArg->getSourceRange() << FnName;
10718 
10719   // Output a FIXIT hint if the destination is an array (rather than a
10720   // pointer to an array).  This could be enhanced to handle some
10721   // pointers if we know the actual size, like if DstArg is 'array+2'
10722   // we could say 'sizeof(array)-2'.
10723   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10724   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10725     return;
10726 
10727   SmallString<128> sizeString;
10728   llvm::raw_svector_ostream OS(sizeString);
10729   OS << "sizeof(";
10730   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10731   OS << ")";
10732 
10733   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10734       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10735                                       OS.str());
10736 }
10737 
10738 /// Check if two expressions refer to the same declaration.
10739 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10740   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10741     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10742       return D1->getDecl() == D2->getDecl();
10743   return false;
10744 }
10745 
10746 static const Expr *getStrlenExprArg(const Expr *E) {
10747   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10748     const FunctionDecl *FD = CE->getDirectCallee();
10749     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10750       return nullptr;
10751     return CE->getArg(0)->IgnoreParenCasts();
10752   }
10753   return nullptr;
10754 }
10755 
10756 // Warn on anti-patterns as the 'size' argument to strncat.
10757 // The correct size argument should look like following:
10758 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10759 void Sema::CheckStrncatArguments(const CallExpr *CE,
10760                                  IdentifierInfo *FnName) {
10761   // Don't crash if the user has the wrong number of arguments.
10762   if (CE->getNumArgs() < 3)
10763     return;
10764   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10765   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10766   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10767 
10768   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10769                                      CE->getRParenLoc()))
10770     return;
10771 
10772   // Identify common expressions, which are wrongly used as the size argument
10773   // to strncat and may lead to buffer overflows.
10774   unsigned PatternType = 0;
10775   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10776     // - sizeof(dst)
10777     if (referToTheSameDecl(SizeOfArg, DstArg))
10778       PatternType = 1;
10779     // - sizeof(src)
10780     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10781       PatternType = 2;
10782   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10783     if (BE->getOpcode() == BO_Sub) {
10784       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10785       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10786       // - sizeof(dst) - strlen(dst)
10787       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10788           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10789         PatternType = 1;
10790       // - sizeof(src) - (anything)
10791       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10792         PatternType = 2;
10793     }
10794   }
10795 
10796   if (PatternType == 0)
10797     return;
10798 
10799   // Generate the diagnostic.
10800   SourceLocation SL = LenArg->getBeginLoc();
10801   SourceRange SR = LenArg->getSourceRange();
10802   SourceManager &SM = getSourceManager();
10803 
10804   // If the function is defined as a builtin macro, do not show macro expansion.
10805   if (SM.isMacroArgExpansion(SL)) {
10806     SL = SM.getSpellingLoc(SL);
10807     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10808                      SM.getSpellingLoc(SR.getEnd()));
10809   }
10810 
10811   // Check if the destination is an array (rather than a pointer to an array).
10812   QualType DstTy = DstArg->getType();
10813   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10814                                                                     Context);
10815   if (!isKnownSizeArray) {
10816     if (PatternType == 1)
10817       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10818     else
10819       Diag(SL, diag::warn_strncat_src_size) << SR;
10820     return;
10821   }
10822 
10823   if (PatternType == 1)
10824     Diag(SL, diag::warn_strncat_large_size) << SR;
10825   else
10826     Diag(SL, diag::warn_strncat_src_size) << SR;
10827 
10828   SmallString<128> sizeString;
10829   llvm::raw_svector_ostream OS(sizeString);
10830   OS << "sizeof(";
10831   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10832   OS << ") - ";
10833   OS << "strlen(";
10834   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10835   OS << ") - 1";
10836 
10837   Diag(SL, diag::note_strncat_wrong_size)
10838     << FixItHint::CreateReplacement(SR, OS.str());
10839 }
10840 
10841 namespace {
10842 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10843                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10844   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10845     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10846         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10847     return;
10848   }
10849 }
10850 
10851 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10852                                  const UnaryOperator *UnaryExpr) {
10853   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10854     const Decl *D = Lvalue->getDecl();
10855     if (isa<DeclaratorDecl>(D))
10856       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10857         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10858   }
10859 
10860   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10861     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10862                                       Lvalue->getMemberDecl());
10863 }
10864 
10865 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10866                             const UnaryOperator *UnaryExpr) {
10867   const auto *Lambda = dyn_cast<LambdaExpr>(
10868       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10869   if (!Lambda)
10870     return;
10871 
10872   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10873       << CalleeName << 2 /*object: lambda expression*/;
10874 }
10875 
10876 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10877                                   const DeclRefExpr *Lvalue) {
10878   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10879   if (Var == nullptr)
10880     return;
10881 
10882   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10883       << CalleeName << 0 /*object: */ << Var;
10884 }
10885 
10886 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10887                             const CastExpr *Cast) {
10888   SmallString<128> SizeString;
10889   llvm::raw_svector_ostream OS(SizeString);
10890 
10891   clang::CastKind Kind = Cast->getCastKind();
10892   if (Kind == clang::CK_BitCast &&
10893       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10894     return;
10895   if (Kind == clang::CK_IntegralToPointer &&
10896       !isa<IntegerLiteral>(
10897           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10898     return;
10899 
10900   switch (Cast->getCastKind()) {
10901   case clang::CK_BitCast:
10902   case clang::CK_IntegralToPointer:
10903   case clang::CK_FunctionToPointerDecay:
10904     OS << '\'';
10905     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10906     OS << '\'';
10907     break;
10908   default:
10909     return;
10910   }
10911 
10912   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10913       << CalleeName << 0 /*object: */ << OS.str();
10914 }
10915 } // namespace
10916 
10917 /// Alerts the user that they are attempting to free a non-malloc'd object.
10918 void Sema::CheckFreeArguments(const CallExpr *E) {
10919   const std::string CalleeName =
10920       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10921 
10922   { // Prefer something that doesn't involve a cast to make things simpler.
10923     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10924     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10925       switch (UnaryExpr->getOpcode()) {
10926       case UnaryOperator::Opcode::UO_AddrOf:
10927         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10928       case UnaryOperator::Opcode::UO_Plus:
10929         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10930       default:
10931         break;
10932       }
10933 
10934     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10935       if (Lvalue->getType()->isArrayType())
10936         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10937 
10938     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10939       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10940           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10941       return;
10942     }
10943 
10944     if (isa<BlockExpr>(Arg)) {
10945       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10946           << CalleeName << 1 /*object: block*/;
10947       return;
10948     }
10949   }
10950   // Maybe the cast was important, check after the other cases.
10951   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10952     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10953 }
10954 
10955 void
10956 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10957                          SourceLocation ReturnLoc,
10958                          bool isObjCMethod,
10959                          const AttrVec *Attrs,
10960                          const FunctionDecl *FD) {
10961   // Check if the return value is null but should not be.
10962   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10963        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10964       CheckNonNullExpr(*this, RetValExp))
10965     Diag(ReturnLoc, diag::warn_null_ret)
10966       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10967 
10968   // C++11 [basic.stc.dynamic.allocation]p4:
10969   //   If an allocation function declared with a non-throwing
10970   //   exception-specification fails to allocate storage, it shall return
10971   //   a null pointer. Any other allocation function that fails to allocate
10972   //   storage shall indicate failure only by throwing an exception [...]
10973   if (FD) {
10974     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10975     if (Op == OO_New || Op == OO_Array_New) {
10976       const FunctionProtoType *Proto
10977         = FD->getType()->castAs<FunctionProtoType>();
10978       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10979           CheckNonNullExpr(*this, RetValExp))
10980         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10981           << FD << getLangOpts().CPlusPlus11;
10982     }
10983   }
10984 
10985   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10986   // here prevent the user from using a PPC MMA type as trailing return type.
10987   if (Context.getTargetInfo().getTriple().isPPC64())
10988     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10989 }
10990 
10991 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10992 
10993 /// Check for comparisons of floating point operands using != and ==.
10994 /// Issue a warning if these are no self-comparisons, as they are not likely
10995 /// to do what the programmer intended.
10996 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10997   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10998   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10999 
11000   // Special case: check for x == x (which is OK).
11001   // Do not emit warnings for such cases.
11002   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11003     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11004       if (DRL->getDecl() == DRR->getDecl())
11005         return;
11006 
11007   // Special case: check for comparisons against literals that can be exactly
11008   //  represented by APFloat.  In such cases, do not emit a warning.  This
11009   //  is a heuristic: often comparison against such literals are used to
11010   //  detect if a value in a variable has not changed.  This clearly can
11011   //  lead to false negatives.
11012   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11013     if (FLL->isExact())
11014       return;
11015   } else
11016     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11017       if (FLR->isExact())
11018         return;
11019 
11020   // Check for comparisons with builtin types.
11021   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11022     if (CL->getBuiltinCallee())
11023       return;
11024 
11025   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11026     if (CR->getBuiltinCallee())
11027       return;
11028 
11029   // Emit the diagnostic.
11030   Diag(Loc, diag::warn_floatingpoint_eq)
11031     << LHS->getSourceRange() << RHS->getSourceRange();
11032 }
11033 
11034 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11035 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11036 
11037 namespace {
11038 
11039 /// Structure recording the 'active' range of an integer-valued
11040 /// expression.
11041 struct IntRange {
11042   /// The number of bits active in the int. Note that this includes exactly one
11043   /// sign bit if !NonNegative.
11044   unsigned Width;
11045 
11046   /// True if the int is known not to have negative values. If so, all leading
11047   /// bits before Width are known zero, otherwise they are known to be the
11048   /// same as the MSB within Width.
11049   bool NonNegative;
11050 
11051   IntRange(unsigned Width, bool NonNegative)
11052       : Width(Width), NonNegative(NonNegative) {}
11053 
11054   /// Number of bits excluding the sign bit.
11055   unsigned valueBits() const {
11056     return NonNegative ? Width : Width - 1;
11057   }
11058 
11059   /// Returns the range of the bool type.
11060   static IntRange forBoolType() {
11061     return IntRange(1, true);
11062   }
11063 
11064   /// Returns the range of an opaque value of the given integral type.
11065   static IntRange forValueOfType(ASTContext &C, QualType T) {
11066     return forValueOfCanonicalType(C,
11067                           T->getCanonicalTypeInternal().getTypePtr());
11068   }
11069 
11070   /// Returns the range of an opaque value of a canonical integral type.
11071   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11072     assert(T->isCanonicalUnqualified());
11073 
11074     if (const VectorType *VT = dyn_cast<VectorType>(T))
11075       T = VT->getElementType().getTypePtr();
11076     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11077       T = CT->getElementType().getTypePtr();
11078     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11079       T = AT->getValueType().getTypePtr();
11080 
11081     if (!C.getLangOpts().CPlusPlus) {
11082       // For enum types in C code, use the underlying datatype.
11083       if (const EnumType *ET = dyn_cast<EnumType>(T))
11084         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11085     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11086       // For enum types in C++, use the known bit width of the enumerators.
11087       EnumDecl *Enum = ET->getDecl();
11088       // In C++11, enums can have a fixed underlying type. Use this type to
11089       // compute the range.
11090       if (Enum->isFixed()) {
11091         return IntRange(C.getIntWidth(QualType(T, 0)),
11092                         !ET->isSignedIntegerOrEnumerationType());
11093       }
11094 
11095       unsigned NumPositive = Enum->getNumPositiveBits();
11096       unsigned NumNegative = Enum->getNumNegativeBits();
11097 
11098       if (NumNegative == 0)
11099         return IntRange(NumPositive, true/*NonNegative*/);
11100       else
11101         return IntRange(std::max(NumPositive + 1, NumNegative),
11102                         false/*NonNegative*/);
11103     }
11104 
11105     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11106       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11107 
11108     const BuiltinType *BT = cast<BuiltinType>(T);
11109     assert(BT->isInteger());
11110 
11111     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11112   }
11113 
11114   /// Returns the "target" range of a canonical integral type, i.e.
11115   /// the range of values expressible in the type.
11116   ///
11117   /// This matches forValueOfCanonicalType except that enums have the
11118   /// full range of their type, not the range of their enumerators.
11119   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11120     assert(T->isCanonicalUnqualified());
11121 
11122     if (const VectorType *VT = dyn_cast<VectorType>(T))
11123       T = VT->getElementType().getTypePtr();
11124     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11125       T = CT->getElementType().getTypePtr();
11126     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11127       T = AT->getValueType().getTypePtr();
11128     if (const EnumType *ET = dyn_cast<EnumType>(T))
11129       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11130 
11131     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11132       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11133 
11134     const BuiltinType *BT = cast<BuiltinType>(T);
11135     assert(BT->isInteger());
11136 
11137     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11138   }
11139 
11140   /// Returns the supremum of two ranges: i.e. their conservative merge.
11141   static IntRange join(IntRange L, IntRange R) {
11142     bool Unsigned = L.NonNegative && R.NonNegative;
11143     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11144                     L.NonNegative && R.NonNegative);
11145   }
11146 
11147   /// Return the range of a bitwise-AND of the two ranges.
11148   static IntRange bit_and(IntRange L, IntRange R) {
11149     unsigned Bits = std::max(L.Width, R.Width);
11150     bool NonNegative = false;
11151     if (L.NonNegative) {
11152       Bits = std::min(Bits, L.Width);
11153       NonNegative = true;
11154     }
11155     if (R.NonNegative) {
11156       Bits = std::min(Bits, R.Width);
11157       NonNegative = true;
11158     }
11159     return IntRange(Bits, NonNegative);
11160   }
11161 
11162   /// Return the range of a sum of the two ranges.
11163   static IntRange sum(IntRange L, IntRange R) {
11164     bool Unsigned = L.NonNegative && R.NonNegative;
11165     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11166                     Unsigned);
11167   }
11168 
11169   /// Return the range of a difference of the two ranges.
11170   static IntRange difference(IntRange L, IntRange R) {
11171     // We need a 1-bit-wider range if:
11172     //   1) LHS can be negative: least value can be reduced.
11173     //   2) RHS can be negative: greatest value can be increased.
11174     bool CanWiden = !L.NonNegative || !R.NonNegative;
11175     bool Unsigned = L.NonNegative && R.Width == 0;
11176     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11177                         !Unsigned,
11178                     Unsigned);
11179   }
11180 
11181   /// Return the range of a product of the two ranges.
11182   static IntRange product(IntRange L, IntRange R) {
11183     // If both LHS and RHS can be negative, we can form
11184     //   -2^L * -2^R = 2^(L + R)
11185     // which requires L + R + 1 value bits to represent.
11186     bool CanWiden = !L.NonNegative && !R.NonNegative;
11187     bool Unsigned = L.NonNegative && R.NonNegative;
11188     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11189                     Unsigned);
11190   }
11191 
11192   /// Return the range of a remainder operation between the two ranges.
11193   static IntRange rem(IntRange L, IntRange R) {
11194     // The result of a remainder can't be larger than the result of
11195     // either side. The sign of the result is the sign of the LHS.
11196     bool Unsigned = L.NonNegative;
11197     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11198                     Unsigned);
11199   }
11200 };
11201 
11202 } // namespace
11203 
11204 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11205                               unsigned MaxWidth) {
11206   if (value.isSigned() && value.isNegative())
11207     return IntRange(value.getMinSignedBits(), false);
11208 
11209   if (value.getBitWidth() > MaxWidth)
11210     value = value.trunc(MaxWidth);
11211 
11212   // isNonNegative() just checks the sign bit without considering
11213   // signedness.
11214   return IntRange(value.getActiveBits(), true);
11215 }
11216 
11217 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11218                               unsigned MaxWidth) {
11219   if (result.isInt())
11220     return GetValueRange(C, result.getInt(), MaxWidth);
11221 
11222   if (result.isVector()) {
11223     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11224     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11225       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11226       R = IntRange::join(R, El);
11227     }
11228     return R;
11229   }
11230 
11231   if (result.isComplexInt()) {
11232     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11233     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11234     return IntRange::join(R, I);
11235   }
11236 
11237   // This can happen with lossless casts to intptr_t of "based" lvalues.
11238   // Assume it might use arbitrary bits.
11239   // FIXME: The only reason we need to pass the type in here is to get
11240   // the sign right on this one case.  It would be nice if APValue
11241   // preserved this.
11242   assert(result.isLValue() || result.isAddrLabelDiff());
11243   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11244 }
11245 
11246 static QualType GetExprType(const Expr *E) {
11247   QualType Ty = E->getType();
11248   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11249     Ty = AtomicRHS->getValueType();
11250   return Ty;
11251 }
11252 
11253 /// Pseudo-evaluate the given integer expression, estimating the
11254 /// range of values it might take.
11255 ///
11256 /// \param MaxWidth The width to which the value will be truncated.
11257 /// \param Approximate If \c true, return a likely range for the result: in
11258 ///        particular, assume that aritmetic on narrower types doesn't leave
11259 ///        those types. If \c false, return a range including all possible
11260 ///        result values.
11261 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11262                              bool InConstantContext, bool Approximate) {
11263   E = E->IgnoreParens();
11264 
11265   // Try a full evaluation first.
11266   Expr::EvalResult result;
11267   if (E->EvaluateAsRValue(result, C, InConstantContext))
11268     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11269 
11270   // I think we only want to look through implicit casts here; if the
11271   // user has an explicit widening cast, we should treat the value as
11272   // being of the new, wider type.
11273   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11274     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11275       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11276                           Approximate);
11277 
11278     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11279 
11280     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11281                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11282 
11283     // Assume that non-integer casts can span the full range of the type.
11284     if (!isIntegerCast)
11285       return OutputTypeRange;
11286 
11287     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11288                                      std::min(MaxWidth, OutputTypeRange.Width),
11289                                      InConstantContext, Approximate);
11290 
11291     // Bail out if the subexpr's range is as wide as the cast type.
11292     if (SubRange.Width >= OutputTypeRange.Width)
11293       return OutputTypeRange;
11294 
11295     // Otherwise, we take the smaller width, and we're non-negative if
11296     // either the output type or the subexpr is.
11297     return IntRange(SubRange.Width,
11298                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11299   }
11300 
11301   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11302     // If we can fold the condition, just take that operand.
11303     bool CondResult;
11304     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11305       return GetExprRange(C,
11306                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11307                           MaxWidth, InConstantContext, Approximate);
11308 
11309     // Otherwise, conservatively merge.
11310     // GetExprRange requires an integer expression, but a throw expression
11311     // results in a void type.
11312     Expr *E = CO->getTrueExpr();
11313     IntRange L = E->getType()->isVoidType()
11314                      ? IntRange{0, true}
11315                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11316     E = CO->getFalseExpr();
11317     IntRange R = E->getType()->isVoidType()
11318                      ? IntRange{0, true}
11319                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11320     return IntRange::join(L, R);
11321   }
11322 
11323   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11324     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11325 
11326     switch (BO->getOpcode()) {
11327     case BO_Cmp:
11328       llvm_unreachable("builtin <=> should have class type");
11329 
11330     // Boolean-valued operations are single-bit and positive.
11331     case BO_LAnd:
11332     case BO_LOr:
11333     case BO_LT:
11334     case BO_GT:
11335     case BO_LE:
11336     case BO_GE:
11337     case BO_EQ:
11338     case BO_NE:
11339       return IntRange::forBoolType();
11340 
11341     // The type of the assignments is the type of the LHS, so the RHS
11342     // is not necessarily the same type.
11343     case BO_MulAssign:
11344     case BO_DivAssign:
11345     case BO_RemAssign:
11346     case BO_AddAssign:
11347     case BO_SubAssign:
11348     case BO_XorAssign:
11349     case BO_OrAssign:
11350       // TODO: bitfields?
11351       return IntRange::forValueOfType(C, GetExprType(E));
11352 
11353     // Simple assignments just pass through the RHS, which will have
11354     // been coerced to the LHS type.
11355     case BO_Assign:
11356       // TODO: bitfields?
11357       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11358                           Approximate);
11359 
11360     // Operations with opaque sources are black-listed.
11361     case BO_PtrMemD:
11362     case BO_PtrMemI:
11363       return IntRange::forValueOfType(C, GetExprType(E));
11364 
11365     // Bitwise-and uses the *infinum* of the two source ranges.
11366     case BO_And:
11367     case BO_AndAssign:
11368       Combine = IntRange::bit_and;
11369       break;
11370 
11371     // Left shift gets black-listed based on a judgement call.
11372     case BO_Shl:
11373       // ...except that we want to treat '1 << (blah)' as logically
11374       // positive.  It's an important idiom.
11375       if (IntegerLiteral *I
11376             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11377         if (I->getValue() == 1) {
11378           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11379           return IntRange(R.Width, /*NonNegative*/ true);
11380         }
11381       }
11382       LLVM_FALLTHROUGH;
11383 
11384     case BO_ShlAssign:
11385       return IntRange::forValueOfType(C, GetExprType(E));
11386 
11387     // Right shift by a constant can narrow its left argument.
11388     case BO_Shr:
11389     case BO_ShrAssign: {
11390       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11391                                 Approximate);
11392 
11393       // If the shift amount is a positive constant, drop the width by
11394       // that much.
11395       if (Optional<llvm::APSInt> shift =
11396               BO->getRHS()->getIntegerConstantExpr(C)) {
11397         if (shift->isNonNegative()) {
11398           unsigned zext = shift->getZExtValue();
11399           if (zext >= L.Width)
11400             L.Width = (L.NonNegative ? 0 : 1);
11401           else
11402             L.Width -= zext;
11403         }
11404       }
11405 
11406       return L;
11407     }
11408 
11409     // Comma acts as its right operand.
11410     case BO_Comma:
11411       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11412                           Approximate);
11413 
11414     case BO_Add:
11415       if (!Approximate)
11416         Combine = IntRange::sum;
11417       break;
11418 
11419     case BO_Sub:
11420       if (BO->getLHS()->getType()->isPointerType())
11421         return IntRange::forValueOfType(C, GetExprType(E));
11422       if (!Approximate)
11423         Combine = IntRange::difference;
11424       break;
11425 
11426     case BO_Mul:
11427       if (!Approximate)
11428         Combine = IntRange::product;
11429       break;
11430 
11431     // The width of a division result is mostly determined by the size
11432     // of the LHS.
11433     case BO_Div: {
11434       // Don't 'pre-truncate' the operands.
11435       unsigned opWidth = C.getIntWidth(GetExprType(E));
11436       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11437                                 Approximate);
11438 
11439       // If the divisor is constant, use that.
11440       if (Optional<llvm::APSInt> divisor =
11441               BO->getRHS()->getIntegerConstantExpr(C)) {
11442         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11443         if (log2 >= L.Width)
11444           L.Width = (L.NonNegative ? 0 : 1);
11445         else
11446           L.Width = std::min(L.Width - log2, MaxWidth);
11447         return L;
11448       }
11449 
11450       // Otherwise, just use the LHS's width.
11451       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11452       // could be -1.
11453       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11454                                 Approximate);
11455       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11456     }
11457 
11458     case BO_Rem:
11459       Combine = IntRange::rem;
11460       break;
11461 
11462     // The default behavior is okay for these.
11463     case BO_Xor:
11464     case BO_Or:
11465       break;
11466     }
11467 
11468     // Combine the two ranges, but limit the result to the type in which we
11469     // performed the computation.
11470     QualType T = GetExprType(E);
11471     unsigned opWidth = C.getIntWidth(T);
11472     IntRange L =
11473         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11474     IntRange R =
11475         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11476     IntRange C = Combine(L, R);
11477     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11478     C.Width = std::min(C.Width, MaxWidth);
11479     return C;
11480   }
11481 
11482   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11483     switch (UO->getOpcode()) {
11484     // Boolean-valued operations are white-listed.
11485     case UO_LNot:
11486       return IntRange::forBoolType();
11487 
11488     // Operations with opaque sources are black-listed.
11489     case UO_Deref:
11490     case UO_AddrOf: // should be impossible
11491       return IntRange::forValueOfType(C, GetExprType(E));
11492 
11493     default:
11494       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11495                           Approximate);
11496     }
11497   }
11498 
11499   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11500     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11501                         Approximate);
11502 
11503   if (const auto *BitField = E->getSourceBitField())
11504     return IntRange(BitField->getBitWidthValue(C),
11505                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11506 
11507   return IntRange::forValueOfType(C, GetExprType(E));
11508 }
11509 
11510 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11511                              bool InConstantContext, bool Approximate) {
11512   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11513                       Approximate);
11514 }
11515 
11516 /// Checks whether the given value, which currently has the given
11517 /// source semantics, has the same value when coerced through the
11518 /// target semantics.
11519 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11520                                  const llvm::fltSemantics &Src,
11521                                  const llvm::fltSemantics &Tgt) {
11522   llvm::APFloat truncated = value;
11523 
11524   bool ignored;
11525   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11526   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11527 
11528   return truncated.bitwiseIsEqual(value);
11529 }
11530 
11531 /// Checks whether the given value, which currently has the given
11532 /// source semantics, has the same value when coerced through the
11533 /// target semantics.
11534 ///
11535 /// The value might be a vector of floats (or a complex number).
11536 static bool IsSameFloatAfterCast(const APValue &value,
11537                                  const llvm::fltSemantics &Src,
11538                                  const llvm::fltSemantics &Tgt) {
11539   if (value.isFloat())
11540     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11541 
11542   if (value.isVector()) {
11543     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11544       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11545         return false;
11546     return true;
11547   }
11548 
11549   assert(value.isComplexFloat());
11550   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11551           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11552 }
11553 
11554 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11555                                        bool IsListInit = false);
11556 
11557 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11558   // Suppress cases where we are comparing against an enum constant.
11559   if (const DeclRefExpr *DR =
11560       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11561     if (isa<EnumConstantDecl>(DR->getDecl()))
11562       return true;
11563 
11564   // Suppress cases where the value is expanded from a macro, unless that macro
11565   // is how a language represents a boolean literal. This is the case in both C
11566   // and Objective-C.
11567   SourceLocation BeginLoc = E->getBeginLoc();
11568   if (BeginLoc.isMacroID()) {
11569     StringRef MacroName = Lexer::getImmediateMacroName(
11570         BeginLoc, S.getSourceManager(), S.getLangOpts());
11571     return MacroName != "YES" && MacroName != "NO" &&
11572            MacroName != "true" && MacroName != "false";
11573   }
11574 
11575   return false;
11576 }
11577 
11578 static bool isKnownToHaveUnsignedValue(Expr *E) {
11579   return E->getType()->isIntegerType() &&
11580          (!E->getType()->isSignedIntegerType() ||
11581           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11582 }
11583 
11584 namespace {
11585 /// The promoted range of values of a type. In general this has the
11586 /// following structure:
11587 ///
11588 ///     |-----------| . . . |-----------|
11589 ///     ^           ^       ^           ^
11590 ///    Min       HoleMin  HoleMax      Max
11591 ///
11592 /// ... where there is only a hole if a signed type is promoted to unsigned
11593 /// (in which case Min and Max are the smallest and largest representable
11594 /// values).
11595 struct PromotedRange {
11596   // Min, or HoleMax if there is a hole.
11597   llvm::APSInt PromotedMin;
11598   // Max, or HoleMin if there is a hole.
11599   llvm::APSInt PromotedMax;
11600 
11601   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11602     if (R.Width == 0)
11603       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11604     else if (R.Width >= BitWidth && !Unsigned) {
11605       // Promotion made the type *narrower*. This happens when promoting
11606       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11607       // Treat all values of 'signed int' as being in range for now.
11608       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11609       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11610     } else {
11611       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11612                         .extOrTrunc(BitWidth);
11613       PromotedMin.setIsUnsigned(Unsigned);
11614 
11615       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11616                         .extOrTrunc(BitWidth);
11617       PromotedMax.setIsUnsigned(Unsigned);
11618     }
11619   }
11620 
11621   // Determine whether this range is contiguous (has no hole).
11622   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11623 
11624   // Where a constant value is within the range.
11625   enum ComparisonResult {
11626     LT = 0x1,
11627     LE = 0x2,
11628     GT = 0x4,
11629     GE = 0x8,
11630     EQ = 0x10,
11631     NE = 0x20,
11632     InRangeFlag = 0x40,
11633 
11634     Less = LE | LT | NE,
11635     Min = LE | InRangeFlag,
11636     InRange = InRangeFlag,
11637     Max = GE | InRangeFlag,
11638     Greater = GE | GT | NE,
11639 
11640     OnlyValue = LE | GE | EQ | InRangeFlag,
11641     InHole = NE
11642   };
11643 
11644   ComparisonResult compare(const llvm::APSInt &Value) const {
11645     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11646            Value.isUnsigned() == PromotedMin.isUnsigned());
11647     if (!isContiguous()) {
11648       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11649       if (Value.isMinValue()) return Min;
11650       if (Value.isMaxValue()) return Max;
11651       if (Value >= PromotedMin) return InRange;
11652       if (Value <= PromotedMax) return InRange;
11653       return InHole;
11654     }
11655 
11656     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11657     case -1: return Less;
11658     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11659     case 1:
11660       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11661       case -1: return InRange;
11662       case 0: return Max;
11663       case 1: return Greater;
11664       }
11665     }
11666 
11667     llvm_unreachable("impossible compare result");
11668   }
11669 
11670   static llvm::Optional<StringRef>
11671   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11672     if (Op == BO_Cmp) {
11673       ComparisonResult LTFlag = LT, GTFlag = GT;
11674       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11675 
11676       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11677       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11678       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11679       return llvm::None;
11680     }
11681 
11682     ComparisonResult TrueFlag, FalseFlag;
11683     if (Op == BO_EQ) {
11684       TrueFlag = EQ;
11685       FalseFlag = NE;
11686     } else if (Op == BO_NE) {
11687       TrueFlag = NE;
11688       FalseFlag = EQ;
11689     } else {
11690       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11691         TrueFlag = LT;
11692         FalseFlag = GE;
11693       } else {
11694         TrueFlag = GT;
11695         FalseFlag = LE;
11696       }
11697       if (Op == BO_GE || Op == BO_LE)
11698         std::swap(TrueFlag, FalseFlag);
11699     }
11700     if (R & TrueFlag)
11701       return StringRef("true");
11702     if (R & FalseFlag)
11703       return StringRef("false");
11704     return llvm::None;
11705   }
11706 };
11707 }
11708 
11709 static bool HasEnumType(Expr *E) {
11710   // Strip off implicit integral promotions.
11711   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11712     if (ICE->getCastKind() != CK_IntegralCast &&
11713         ICE->getCastKind() != CK_NoOp)
11714       break;
11715     E = ICE->getSubExpr();
11716   }
11717 
11718   return E->getType()->isEnumeralType();
11719 }
11720 
11721 static int classifyConstantValue(Expr *Constant) {
11722   // The values of this enumeration are used in the diagnostics
11723   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11724   enum ConstantValueKind {
11725     Miscellaneous = 0,
11726     LiteralTrue,
11727     LiteralFalse
11728   };
11729   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11730     return BL->getValue() ? ConstantValueKind::LiteralTrue
11731                           : ConstantValueKind::LiteralFalse;
11732   return ConstantValueKind::Miscellaneous;
11733 }
11734 
11735 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11736                                         Expr *Constant, Expr *Other,
11737                                         const llvm::APSInt &Value,
11738                                         bool RhsConstant) {
11739   if (S.inTemplateInstantiation())
11740     return false;
11741 
11742   Expr *OriginalOther = Other;
11743 
11744   Constant = Constant->IgnoreParenImpCasts();
11745   Other = Other->IgnoreParenImpCasts();
11746 
11747   // Suppress warnings on tautological comparisons between values of the same
11748   // enumeration type. There are only two ways we could warn on this:
11749   //  - If the constant is outside the range of representable values of
11750   //    the enumeration. In such a case, we should warn about the cast
11751   //    to enumeration type, not about the comparison.
11752   //  - If the constant is the maximum / minimum in-range value. For an
11753   //    enumeratin type, such comparisons can be meaningful and useful.
11754   if (Constant->getType()->isEnumeralType() &&
11755       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11756     return false;
11757 
11758   IntRange OtherValueRange = GetExprRange(
11759       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11760 
11761   QualType OtherT = Other->getType();
11762   if (const auto *AT = OtherT->getAs<AtomicType>())
11763     OtherT = AT->getValueType();
11764   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11765 
11766   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11767   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11768   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11769                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11770                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11771 
11772   // Whether we're treating Other as being a bool because of the form of
11773   // expression despite it having another type (typically 'int' in C).
11774   bool OtherIsBooleanDespiteType =
11775       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11776   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11777     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11778 
11779   // Check if all values in the range of possible values of this expression
11780   // lead to the same comparison outcome.
11781   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11782                                         Value.isUnsigned());
11783   auto Cmp = OtherPromotedValueRange.compare(Value);
11784   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11785   if (!Result)
11786     return false;
11787 
11788   // Also consider the range determined by the type alone. This allows us to
11789   // classify the warning under the proper diagnostic group.
11790   bool TautologicalTypeCompare = false;
11791   {
11792     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11793                                          Value.isUnsigned());
11794     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11795     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11796                                                        RhsConstant)) {
11797       TautologicalTypeCompare = true;
11798       Cmp = TypeCmp;
11799       Result = TypeResult;
11800     }
11801   }
11802 
11803   // Don't warn if the non-constant operand actually always evaluates to the
11804   // same value.
11805   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11806     return false;
11807 
11808   // Suppress the diagnostic for an in-range comparison if the constant comes
11809   // from a macro or enumerator. We don't want to diagnose
11810   //
11811   //   some_long_value <= INT_MAX
11812   //
11813   // when sizeof(int) == sizeof(long).
11814   bool InRange = Cmp & PromotedRange::InRangeFlag;
11815   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11816     return false;
11817 
11818   // A comparison of an unsigned bit-field against 0 is really a type problem,
11819   // even though at the type level the bit-field might promote to 'signed int'.
11820   if (Other->refersToBitField() && InRange && Value == 0 &&
11821       Other->getType()->isUnsignedIntegerOrEnumerationType())
11822     TautologicalTypeCompare = true;
11823 
11824   // If this is a comparison to an enum constant, include that
11825   // constant in the diagnostic.
11826   const EnumConstantDecl *ED = nullptr;
11827   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11828     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11829 
11830   // Should be enough for uint128 (39 decimal digits)
11831   SmallString<64> PrettySourceValue;
11832   llvm::raw_svector_ostream OS(PrettySourceValue);
11833   if (ED) {
11834     OS << '\'' << *ED << "' (" << Value << ")";
11835   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11836                Constant->IgnoreParenImpCasts())) {
11837     OS << (BL->getValue() ? "YES" : "NO");
11838   } else {
11839     OS << Value;
11840   }
11841 
11842   if (!TautologicalTypeCompare) {
11843     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11844         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11845         << E->getOpcodeStr() << OS.str() << *Result
11846         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11847     return true;
11848   }
11849 
11850   if (IsObjCSignedCharBool) {
11851     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11852                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11853                               << OS.str() << *Result);
11854     return true;
11855   }
11856 
11857   // FIXME: We use a somewhat different formatting for the in-range cases and
11858   // cases involving boolean values for historical reasons. We should pick a
11859   // consistent way of presenting these diagnostics.
11860   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11861 
11862     S.DiagRuntimeBehavior(
11863         E->getOperatorLoc(), E,
11864         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11865                          : diag::warn_tautological_bool_compare)
11866             << OS.str() << classifyConstantValue(Constant) << OtherT
11867             << OtherIsBooleanDespiteType << *Result
11868             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11869   } else {
11870     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11871     unsigned Diag =
11872         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11873             ? (HasEnumType(OriginalOther)
11874                    ? diag::warn_unsigned_enum_always_true_comparison
11875                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11876                               : diag::warn_unsigned_always_true_comparison)
11877             : diag::warn_tautological_constant_compare;
11878 
11879     S.Diag(E->getOperatorLoc(), Diag)
11880         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11881         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11882   }
11883 
11884   return true;
11885 }
11886 
11887 /// Analyze the operands of the given comparison.  Implements the
11888 /// fallback case from AnalyzeComparison.
11889 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11890   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11891   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11892 }
11893 
11894 /// Implements -Wsign-compare.
11895 ///
11896 /// \param E the binary operator to check for warnings
11897 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11898   // The type the comparison is being performed in.
11899   QualType T = E->getLHS()->getType();
11900 
11901   // Only analyze comparison operators where both sides have been converted to
11902   // the same type.
11903   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11904     return AnalyzeImpConvsInComparison(S, E);
11905 
11906   // Don't analyze value-dependent comparisons directly.
11907   if (E->isValueDependent())
11908     return AnalyzeImpConvsInComparison(S, E);
11909 
11910   Expr *LHS = E->getLHS();
11911   Expr *RHS = E->getRHS();
11912 
11913   if (T->isIntegralType(S.Context)) {
11914     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11915     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11916 
11917     // We don't care about expressions whose result is a constant.
11918     if (RHSValue && LHSValue)
11919       return AnalyzeImpConvsInComparison(S, E);
11920 
11921     // We only care about expressions where just one side is literal
11922     if ((bool)RHSValue ^ (bool)LHSValue) {
11923       // Is the constant on the RHS or LHS?
11924       const bool RhsConstant = (bool)RHSValue;
11925       Expr *Const = RhsConstant ? RHS : LHS;
11926       Expr *Other = RhsConstant ? LHS : RHS;
11927       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11928 
11929       // Check whether an integer constant comparison results in a value
11930       // of 'true' or 'false'.
11931       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11932         return AnalyzeImpConvsInComparison(S, E);
11933     }
11934   }
11935 
11936   if (!T->hasUnsignedIntegerRepresentation()) {
11937     // We don't do anything special if this isn't an unsigned integral
11938     // comparison:  we're only interested in integral comparisons, and
11939     // signed comparisons only happen in cases we don't care to warn about.
11940     return AnalyzeImpConvsInComparison(S, E);
11941   }
11942 
11943   LHS = LHS->IgnoreParenImpCasts();
11944   RHS = RHS->IgnoreParenImpCasts();
11945 
11946   if (!S.getLangOpts().CPlusPlus) {
11947     // Avoid warning about comparison of integers with different signs when
11948     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11949     // the type of `E`.
11950     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11951       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11952     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11953       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11954   }
11955 
11956   // Check to see if one of the (unmodified) operands is of different
11957   // signedness.
11958   Expr *signedOperand, *unsignedOperand;
11959   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11960     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11961            "unsigned comparison between two signed integer expressions?");
11962     signedOperand = LHS;
11963     unsignedOperand = RHS;
11964   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11965     signedOperand = RHS;
11966     unsignedOperand = LHS;
11967   } else {
11968     return AnalyzeImpConvsInComparison(S, E);
11969   }
11970 
11971   // Otherwise, calculate the effective range of the signed operand.
11972   IntRange signedRange = GetExprRange(
11973       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11974 
11975   // Go ahead and analyze implicit conversions in the operands.  Note
11976   // that we skip the implicit conversions on both sides.
11977   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11978   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11979 
11980   // If the signed range is non-negative, -Wsign-compare won't fire.
11981   if (signedRange.NonNegative)
11982     return;
11983 
11984   // For (in)equality comparisons, if the unsigned operand is a
11985   // constant which cannot collide with a overflowed signed operand,
11986   // then reinterpreting the signed operand as unsigned will not
11987   // change the result of the comparison.
11988   if (E->isEqualityOp()) {
11989     unsigned comparisonWidth = S.Context.getIntWidth(T);
11990     IntRange unsignedRange =
11991         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11992                      /*Approximate*/ true);
11993 
11994     // We should never be unable to prove that the unsigned operand is
11995     // non-negative.
11996     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11997 
11998     if (unsignedRange.Width < comparisonWidth)
11999       return;
12000   }
12001 
12002   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12003                         S.PDiag(diag::warn_mixed_sign_comparison)
12004                             << LHS->getType() << RHS->getType()
12005                             << LHS->getSourceRange() << RHS->getSourceRange());
12006 }
12007 
12008 /// Analyzes an attempt to assign the given value to a bitfield.
12009 ///
12010 /// Returns true if there was something fishy about the attempt.
12011 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12012                                       SourceLocation InitLoc) {
12013   assert(Bitfield->isBitField());
12014   if (Bitfield->isInvalidDecl())
12015     return false;
12016 
12017   // White-list bool bitfields.
12018   QualType BitfieldType = Bitfield->getType();
12019   if (BitfieldType->isBooleanType())
12020      return false;
12021 
12022   if (BitfieldType->isEnumeralType()) {
12023     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12024     // If the underlying enum type was not explicitly specified as an unsigned
12025     // type and the enum contain only positive values, MSVC++ will cause an
12026     // inconsistency by storing this as a signed type.
12027     if (S.getLangOpts().CPlusPlus11 &&
12028         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12029         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12030         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12031       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12032           << BitfieldEnumDecl;
12033     }
12034   }
12035 
12036   if (Bitfield->getType()->isBooleanType())
12037     return false;
12038 
12039   // Ignore value- or type-dependent expressions.
12040   if (Bitfield->getBitWidth()->isValueDependent() ||
12041       Bitfield->getBitWidth()->isTypeDependent() ||
12042       Init->isValueDependent() ||
12043       Init->isTypeDependent())
12044     return false;
12045 
12046   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12047   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12048 
12049   Expr::EvalResult Result;
12050   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12051                                    Expr::SE_AllowSideEffects)) {
12052     // The RHS is not constant.  If the RHS has an enum type, make sure the
12053     // bitfield is wide enough to hold all the values of the enum without
12054     // truncation.
12055     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12056       EnumDecl *ED = EnumTy->getDecl();
12057       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12058 
12059       // Enum types are implicitly signed on Windows, so check if there are any
12060       // negative enumerators to see if the enum was intended to be signed or
12061       // not.
12062       bool SignedEnum = ED->getNumNegativeBits() > 0;
12063 
12064       // Check for surprising sign changes when assigning enum values to a
12065       // bitfield of different signedness.  If the bitfield is signed and we
12066       // have exactly the right number of bits to store this unsigned enum,
12067       // suggest changing the enum to an unsigned type. This typically happens
12068       // on Windows where unfixed enums always use an underlying type of 'int'.
12069       unsigned DiagID = 0;
12070       if (SignedEnum && !SignedBitfield) {
12071         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12072       } else if (SignedBitfield && !SignedEnum &&
12073                  ED->getNumPositiveBits() == FieldWidth) {
12074         DiagID = diag::warn_signed_bitfield_enum_conversion;
12075       }
12076 
12077       if (DiagID) {
12078         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12079         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12080         SourceRange TypeRange =
12081             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12082         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12083             << SignedEnum << TypeRange;
12084       }
12085 
12086       // Compute the required bitwidth. If the enum has negative values, we need
12087       // one more bit than the normal number of positive bits to represent the
12088       // sign bit.
12089       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12090                                                   ED->getNumNegativeBits())
12091                                        : ED->getNumPositiveBits();
12092 
12093       // Check the bitwidth.
12094       if (BitsNeeded > FieldWidth) {
12095         Expr *WidthExpr = Bitfield->getBitWidth();
12096         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12097             << Bitfield << ED;
12098         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12099             << BitsNeeded << ED << WidthExpr->getSourceRange();
12100       }
12101     }
12102 
12103     return false;
12104   }
12105 
12106   llvm::APSInt Value = Result.Val.getInt();
12107 
12108   unsigned OriginalWidth = Value.getBitWidth();
12109 
12110   if (!Value.isSigned() || Value.isNegative())
12111     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12112       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12113         OriginalWidth = Value.getMinSignedBits();
12114 
12115   if (OriginalWidth <= FieldWidth)
12116     return false;
12117 
12118   // Compute the value which the bitfield will contain.
12119   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12120   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12121 
12122   // Check whether the stored value is equal to the original value.
12123   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12124   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12125     return false;
12126 
12127   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12128   // therefore don't strictly fit into a signed bitfield of width 1.
12129   if (FieldWidth == 1 && Value == 1)
12130     return false;
12131 
12132   std::string PrettyValue = toString(Value, 10);
12133   std::string PrettyTrunc = toString(TruncatedValue, 10);
12134 
12135   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12136     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12137     << Init->getSourceRange();
12138 
12139   return true;
12140 }
12141 
12142 /// Analyze the given simple or compound assignment for warning-worthy
12143 /// operations.
12144 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12145   // Just recurse on the LHS.
12146   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12147 
12148   // We want to recurse on the RHS as normal unless we're assigning to
12149   // a bitfield.
12150   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12151     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12152                                   E->getOperatorLoc())) {
12153       // Recurse, ignoring any implicit conversions on the RHS.
12154       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12155                                         E->getOperatorLoc());
12156     }
12157   }
12158 
12159   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12160 
12161   // Diagnose implicitly sequentially-consistent atomic assignment.
12162   if (E->getLHS()->getType()->isAtomicType())
12163     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12164 }
12165 
12166 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12167 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12168                             SourceLocation CContext, unsigned diag,
12169                             bool pruneControlFlow = false) {
12170   if (pruneControlFlow) {
12171     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12172                           S.PDiag(diag)
12173                               << SourceType << T << E->getSourceRange()
12174                               << SourceRange(CContext));
12175     return;
12176   }
12177   S.Diag(E->getExprLoc(), diag)
12178     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12179 }
12180 
12181 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12182 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12183                             SourceLocation CContext,
12184                             unsigned diag, bool pruneControlFlow = false) {
12185   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12186 }
12187 
12188 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12189   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12190       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12191 }
12192 
12193 static void adornObjCBoolConversionDiagWithTernaryFixit(
12194     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12195   Expr *Ignored = SourceExpr->IgnoreImplicit();
12196   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12197     Ignored = OVE->getSourceExpr();
12198   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12199                      isa<BinaryOperator>(Ignored) ||
12200                      isa<CXXOperatorCallExpr>(Ignored);
12201   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12202   if (NeedsParens)
12203     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12204             << FixItHint::CreateInsertion(EndLoc, ")");
12205   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12206 }
12207 
12208 /// Diagnose an implicit cast from a floating point value to an integer value.
12209 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12210                                     SourceLocation CContext) {
12211   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12212   const bool PruneWarnings = S.inTemplateInstantiation();
12213 
12214   Expr *InnerE = E->IgnoreParenImpCasts();
12215   // We also want to warn on, e.g., "int i = -1.234"
12216   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12217     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12218       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12219 
12220   const bool IsLiteral =
12221       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12222 
12223   llvm::APFloat Value(0.0);
12224   bool IsConstant =
12225     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12226   if (!IsConstant) {
12227     if (isObjCSignedCharBool(S, T)) {
12228       return adornObjCBoolConversionDiagWithTernaryFixit(
12229           S, E,
12230           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12231               << E->getType());
12232     }
12233 
12234     return DiagnoseImpCast(S, E, T, CContext,
12235                            diag::warn_impcast_float_integer, PruneWarnings);
12236   }
12237 
12238   bool isExact = false;
12239 
12240   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12241                             T->hasUnsignedIntegerRepresentation());
12242   llvm::APFloat::opStatus Result = Value.convertToInteger(
12243       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12244 
12245   // FIXME: Force the precision of the source value down so we don't print
12246   // digits which are usually useless (we don't really care here if we
12247   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12248   // would automatically print the shortest representation, but it's a bit
12249   // tricky to implement.
12250   SmallString<16> PrettySourceValue;
12251   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12252   precision = (precision * 59 + 195) / 196;
12253   Value.toString(PrettySourceValue, precision);
12254 
12255   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12256     return adornObjCBoolConversionDiagWithTernaryFixit(
12257         S, E,
12258         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12259             << PrettySourceValue);
12260   }
12261 
12262   if (Result == llvm::APFloat::opOK && isExact) {
12263     if (IsLiteral) return;
12264     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12265                            PruneWarnings);
12266   }
12267 
12268   // Conversion of a floating-point value to a non-bool integer where the
12269   // integral part cannot be represented by the integer type is undefined.
12270   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12271     return DiagnoseImpCast(
12272         S, E, T, CContext,
12273         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12274                   : diag::warn_impcast_float_to_integer_out_of_range,
12275         PruneWarnings);
12276 
12277   unsigned DiagID = 0;
12278   if (IsLiteral) {
12279     // Warn on floating point literal to integer.
12280     DiagID = diag::warn_impcast_literal_float_to_integer;
12281   } else if (IntegerValue == 0) {
12282     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12283       return DiagnoseImpCast(S, E, T, CContext,
12284                              diag::warn_impcast_float_integer, PruneWarnings);
12285     }
12286     // Warn on non-zero to zero conversion.
12287     DiagID = diag::warn_impcast_float_to_integer_zero;
12288   } else {
12289     if (IntegerValue.isUnsigned()) {
12290       if (!IntegerValue.isMaxValue()) {
12291         return DiagnoseImpCast(S, E, T, CContext,
12292                                diag::warn_impcast_float_integer, PruneWarnings);
12293       }
12294     } else {  // IntegerValue.isSigned()
12295       if (!IntegerValue.isMaxSignedValue() &&
12296           !IntegerValue.isMinSignedValue()) {
12297         return DiagnoseImpCast(S, E, T, CContext,
12298                                diag::warn_impcast_float_integer, PruneWarnings);
12299       }
12300     }
12301     // Warn on evaluatable floating point expression to integer conversion.
12302     DiagID = diag::warn_impcast_float_to_integer;
12303   }
12304 
12305   SmallString<16> PrettyTargetValue;
12306   if (IsBool)
12307     PrettyTargetValue = Value.isZero() ? "false" : "true";
12308   else
12309     IntegerValue.toString(PrettyTargetValue);
12310 
12311   if (PruneWarnings) {
12312     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12313                           S.PDiag(DiagID)
12314                               << E->getType() << T.getUnqualifiedType()
12315                               << PrettySourceValue << PrettyTargetValue
12316                               << E->getSourceRange() << SourceRange(CContext));
12317   } else {
12318     S.Diag(E->getExprLoc(), DiagID)
12319         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12320         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12321   }
12322 }
12323 
12324 /// Analyze the given compound assignment for the possible losing of
12325 /// floating-point precision.
12326 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12327   assert(isa<CompoundAssignOperator>(E) &&
12328          "Must be compound assignment operation");
12329   // Recurse on the LHS and RHS in here
12330   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12331   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12332 
12333   if (E->getLHS()->getType()->isAtomicType())
12334     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12335 
12336   // Now check the outermost expression
12337   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12338   const auto *RBT = cast<CompoundAssignOperator>(E)
12339                         ->getComputationResultType()
12340                         ->getAs<BuiltinType>();
12341 
12342   // The below checks assume source is floating point.
12343   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12344 
12345   // If source is floating point but target is an integer.
12346   if (ResultBT->isInteger())
12347     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12348                            E->getExprLoc(), diag::warn_impcast_float_integer);
12349 
12350   if (!ResultBT->isFloatingPoint())
12351     return;
12352 
12353   // If both source and target are floating points, warn about losing precision.
12354   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12355       QualType(ResultBT, 0), QualType(RBT, 0));
12356   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12357     // warn about dropping FP rank.
12358     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12359                     diag::warn_impcast_float_result_precision);
12360 }
12361 
12362 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12363                                       IntRange Range) {
12364   if (!Range.Width) return "0";
12365 
12366   llvm::APSInt ValueInRange = Value;
12367   ValueInRange.setIsSigned(!Range.NonNegative);
12368   ValueInRange = ValueInRange.trunc(Range.Width);
12369   return toString(ValueInRange, 10);
12370 }
12371 
12372 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12373   if (!isa<ImplicitCastExpr>(Ex))
12374     return false;
12375 
12376   Expr *InnerE = Ex->IgnoreParenImpCasts();
12377   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12378   const Type *Source =
12379     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12380   if (Target->isDependentType())
12381     return false;
12382 
12383   const BuiltinType *FloatCandidateBT =
12384     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12385   const Type *BoolCandidateType = ToBool ? Target : Source;
12386 
12387   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12388           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12389 }
12390 
12391 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12392                                              SourceLocation CC) {
12393   unsigned NumArgs = TheCall->getNumArgs();
12394   for (unsigned i = 0; i < NumArgs; ++i) {
12395     Expr *CurrA = TheCall->getArg(i);
12396     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12397       continue;
12398 
12399     bool IsSwapped = ((i > 0) &&
12400         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12401     IsSwapped |= ((i < (NumArgs - 1)) &&
12402         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12403     if (IsSwapped) {
12404       // Warn on this floating-point to bool conversion.
12405       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12406                       CurrA->getType(), CC,
12407                       diag::warn_impcast_floating_point_to_bool);
12408     }
12409   }
12410 }
12411 
12412 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12413                                    SourceLocation CC) {
12414   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12415                         E->getExprLoc()))
12416     return;
12417 
12418   // Don't warn on functions which have return type nullptr_t.
12419   if (isa<CallExpr>(E))
12420     return;
12421 
12422   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12423   const Expr::NullPointerConstantKind NullKind =
12424       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12425   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12426     return;
12427 
12428   // Return if target type is a safe conversion.
12429   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12430       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12431     return;
12432 
12433   SourceLocation Loc = E->getSourceRange().getBegin();
12434 
12435   // Venture through the macro stacks to get to the source of macro arguments.
12436   // The new location is a better location than the complete location that was
12437   // passed in.
12438   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12439   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12440 
12441   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12442   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12443     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12444         Loc, S.SourceMgr, S.getLangOpts());
12445     if (MacroName == "NULL")
12446       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12447   }
12448 
12449   // Only warn if the null and context location are in the same macro expansion.
12450   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12451     return;
12452 
12453   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12454       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12455       << FixItHint::CreateReplacement(Loc,
12456                                       S.getFixItZeroLiteralForType(T, Loc));
12457 }
12458 
12459 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12460                                   ObjCArrayLiteral *ArrayLiteral);
12461 
12462 static void
12463 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12464                            ObjCDictionaryLiteral *DictionaryLiteral);
12465 
12466 /// Check a single element within a collection literal against the
12467 /// target element type.
12468 static void checkObjCCollectionLiteralElement(Sema &S,
12469                                               QualType TargetElementType,
12470                                               Expr *Element,
12471                                               unsigned ElementKind) {
12472   // Skip a bitcast to 'id' or qualified 'id'.
12473   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12474     if (ICE->getCastKind() == CK_BitCast &&
12475         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12476       Element = ICE->getSubExpr();
12477   }
12478 
12479   QualType ElementType = Element->getType();
12480   ExprResult ElementResult(Element);
12481   if (ElementType->getAs<ObjCObjectPointerType>() &&
12482       S.CheckSingleAssignmentConstraints(TargetElementType,
12483                                          ElementResult,
12484                                          false, false)
12485         != Sema::Compatible) {
12486     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12487         << ElementType << ElementKind << TargetElementType
12488         << Element->getSourceRange();
12489   }
12490 
12491   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12492     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12493   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12494     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12495 }
12496 
12497 /// Check an Objective-C array literal being converted to the given
12498 /// target type.
12499 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12500                                   ObjCArrayLiteral *ArrayLiteral) {
12501   if (!S.NSArrayDecl)
12502     return;
12503 
12504   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12505   if (!TargetObjCPtr)
12506     return;
12507 
12508   if (TargetObjCPtr->isUnspecialized() ||
12509       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12510         != S.NSArrayDecl->getCanonicalDecl())
12511     return;
12512 
12513   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12514   if (TypeArgs.size() != 1)
12515     return;
12516 
12517   QualType TargetElementType = TypeArgs[0];
12518   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12519     checkObjCCollectionLiteralElement(S, TargetElementType,
12520                                       ArrayLiteral->getElement(I),
12521                                       0);
12522   }
12523 }
12524 
12525 /// Check an Objective-C dictionary literal being converted to the given
12526 /// target type.
12527 static void
12528 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12529                            ObjCDictionaryLiteral *DictionaryLiteral) {
12530   if (!S.NSDictionaryDecl)
12531     return;
12532 
12533   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12534   if (!TargetObjCPtr)
12535     return;
12536 
12537   if (TargetObjCPtr->isUnspecialized() ||
12538       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12539         != S.NSDictionaryDecl->getCanonicalDecl())
12540     return;
12541 
12542   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12543   if (TypeArgs.size() != 2)
12544     return;
12545 
12546   QualType TargetKeyType = TypeArgs[0];
12547   QualType TargetObjectType = TypeArgs[1];
12548   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12549     auto Element = DictionaryLiteral->getKeyValueElement(I);
12550     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12551     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12552   }
12553 }
12554 
12555 // Helper function to filter out cases for constant width constant conversion.
12556 // Don't warn on char array initialization or for non-decimal values.
12557 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12558                                           SourceLocation CC) {
12559   // If initializing from a constant, and the constant starts with '0',
12560   // then it is a binary, octal, or hexadecimal.  Allow these constants
12561   // to fill all the bits, even if there is a sign change.
12562   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12563     const char FirstLiteralCharacter =
12564         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12565     if (FirstLiteralCharacter == '0')
12566       return false;
12567   }
12568 
12569   // If the CC location points to a '{', and the type is char, then assume
12570   // assume it is an array initialization.
12571   if (CC.isValid() && T->isCharType()) {
12572     const char FirstContextCharacter =
12573         S.getSourceManager().getCharacterData(CC)[0];
12574     if (FirstContextCharacter == '{')
12575       return false;
12576   }
12577 
12578   return true;
12579 }
12580 
12581 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12582   const auto *IL = dyn_cast<IntegerLiteral>(E);
12583   if (!IL) {
12584     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12585       if (UO->getOpcode() == UO_Minus)
12586         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12587     }
12588   }
12589 
12590   return IL;
12591 }
12592 
12593 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12594   E = E->IgnoreParenImpCasts();
12595   SourceLocation ExprLoc = E->getExprLoc();
12596 
12597   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12598     BinaryOperator::Opcode Opc = BO->getOpcode();
12599     Expr::EvalResult Result;
12600     // Do not diagnose unsigned shifts.
12601     if (Opc == BO_Shl) {
12602       const auto *LHS = getIntegerLiteral(BO->getLHS());
12603       const auto *RHS = getIntegerLiteral(BO->getRHS());
12604       if (LHS && LHS->getValue() == 0)
12605         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12606       else if (!E->isValueDependent() && LHS && RHS &&
12607                RHS->getValue().isNonNegative() &&
12608                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12609         S.Diag(ExprLoc, diag::warn_left_shift_always)
12610             << (Result.Val.getInt() != 0);
12611       else if (E->getType()->isSignedIntegerType())
12612         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12613     }
12614   }
12615 
12616   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12617     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12618     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12619     if (!LHS || !RHS)
12620       return;
12621     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12622         (RHS->getValue() == 0 || RHS->getValue() == 1))
12623       // Do not diagnose common idioms.
12624       return;
12625     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12626       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12627   }
12628 }
12629 
12630 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12631                                     SourceLocation CC,
12632                                     bool *ICContext = nullptr,
12633                                     bool IsListInit = false) {
12634   if (E->isTypeDependent() || E->isValueDependent()) return;
12635 
12636   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12637   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12638   if (Source == Target) return;
12639   if (Target->isDependentType()) return;
12640 
12641   // If the conversion context location is invalid don't complain. We also
12642   // don't want to emit a warning if the issue occurs from the expansion of
12643   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12644   // delay this check as long as possible. Once we detect we are in that
12645   // scenario, we just return.
12646   if (CC.isInvalid())
12647     return;
12648 
12649   if (Source->isAtomicType())
12650     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12651 
12652   // Diagnose implicit casts to bool.
12653   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12654     if (isa<StringLiteral>(E))
12655       // Warn on string literal to bool.  Checks for string literals in logical
12656       // and expressions, for instance, assert(0 && "error here"), are
12657       // prevented by a check in AnalyzeImplicitConversions().
12658       return DiagnoseImpCast(S, E, T, CC,
12659                              diag::warn_impcast_string_literal_to_bool);
12660     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12661         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12662       // This covers the literal expressions that evaluate to Objective-C
12663       // objects.
12664       return DiagnoseImpCast(S, E, T, CC,
12665                              diag::warn_impcast_objective_c_literal_to_bool);
12666     }
12667     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12668       // Warn on pointer to bool conversion that is always true.
12669       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12670                                      SourceRange(CC));
12671     }
12672   }
12673 
12674   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12675   // is a typedef for signed char (macOS), then that constant value has to be 1
12676   // or 0.
12677   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12678     Expr::EvalResult Result;
12679     if (E->EvaluateAsInt(Result, S.getASTContext(),
12680                          Expr::SE_AllowSideEffects)) {
12681       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12682         adornObjCBoolConversionDiagWithTernaryFixit(
12683             S, E,
12684             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12685                 << toString(Result.Val.getInt(), 10));
12686       }
12687       return;
12688     }
12689   }
12690 
12691   // Check implicit casts from Objective-C collection literals to specialized
12692   // collection types, e.g., NSArray<NSString *> *.
12693   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12694     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12695   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12696     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12697 
12698   // Strip vector types.
12699   if (isa<VectorType>(Source)) {
12700     if (Target->isVLSTBuiltinType() &&
12701         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12702                                          QualType(Source, 0)) ||
12703          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12704                                             QualType(Source, 0))))
12705       return;
12706 
12707     if (!isa<VectorType>(Target)) {
12708       if (S.SourceMgr.isInSystemMacro(CC))
12709         return;
12710       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12711     }
12712 
12713     // If the vector cast is cast between two vectors of the same size, it is
12714     // a bitcast, not a conversion.
12715     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12716       return;
12717 
12718     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12719     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12720   }
12721   if (auto VecTy = dyn_cast<VectorType>(Target))
12722     Target = VecTy->getElementType().getTypePtr();
12723 
12724   // Strip complex types.
12725   if (isa<ComplexType>(Source)) {
12726     if (!isa<ComplexType>(Target)) {
12727       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12728         return;
12729 
12730       return DiagnoseImpCast(S, E, T, CC,
12731                              S.getLangOpts().CPlusPlus
12732                                  ? diag::err_impcast_complex_scalar
12733                                  : diag::warn_impcast_complex_scalar);
12734     }
12735 
12736     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12737     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12738   }
12739 
12740   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12741   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12742 
12743   // If the source is floating point...
12744   if (SourceBT && SourceBT->isFloatingPoint()) {
12745     // ...and the target is floating point...
12746     if (TargetBT && TargetBT->isFloatingPoint()) {
12747       // ...then warn if we're dropping FP rank.
12748 
12749       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12750           QualType(SourceBT, 0), QualType(TargetBT, 0));
12751       if (Order > 0) {
12752         // Don't warn about float constants that are precisely
12753         // representable in the target type.
12754         Expr::EvalResult result;
12755         if (E->EvaluateAsRValue(result, S.Context)) {
12756           // Value might be a float, a float vector, or a float complex.
12757           if (IsSameFloatAfterCast(result.Val,
12758                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12759                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12760             return;
12761         }
12762 
12763         if (S.SourceMgr.isInSystemMacro(CC))
12764           return;
12765 
12766         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12767       }
12768       // ... or possibly if we're increasing rank, too
12769       else if (Order < 0) {
12770         if (S.SourceMgr.isInSystemMacro(CC))
12771           return;
12772 
12773         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12774       }
12775       return;
12776     }
12777 
12778     // If the target is integral, always warn.
12779     if (TargetBT && TargetBT->isInteger()) {
12780       if (S.SourceMgr.isInSystemMacro(CC))
12781         return;
12782 
12783       DiagnoseFloatingImpCast(S, E, T, CC);
12784     }
12785 
12786     // Detect the case where a call result is converted from floating-point to
12787     // to bool, and the final argument to the call is converted from bool, to
12788     // discover this typo:
12789     //
12790     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12791     //
12792     // FIXME: This is an incredibly special case; is there some more general
12793     // way to detect this class of misplaced-parentheses bug?
12794     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12795       // Check last argument of function call to see if it is an
12796       // implicit cast from a type matching the type the result
12797       // is being cast to.
12798       CallExpr *CEx = cast<CallExpr>(E);
12799       if (unsigned NumArgs = CEx->getNumArgs()) {
12800         Expr *LastA = CEx->getArg(NumArgs - 1);
12801         Expr *InnerE = LastA->IgnoreParenImpCasts();
12802         if (isa<ImplicitCastExpr>(LastA) &&
12803             InnerE->getType()->isBooleanType()) {
12804           // Warn on this floating-point to bool conversion
12805           DiagnoseImpCast(S, E, T, CC,
12806                           diag::warn_impcast_floating_point_to_bool);
12807         }
12808       }
12809     }
12810     return;
12811   }
12812 
12813   // Valid casts involving fixed point types should be accounted for here.
12814   if (Source->isFixedPointType()) {
12815     if (Target->isUnsaturatedFixedPointType()) {
12816       Expr::EvalResult Result;
12817       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12818                                   S.isConstantEvaluated())) {
12819         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12820         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12821         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12822         if (Value > MaxVal || Value < MinVal) {
12823           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12824                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12825                                     << Value.toString() << T
12826                                     << E->getSourceRange()
12827                                     << clang::SourceRange(CC));
12828           return;
12829         }
12830       }
12831     } else if (Target->isIntegerType()) {
12832       Expr::EvalResult Result;
12833       if (!S.isConstantEvaluated() &&
12834           E->EvaluateAsFixedPoint(Result, S.Context,
12835                                   Expr::SE_AllowSideEffects)) {
12836         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12837 
12838         bool Overflowed;
12839         llvm::APSInt IntResult = FXResult.convertToInt(
12840             S.Context.getIntWidth(T),
12841             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12842 
12843         if (Overflowed) {
12844           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12845                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12846                                     << FXResult.toString() << T
12847                                     << E->getSourceRange()
12848                                     << clang::SourceRange(CC));
12849           return;
12850         }
12851       }
12852     }
12853   } else if (Target->isUnsaturatedFixedPointType()) {
12854     if (Source->isIntegerType()) {
12855       Expr::EvalResult Result;
12856       if (!S.isConstantEvaluated() &&
12857           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12858         llvm::APSInt Value = Result.Val.getInt();
12859 
12860         bool Overflowed;
12861         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12862             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12863 
12864         if (Overflowed) {
12865           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12866                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12867                                     << toString(Value, /*Radix=*/10) << T
12868                                     << E->getSourceRange()
12869                                     << clang::SourceRange(CC));
12870           return;
12871         }
12872       }
12873     }
12874   }
12875 
12876   // If we are casting an integer type to a floating point type without
12877   // initialization-list syntax, we might lose accuracy if the floating
12878   // point type has a narrower significand than the integer type.
12879   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12880       TargetBT->isFloatingType() && !IsListInit) {
12881     // Determine the number of precision bits in the source integer type.
12882     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12883                                         /*Approximate*/ true);
12884     unsigned int SourcePrecision = SourceRange.Width;
12885 
12886     // Determine the number of precision bits in the
12887     // target floating point type.
12888     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12889         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12890 
12891     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12892         SourcePrecision > TargetPrecision) {
12893 
12894       if (Optional<llvm::APSInt> SourceInt =
12895               E->getIntegerConstantExpr(S.Context)) {
12896         // If the source integer is a constant, convert it to the target
12897         // floating point type. Issue a warning if the value changes
12898         // during the whole conversion.
12899         llvm::APFloat TargetFloatValue(
12900             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12901         llvm::APFloat::opStatus ConversionStatus =
12902             TargetFloatValue.convertFromAPInt(
12903                 *SourceInt, SourceBT->isSignedInteger(),
12904                 llvm::APFloat::rmNearestTiesToEven);
12905 
12906         if (ConversionStatus != llvm::APFloat::opOK) {
12907           SmallString<32> PrettySourceValue;
12908           SourceInt->toString(PrettySourceValue, 10);
12909           SmallString<32> PrettyTargetValue;
12910           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12911 
12912           S.DiagRuntimeBehavior(
12913               E->getExprLoc(), E,
12914               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12915                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12916                   << E->getSourceRange() << clang::SourceRange(CC));
12917         }
12918       } else {
12919         // Otherwise, the implicit conversion may lose precision.
12920         DiagnoseImpCast(S, E, T, CC,
12921                         diag::warn_impcast_integer_float_precision);
12922       }
12923     }
12924   }
12925 
12926   DiagnoseNullConversion(S, E, T, CC);
12927 
12928   S.DiscardMisalignedMemberAddress(Target, E);
12929 
12930   if (Target->isBooleanType())
12931     DiagnoseIntInBoolContext(S, E);
12932 
12933   if (!Source->isIntegerType() || !Target->isIntegerType())
12934     return;
12935 
12936   // TODO: remove this early return once the false positives for constant->bool
12937   // in templates, macros, etc, are reduced or removed.
12938   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12939     return;
12940 
12941   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12942       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12943     return adornObjCBoolConversionDiagWithTernaryFixit(
12944         S, E,
12945         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12946             << E->getType());
12947   }
12948 
12949   IntRange SourceTypeRange =
12950       IntRange::forTargetOfCanonicalType(S.Context, Source);
12951   IntRange LikelySourceRange =
12952       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12953   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12954 
12955   if (LikelySourceRange.Width > TargetRange.Width) {
12956     // If the source is a constant, use a default-on diagnostic.
12957     // TODO: this should happen for bitfield stores, too.
12958     Expr::EvalResult Result;
12959     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12960                          S.isConstantEvaluated())) {
12961       llvm::APSInt Value(32);
12962       Value = Result.Val.getInt();
12963 
12964       if (S.SourceMgr.isInSystemMacro(CC))
12965         return;
12966 
12967       std::string PrettySourceValue = toString(Value, 10);
12968       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12969 
12970       S.DiagRuntimeBehavior(
12971           E->getExprLoc(), E,
12972           S.PDiag(diag::warn_impcast_integer_precision_constant)
12973               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12974               << E->getSourceRange() << SourceRange(CC));
12975       return;
12976     }
12977 
12978     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12979     if (S.SourceMgr.isInSystemMacro(CC))
12980       return;
12981 
12982     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12983       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12984                              /* pruneControlFlow */ true);
12985     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12986   }
12987 
12988   if (TargetRange.Width > SourceTypeRange.Width) {
12989     if (auto *UO = dyn_cast<UnaryOperator>(E))
12990       if (UO->getOpcode() == UO_Minus)
12991         if (Source->isUnsignedIntegerType()) {
12992           if (Target->isUnsignedIntegerType())
12993             return DiagnoseImpCast(S, E, T, CC,
12994                                    diag::warn_impcast_high_order_zero_bits);
12995           if (Target->isSignedIntegerType())
12996             return DiagnoseImpCast(S, E, T, CC,
12997                                    diag::warn_impcast_nonnegative_result);
12998         }
12999   }
13000 
13001   if (TargetRange.Width == LikelySourceRange.Width &&
13002       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13003       Source->isSignedIntegerType()) {
13004     // Warn when doing a signed to signed conversion, warn if the positive
13005     // source value is exactly the width of the target type, which will
13006     // cause a negative value to be stored.
13007 
13008     Expr::EvalResult Result;
13009     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13010         !S.SourceMgr.isInSystemMacro(CC)) {
13011       llvm::APSInt Value = Result.Val.getInt();
13012       if (isSameWidthConstantConversion(S, E, T, CC)) {
13013         std::string PrettySourceValue = toString(Value, 10);
13014         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13015 
13016         S.DiagRuntimeBehavior(
13017             E->getExprLoc(), E,
13018             S.PDiag(diag::warn_impcast_integer_precision_constant)
13019                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13020                 << E->getSourceRange() << SourceRange(CC));
13021         return;
13022       }
13023     }
13024 
13025     // Fall through for non-constants to give a sign conversion warning.
13026   }
13027 
13028   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13029       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13030        LikelySourceRange.Width == TargetRange.Width)) {
13031     if (S.SourceMgr.isInSystemMacro(CC))
13032       return;
13033 
13034     unsigned DiagID = diag::warn_impcast_integer_sign;
13035 
13036     // Traditionally, gcc has warned about this under -Wsign-compare.
13037     // We also want to warn about it in -Wconversion.
13038     // So if -Wconversion is off, use a completely identical diagnostic
13039     // in the sign-compare group.
13040     // The conditional-checking code will
13041     if (ICContext) {
13042       DiagID = diag::warn_impcast_integer_sign_conditional;
13043       *ICContext = true;
13044     }
13045 
13046     return DiagnoseImpCast(S, E, T, CC, DiagID);
13047   }
13048 
13049   // Diagnose conversions between different enumeration types.
13050   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13051   // type, to give us better diagnostics.
13052   QualType SourceType = E->getType();
13053   if (!S.getLangOpts().CPlusPlus) {
13054     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13055       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13056         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13057         SourceType = S.Context.getTypeDeclType(Enum);
13058         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13059       }
13060   }
13061 
13062   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13063     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13064       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13065           TargetEnum->getDecl()->hasNameForLinkage() &&
13066           SourceEnum != TargetEnum) {
13067         if (S.SourceMgr.isInSystemMacro(CC))
13068           return;
13069 
13070         return DiagnoseImpCast(S, E, SourceType, T, CC,
13071                                diag::warn_impcast_different_enum_types);
13072       }
13073 }
13074 
13075 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13076                                      SourceLocation CC, QualType T);
13077 
13078 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13079                                     SourceLocation CC, bool &ICContext) {
13080   E = E->IgnoreParenImpCasts();
13081 
13082   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13083     return CheckConditionalOperator(S, CO, CC, T);
13084 
13085   AnalyzeImplicitConversions(S, E, CC);
13086   if (E->getType() != T)
13087     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13088 }
13089 
13090 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13091                                      SourceLocation CC, QualType T) {
13092   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13093 
13094   Expr *TrueExpr = E->getTrueExpr();
13095   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13096     TrueExpr = BCO->getCommon();
13097 
13098   bool Suspicious = false;
13099   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13100   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13101 
13102   if (T->isBooleanType())
13103     DiagnoseIntInBoolContext(S, E);
13104 
13105   // If -Wconversion would have warned about either of the candidates
13106   // for a signedness conversion to the context type...
13107   if (!Suspicious) return;
13108 
13109   // ...but it's currently ignored...
13110   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13111     return;
13112 
13113   // ...then check whether it would have warned about either of the
13114   // candidates for a signedness conversion to the condition type.
13115   if (E->getType() == T) return;
13116 
13117   Suspicious = false;
13118   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13119                           E->getType(), CC, &Suspicious);
13120   if (!Suspicious)
13121     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13122                             E->getType(), CC, &Suspicious);
13123 }
13124 
13125 /// Check conversion of given expression to boolean.
13126 /// Input argument E is a logical expression.
13127 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13128   if (S.getLangOpts().Bool)
13129     return;
13130   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13131     return;
13132   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13133 }
13134 
13135 namespace {
13136 struct AnalyzeImplicitConversionsWorkItem {
13137   Expr *E;
13138   SourceLocation CC;
13139   bool IsListInit;
13140 };
13141 }
13142 
13143 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13144 /// that should be visited are added to WorkList.
13145 static void AnalyzeImplicitConversions(
13146     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13147     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13148   Expr *OrigE = Item.E;
13149   SourceLocation CC = Item.CC;
13150 
13151   QualType T = OrigE->getType();
13152   Expr *E = OrigE->IgnoreParenImpCasts();
13153 
13154   // Propagate whether we are in a C++ list initialization expression.
13155   // If so, we do not issue warnings for implicit int-float conversion
13156   // precision loss, because C++11 narrowing already handles it.
13157   bool IsListInit = Item.IsListInit ||
13158                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13159 
13160   if (E->isTypeDependent() || E->isValueDependent())
13161     return;
13162 
13163   Expr *SourceExpr = E;
13164   // Examine, but don't traverse into the source expression of an
13165   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13166   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13167   // evaluate it in the context of checking the specific conversion to T though.
13168   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13169     if (auto *Src = OVE->getSourceExpr())
13170       SourceExpr = Src;
13171 
13172   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13173     if (UO->getOpcode() == UO_Not &&
13174         UO->getSubExpr()->isKnownToHaveBooleanValue())
13175       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13176           << OrigE->getSourceRange() << T->isBooleanType()
13177           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13178 
13179   // For conditional operators, we analyze the arguments as if they
13180   // were being fed directly into the output.
13181   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13182     CheckConditionalOperator(S, CO, CC, T);
13183     return;
13184   }
13185 
13186   // Check implicit argument conversions for function calls.
13187   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13188     CheckImplicitArgumentConversions(S, Call, CC);
13189 
13190   // Go ahead and check any implicit conversions we might have skipped.
13191   // The non-canonical typecheck is just an optimization;
13192   // CheckImplicitConversion will filter out dead implicit conversions.
13193   if (SourceExpr->getType() != T)
13194     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13195 
13196   // Now continue drilling into this expression.
13197 
13198   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13199     // The bound subexpressions in a PseudoObjectExpr are not reachable
13200     // as transitive children.
13201     // FIXME: Use a more uniform representation for this.
13202     for (auto *SE : POE->semantics())
13203       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13204         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13205   }
13206 
13207   // Skip past explicit casts.
13208   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13209     E = CE->getSubExpr()->IgnoreParenImpCasts();
13210     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13211       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13212     WorkList.push_back({E, CC, IsListInit});
13213     return;
13214   }
13215 
13216   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13217     // Do a somewhat different check with comparison operators.
13218     if (BO->isComparisonOp())
13219       return AnalyzeComparison(S, BO);
13220 
13221     // And with simple assignments.
13222     if (BO->getOpcode() == BO_Assign)
13223       return AnalyzeAssignment(S, BO);
13224     // And with compound assignments.
13225     if (BO->isAssignmentOp())
13226       return AnalyzeCompoundAssignment(S, BO);
13227   }
13228 
13229   // These break the otherwise-useful invariant below.  Fortunately,
13230   // we don't really need to recurse into them, because any internal
13231   // expressions should have been analyzed already when they were
13232   // built into statements.
13233   if (isa<StmtExpr>(E)) return;
13234 
13235   // Don't descend into unevaluated contexts.
13236   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13237 
13238   // Now just recurse over the expression's children.
13239   CC = E->getExprLoc();
13240   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13241   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13242   for (Stmt *SubStmt : E->children()) {
13243     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13244     if (!ChildExpr)
13245       continue;
13246 
13247     if (IsLogicalAndOperator &&
13248         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13249       // Ignore checking string literals that are in logical and operators.
13250       // This is a common pattern for asserts.
13251       continue;
13252     WorkList.push_back({ChildExpr, CC, IsListInit});
13253   }
13254 
13255   if (BO && BO->isLogicalOp()) {
13256     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13257     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13258       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13259 
13260     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13261     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13262       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13263   }
13264 
13265   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13266     if (U->getOpcode() == UO_LNot) {
13267       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13268     } else if (U->getOpcode() != UO_AddrOf) {
13269       if (U->getSubExpr()->getType()->isAtomicType())
13270         S.Diag(U->getSubExpr()->getBeginLoc(),
13271                diag::warn_atomic_implicit_seq_cst);
13272     }
13273   }
13274 }
13275 
13276 /// AnalyzeImplicitConversions - Find and report any interesting
13277 /// implicit conversions in the given expression.  There are a couple
13278 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13279 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13280                                        bool IsListInit/*= false*/) {
13281   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13282   WorkList.push_back({OrigE, CC, IsListInit});
13283   while (!WorkList.empty())
13284     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13285 }
13286 
13287 /// Diagnose integer type and any valid implicit conversion to it.
13288 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13289   // Taking into account implicit conversions,
13290   // allow any integer.
13291   if (!E->getType()->isIntegerType()) {
13292     S.Diag(E->getBeginLoc(),
13293            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13294     return true;
13295   }
13296   // Potentially emit standard warnings for implicit conversions if enabled
13297   // using -Wconversion.
13298   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13299   return false;
13300 }
13301 
13302 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13303 // Returns true when emitting a warning about taking the address of a reference.
13304 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13305                               const PartialDiagnostic &PD) {
13306   E = E->IgnoreParenImpCasts();
13307 
13308   const FunctionDecl *FD = nullptr;
13309 
13310   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13311     if (!DRE->getDecl()->getType()->isReferenceType())
13312       return false;
13313   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13314     if (!M->getMemberDecl()->getType()->isReferenceType())
13315       return false;
13316   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13317     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13318       return false;
13319     FD = Call->getDirectCallee();
13320   } else {
13321     return false;
13322   }
13323 
13324   SemaRef.Diag(E->getExprLoc(), PD);
13325 
13326   // If possible, point to location of function.
13327   if (FD) {
13328     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13329   }
13330 
13331   return true;
13332 }
13333 
13334 // Returns true if the SourceLocation is expanded from any macro body.
13335 // Returns false if the SourceLocation is invalid, is from not in a macro
13336 // expansion, or is from expanded from a top-level macro argument.
13337 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13338   if (Loc.isInvalid())
13339     return false;
13340 
13341   while (Loc.isMacroID()) {
13342     if (SM.isMacroBodyExpansion(Loc))
13343       return true;
13344     Loc = SM.getImmediateMacroCallerLoc(Loc);
13345   }
13346 
13347   return false;
13348 }
13349 
13350 /// Diagnose pointers that are always non-null.
13351 /// \param E the expression containing the pointer
13352 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13353 /// compared to a null pointer
13354 /// \param IsEqual True when the comparison is equal to a null pointer
13355 /// \param Range Extra SourceRange to highlight in the diagnostic
13356 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13357                                         Expr::NullPointerConstantKind NullKind,
13358                                         bool IsEqual, SourceRange Range) {
13359   if (!E)
13360     return;
13361 
13362   // Don't warn inside macros.
13363   if (E->getExprLoc().isMacroID()) {
13364     const SourceManager &SM = getSourceManager();
13365     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13366         IsInAnyMacroBody(SM, Range.getBegin()))
13367       return;
13368   }
13369   E = E->IgnoreImpCasts();
13370 
13371   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13372 
13373   if (isa<CXXThisExpr>(E)) {
13374     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13375                                 : diag::warn_this_bool_conversion;
13376     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13377     return;
13378   }
13379 
13380   bool IsAddressOf = false;
13381 
13382   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13383     if (UO->getOpcode() != UO_AddrOf)
13384       return;
13385     IsAddressOf = true;
13386     E = UO->getSubExpr();
13387   }
13388 
13389   if (IsAddressOf) {
13390     unsigned DiagID = IsCompare
13391                           ? diag::warn_address_of_reference_null_compare
13392                           : diag::warn_address_of_reference_bool_conversion;
13393     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13394                                          << IsEqual;
13395     if (CheckForReference(*this, E, PD)) {
13396       return;
13397     }
13398   }
13399 
13400   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13401     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13402     std::string Str;
13403     llvm::raw_string_ostream S(Str);
13404     E->printPretty(S, nullptr, getPrintingPolicy());
13405     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13406                                 : diag::warn_cast_nonnull_to_bool;
13407     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13408       << E->getSourceRange() << Range << IsEqual;
13409     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13410   };
13411 
13412   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13413   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13414     if (auto *Callee = Call->getDirectCallee()) {
13415       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13416         ComplainAboutNonnullParamOrCall(A);
13417         return;
13418       }
13419     }
13420   }
13421 
13422   // Expect to find a single Decl.  Skip anything more complicated.
13423   ValueDecl *D = nullptr;
13424   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13425     D = R->getDecl();
13426   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13427     D = M->getMemberDecl();
13428   }
13429 
13430   // Weak Decls can be null.
13431   if (!D || D->isWeak())
13432     return;
13433 
13434   // Check for parameter decl with nonnull attribute
13435   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13436     if (getCurFunction() &&
13437         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13438       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13439         ComplainAboutNonnullParamOrCall(A);
13440         return;
13441       }
13442 
13443       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13444         // Skip function template not specialized yet.
13445         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13446           return;
13447         auto ParamIter = llvm::find(FD->parameters(), PV);
13448         assert(ParamIter != FD->param_end());
13449         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13450 
13451         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13452           if (!NonNull->args_size()) {
13453               ComplainAboutNonnullParamOrCall(NonNull);
13454               return;
13455           }
13456 
13457           for (const ParamIdx &ArgNo : NonNull->args()) {
13458             if (ArgNo.getASTIndex() == ParamNo) {
13459               ComplainAboutNonnullParamOrCall(NonNull);
13460               return;
13461             }
13462           }
13463         }
13464       }
13465     }
13466   }
13467 
13468   QualType T = D->getType();
13469   const bool IsArray = T->isArrayType();
13470   const bool IsFunction = T->isFunctionType();
13471 
13472   // Address of function is used to silence the function warning.
13473   if (IsAddressOf && IsFunction) {
13474     return;
13475   }
13476 
13477   // Found nothing.
13478   if (!IsAddressOf && !IsFunction && !IsArray)
13479     return;
13480 
13481   // Pretty print the expression for the diagnostic.
13482   std::string Str;
13483   llvm::raw_string_ostream S(Str);
13484   E->printPretty(S, nullptr, getPrintingPolicy());
13485 
13486   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13487                               : diag::warn_impcast_pointer_to_bool;
13488   enum {
13489     AddressOf,
13490     FunctionPointer,
13491     ArrayPointer
13492   } DiagType;
13493   if (IsAddressOf)
13494     DiagType = AddressOf;
13495   else if (IsFunction)
13496     DiagType = FunctionPointer;
13497   else if (IsArray)
13498     DiagType = ArrayPointer;
13499   else
13500     llvm_unreachable("Could not determine diagnostic.");
13501   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13502                                 << Range << IsEqual;
13503 
13504   if (!IsFunction)
13505     return;
13506 
13507   // Suggest '&' to silence the function warning.
13508   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13509       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13510 
13511   // Check to see if '()' fixit should be emitted.
13512   QualType ReturnType;
13513   UnresolvedSet<4> NonTemplateOverloads;
13514   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13515   if (ReturnType.isNull())
13516     return;
13517 
13518   if (IsCompare) {
13519     // There are two cases here.  If there is null constant, the only suggest
13520     // for a pointer return type.  If the null is 0, then suggest if the return
13521     // type is a pointer or an integer type.
13522     if (!ReturnType->isPointerType()) {
13523       if (NullKind == Expr::NPCK_ZeroExpression ||
13524           NullKind == Expr::NPCK_ZeroLiteral) {
13525         if (!ReturnType->isIntegerType())
13526           return;
13527       } else {
13528         return;
13529       }
13530     }
13531   } else { // !IsCompare
13532     // For function to bool, only suggest if the function pointer has bool
13533     // return type.
13534     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13535       return;
13536   }
13537   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13538       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13539 }
13540 
13541 /// Diagnoses "dangerous" implicit conversions within the given
13542 /// expression (which is a full expression).  Implements -Wconversion
13543 /// and -Wsign-compare.
13544 ///
13545 /// \param CC the "context" location of the implicit conversion, i.e.
13546 ///   the most location of the syntactic entity requiring the implicit
13547 ///   conversion
13548 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13549   // Don't diagnose in unevaluated contexts.
13550   if (isUnevaluatedContext())
13551     return;
13552 
13553   // Don't diagnose for value- or type-dependent expressions.
13554   if (E->isTypeDependent() || E->isValueDependent())
13555     return;
13556 
13557   // Check for array bounds violations in cases where the check isn't triggered
13558   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13559   // ArraySubscriptExpr is on the RHS of a variable initialization.
13560   CheckArrayAccess(E);
13561 
13562   // This is not the right CC for (e.g.) a variable initialization.
13563   AnalyzeImplicitConversions(*this, E, CC);
13564 }
13565 
13566 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13567 /// Input argument E is a logical expression.
13568 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13569   ::CheckBoolLikeConversion(*this, E, CC);
13570 }
13571 
13572 /// Diagnose when expression is an integer constant expression and its evaluation
13573 /// results in integer overflow
13574 void Sema::CheckForIntOverflow (Expr *E) {
13575   // Use a work list to deal with nested struct initializers.
13576   SmallVector<Expr *, 2> Exprs(1, E);
13577 
13578   do {
13579     Expr *OriginalE = Exprs.pop_back_val();
13580     Expr *E = OriginalE->IgnoreParenCasts();
13581 
13582     if (isa<BinaryOperator>(E)) {
13583       E->EvaluateForOverflow(Context);
13584       continue;
13585     }
13586 
13587     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13588       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13589     else if (isa<ObjCBoxedExpr>(OriginalE))
13590       E->EvaluateForOverflow(Context);
13591     else if (auto Call = dyn_cast<CallExpr>(E))
13592       Exprs.append(Call->arg_begin(), Call->arg_end());
13593     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13594       Exprs.append(Message->arg_begin(), Message->arg_end());
13595   } while (!Exprs.empty());
13596 }
13597 
13598 namespace {
13599 
13600 /// Visitor for expressions which looks for unsequenced operations on the
13601 /// same object.
13602 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13603   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13604 
13605   /// A tree of sequenced regions within an expression. Two regions are
13606   /// unsequenced if one is an ancestor or a descendent of the other. When we
13607   /// finish processing an expression with sequencing, such as a comma
13608   /// expression, we fold its tree nodes into its parent, since they are
13609   /// unsequenced with respect to nodes we will visit later.
13610   class SequenceTree {
13611     struct Value {
13612       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13613       unsigned Parent : 31;
13614       unsigned Merged : 1;
13615     };
13616     SmallVector<Value, 8> Values;
13617 
13618   public:
13619     /// A region within an expression which may be sequenced with respect
13620     /// to some other region.
13621     class Seq {
13622       friend class SequenceTree;
13623 
13624       unsigned Index;
13625 
13626       explicit Seq(unsigned N) : Index(N) {}
13627 
13628     public:
13629       Seq() : Index(0) {}
13630     };
13631 
13632     SequenceTree() { Values.push_back(Value(0)); }
13633     Seq root() const { return Seq(0); }
13634 
13635     /// Create a new sequence of operations, which is an unsequenced
13636     /// subset of \p Parent. This sequence of operations is sequenced with
13637     /// respect to other children of \p Parent.
13638     Seq allocate(Seq Parent) {
13639       Values.push_back(Value(Parent.Index));
13640       return Seq(Values.size() - 1);
13641     }
13642 
13643     /// Merge a sequence of operations into its parent.
13644     void merge(Seq S) {
13645       Values[S.Index].Merged = true;
13646     }
13647 
13648     /// Determine whether two operations are unsequenced. This operation
13649     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13650     /// should have been merged into its parent as appropriate.
13651     bool isUnsequenced(Seq Cur, Seq Old) {
13652       unsigned C = representative(Cur.Index);
13653       unsigned Target = representative(Old.Index);
13654       while (C >= Target) {
13655         if (C == Target)
13656           return true;
13657         C = Values[C].Parent;
13658       }
13659       return false;
13660     }
13661 
13662   private:
13663     /// Pick a representative for a sequence.
13664     unsigned representative(unsigned K) {
13665       if (Values[K].Merged)
13666         // Perform path compression as we go.
13667         return Values[K].Parent = representative(Values[K].Parent);
13668       return K;
13669     }
13670   };
13671 
13672   /// An object for which we can track unsequenced uses.
13673   using Object = const NamedDecl *;
13674 
13675   /// Different flavors of object usage which we track. We only track the
13676   /// least-sequenced usage of each kind.
13677   enum UsageKind {
13678     /// A read of an object. Multiple unsequenced reads are OK.
13679     UK_Use,
13680 
13681     /// A modification of an object which is sequenced before the value
13682     /// computation of the expression, such as ++n in C++.
13683     UK_ModAsValue,
13684 
13685     /// A modification of an object which is not sequenced before the value
13686     /// computation of the expression, such as n++.
13687     UK_ModAsSideEffect,
13688 
13689     UK_Count = UK_ModAsSideEffect + 1
13690   };
13691 
13692   /// Bundle together a sequencing region and the expression corresponding
13693   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13694   struct Usage {
13695     const Expr *UsageExpr;
13696     SequenceTree::Seq Seq;
13697 
13698     Usage() : UsageExpr(nullptr), Seq() {}
13699   };
13700 
13701   struct UsageInfo {
13702     Usage Uses[UK_Count];
13703 
13704     /// Have we issued a diagnostic for this object already?
13705     bool Diagnosed;
13706 
13707     UsageInfo() : Uses(), Diagnosed(false) {}
13708   };
13709   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13710 
13711   Sema &SemaRef;
13712 
13713   /// Sequenced regions within the expression.
13714   SequenceTree Tree;
13715 
13716   /// Declaration modifications and references which we have seen.
13717   UsageInfoMap UsageMap;
13718 
13719   /// The region we are currently within.
13720   SequenceTree::Seq Region;
13721 
13722   /// Filled in with declarations which were modified as a side-effect
13723   /// (that is, post-increment operations).
13724   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13725 
13726   /// Expressions to check later. We defer checking these to reduce
13727   /// stack usage.
13728   SmallVectorImpl<const Expr *> &WorkList;
13729 
13730   /// RAII object wrapping the visitation of a sequenced subexpression of an
13731   /// expression. At the end of this process, the side-effects of the evaluation
13732   /// become sequenced with respect to the value computation of the result, so
13733   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13734   /// UK_ModAsValue.
13735   struct SequencedSubexpression {
13736     SequencedSubexpression(SequenceChecker &Self)
13737       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13738       Self.ModAsSideEffect = &ModAsSideEffect;
13739     }
13740 
13741     ~SequencedSubexpression() {
13742       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13743         // Add a new usage with usage kind UK_ModAsValue, and then restore
13744         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13745         // the previous one was empty).
13746         UsageInfo &UI = Self.UsageMap[M.first];
13747         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13748         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13749         SideEffectUsage = M.second;
13750       }
13751       Self.ModAsSideEffect = OldModAsSideEffect;
13752     }
13753 
13754     SequenceChecker &Self;
13755     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13756     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13757   };
13758 
13759   /// RAII object wrapping the visitation of a subexpression which we might
13760   /// choose to evaluate as a constant. If any subexpression is evaluated and
13761   /// found to be non-constant, this allows us to suppress the evaluation of
13762   /// the outer expression.
13763   class EvaluationTracker {
13764   public:
13765     EvaluationTracker(SequenceChecker &Self)
13766         : Self(Self), Prev(Self.EvalTracker) {
13767       Self.EvalTracker = this;
13768     }
13769 
13770     ~EvaluationTracker() {
13771       Self.EvalTracker = Prev;
13772       if (Prev)
13773         Prev->EvalOK &= EvalOK;
13774     }
13775 
13776     bool evaluate(const Expr *E, bool &Result) {
13777       if (!EvalOK || E->isValueDependent())
13778         return false;
13779       EvalOK = E->EvaluateAsBooleanCondition(
13780           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13781       return EvalOK;
13782     }
13783 
13784   private:
13785     SequenceChecker &Self;
13786     EvaluationTracker *Prev;
13787     bool EvalOK = true;
13788   } *EvalTracker = nullptr;
13789 
13790   /// Find the object which is produced by the specified expression,
13791   /// if any.
13792   Object getObject(const Expr *E, bool Mod) const {
13793     E = E->IgnoreParenCasts();
13794     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13795       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13796         return getObject(UO->getSubExpr(), Mod);
13797     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13798       if (BO->getOpcode() == BO_Comma)
13799         return getObject(BO->getRHS(), Mod);
13800       if (Mod && BO->isAssignmentOp())
13801         return getObject(BO->getLHS(), Mod);
13802     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13803       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13804       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13805         return ME->getMemberDecl();
13806     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13807       // FIXME: If this is a reference, map through to its value.
13808       return DRE->getDecl();
13809     return nullptr;
13810   }
13811 
13812   /// Note that an object \p O was modified or used by an expression
13813   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13814   /// the object \p O as obtained via the \p UsageMap.
13815   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13816     // Get the old usage for the given object and usage kind.
13817     Usage &U = UI.Uses[UK];
13818     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13819       // If we have a modification as side effect and are in a sequenced
13820       // subexpression, save the old Usage so that we can restore it later
13821       // in SequencedSubexpression::~SequencedSubexpression.
13822       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13823         ModAsSideEffect->push_back(std::make_pair(O, U));
13824       // Then record the new usage with the current sequencing region.
13825       U.UsageExpr = UsageExpr;
13826       U.Seq = Region;
13827     }
13828   }
13829 
13830   /// Check whether a modification or use of an object \p O in an expression
13831   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13832   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13833   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13834   /// usage and false we are checking for a mod-use unsequenced usage.
13835   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13836                   UsageKind OtherKind, bool IsModMod) {
13837     if (UI.Diagnosed)
13838       return;
13839 
13840     const Usage &U = UI.Uses[OtherKind];
13841     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13842       return;
13843 
13844     const Expr *Mod = U.UsageExpr;
13845     const Expr *ModOrUse = UsageExpr;
13846     if (OtherKind == UK_Use)
13847       std::swap(Mod, ModOrUse);
13848 
13849     SemaRef.DiagRuntimeBehavior(
13850         Mod->getExprLoc(), {Mod, ModOrUse},
13851         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13852                                : diag::warn_unsequenced_mod_use)
13853             << O << SourceRange(ModOrUse->getExprLoc()));
13854     UI.Diagnosed = true;
13855   }
13856 
13857   // A note on note{Pre, Post}{Use, Mod}:
13858   //
13859   // (It helps to follow the algorithm with an expression such as
13860   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13861   //  operations before C++17 and both are well-defined in C++17).
13862   //
13863   // When visiting a node which uses/modify an object we first call notePreUse
13864   // or notePreMod before visiting its sub-expression(s). At this point the
13865   // children of the current node have not yet been visited and so the eventual
13866   // uses/modifications resulting from the children of the current node have not
13867   // been recorded yet.
13868   //
13869   // We then visit the children of the current node. After that notePostUse or
13870   // notePostMod is called. These will 1) detect an unsequenced modification
13871   // as side effect (as in "k++ + k") and 2) add a new usage with the
13872   // appropriate usage kind.
13873   //
13874   // We also have to be careful that some operation sequences modification as
13875   // side effect as well (for example: || or ,). To account for this we wrap
13876   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13877   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13878   // which record usages which are modifications as side effect, and then
13879   // downgrade them (or more accurately restore the previous usage which was a
13880   // modification as side effect) when exiting the scope of the sequenced
13881   // subexpression.
13882 
13883   void notePreUse(Object O, const Expr *UseExpr) {
13884     UsageInfo &UI = UsageMap[O];
13885     // Uses conflict with other modifications.
13886     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13887   }
13888 
13889   void notePostUse(Object O, const Expr *UseExpr) {
13890     UsageInfo &UI = UsageMap[O];
13891     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13892                /*IsModMod=*/false);
13893     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13894   }
13895 
13896   void notePreMod(Object O, const Expr *ModExpr) {
13897     UsageInfo &UI = UsageMap[O];
13898     // Modifications conflict with other modifications and with uses.
13899     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13900     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13901   }
13902 
13903   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13904     UsageInfo &UI = UsageMap[O];
13905     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13906                /*IsModMod=*/true);
13907     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13908   }
13909 
13910 public:
13911   SequenceChecker(Sema &S, const Expr *E,
13912                   SmallVectorImpl<const Expr *> &WorkList)
13913       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13914     Visit(E);
13915     // Silence a -Wunused-private-field since WorkList is now unused.
13916     // TODO: Evaluate if it can be used, and if not remove it.
13917     (void)this->WorkList;
13918   }
13919 
13920   void VisitStmt(const Stmt *S) {
13921     // Skip all statements which aren't expressions for now.
13922   }
13923 
13924   void VisitExpr(const Expr *E) {
13925     // By default, just recurse to evaluated subexpressions.
13926     Base::VisitStmt(E);
13927   }
13928 
13929   void VisitCastExpr(const CastExpr *E) {
13930     Object O = Object();
13931     if (E->getCastKind() == CK_LValueToRValue)
13932       O = getObject(E->getSubExpr(), false);
13933 
13934     if (O)
13935       notePreUse(O, E);
13936     VisitExpr(E);
13937     if (O)
13938       notePostUse(O, E);
13939   }
13940 
13941   void VisitSequencedExpressions(const Expr *SequencedBefore,
13942                                  const Expr *SequencedAfter) {
13943     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13944     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13945     SequenceTree::Seq OldRegion = Region;
13946 
13947     {
13948       SequencedSubexpression SeqBefore(*this);
13949       Region = BeforeRegion;
13950       Visit(SequencedBefore);
13951     }
13952 
13953     Region = AfterRegion;
13954     Visit(SequencedAfter);
13955 
13956     Region = OldRegion;
13957 
13958     Tree.merge(BeforeRegion);
13959     Tree.merge(AfterRegion);
13960   }
13961 
13962   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13963     // C++17 [expr.sub]p1:
13964     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13965     //   expression E1 is sequenced before the expression E2.
13966     if (SemaRef.getLangOpts().CPlusPlus17)
13967       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13968     else {
13969       Visit(ASE->getLHS());
13970       Visit(ASE->getRHS());
13971     }
13972   }
13973 
13974   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13975   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13976   void VisitBinPtrMem(const BinaryOperator *BO) {
13977     // C++17 [expr.mptr.oper]p4:
13978     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13979     //  the expression E1 is sequenced before the expression E2.
13980     if (SemaRef.getLangOpts().CPlusPlus17)
13981       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13982     else {
13983       Visit(BO->getLHS());
13984       Visit(BO->getRHS());
13985     }
13986   }
13987 
13988   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13989   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13990   void VisitBinShlShr(const BinaryOperator *BO) {
13991     // C++17 [expr.shift]p4:
13992     //  The expression E1 is sequenced before the expression E2.
13993     if (SemaRef.getLangOpts().CPlusPlus17)
13994       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13995     else {
13996       Visit(BO->getLHS());
13997       Visit(BO->getRHS());
13998     }
13999   }
14000 
14001   void VisitBinComma(const BinaryOperator *BO) {
14002     // C++11 [expr.comma]p1:
14003     //   Every value computation and side effect associated with the left
14004     //   expression is sequenced before every value computation and side
14005     //   effect associated with the right expression.
14006     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14007   }
14008 
14009   void VisitBinAssign(const BinaryOperator *BO) {
14010     SequenceTree::Seq RHSRegion;
14011     SequenceTree::Seq LHSRegion;
14012     if (SemaRef.getLangOpts().CPlusPlus17) {
14013       RHSRegion = Tree.allocate(Region);
14014       LHSRegion = Tree.allocate(Region);
14015     } else {
14016       RHSRegion = Region;
14017       LHSRegion = Region;
14018     }
14019     SequenceTree::Seq OldRegion = Region;
14020 
14021     // C++11 [expr.ass]p1:
14022     //  [...] the assignment is sequenced after the value computation
14023     //  of the right and left operands, [...]
14024     //
14025     // so check it before inspecting the operands and update the
14026     // map afterwards.
14027     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14028     if (O)
14029       notePreMod(O, BO);
14030 
14031     if (SemaRef.getLangOpts().CPlusPlus17) {
14032       // C++17 [expr.ass]p1:
14033       //  [...] The right operand is sequenced before the left operand. [...]
14034       {
14035         SequencedSubexpression SeqBefore(*this);
14036         Region = RHSRegion;
14037         Visit(BO->getRHS());
14038       }
14039 
14040       Region = LHSRegion;
14041       Visit(BO->getLHS());
14042 
14043       if (O && isa<CompoundAssignOperator>(BO))
14044         notePostUse(O, BO);
14045 
14046     } else {
14047       // C++11 does not specify any sequencing between the LHS and RHS.
14048       Region = LHSRegion;
14049       Visit(BO->getLHS());
14050 
14051       if (O && isa<CompoundAssignOperator>(BO))
14052         notePostUse(O, BO);
14053 
14054       Region = RHSRegion;
14055       Visit(BO->getRHS());
14056     }
14057 
14058     // C++11 [expr.ass]p1:
14059     //  the assignment is sequenced [...] before the value computation of the
14060     //  assignment expression.
14061     // C11 6.5.16/3 has no such rule.
14062     Region = OldRegion;
14063     if (O)
14064       notePostMod(O, BO,
14065                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14066                                                   : UK_ModAsSideEffect);
14067     if (SemaRef.getLangOpts().CPlusPlus17) {
14068       Tree.merge(RHSRegion);
14069       Tree.merge(LHSRegion);
14070     }
14071   }
14072 
14073   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14074     VisitBinAssign(CAO);
14075   }
14076 
14077   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14078   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14079   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14080     Object O = getObject(UO->getSubExpr(), true);
14081     if (!O)
14082       return VisitExpr(UO);
14083 
14084     notePreMod(O, UO);
14085     Visit(UO->getSubExpr());
14086     // C++11 [expr.pre.incr]p1:
14087     //   the expression ++x is equivalent to x+=1
14088     notePostMod(O, UO,
14089                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14090                                                 : UK_ModAsSideEffect);
14091   }
14092 
14093   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14094   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14095   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14096     Object O = getObject(UO->getSubExpr(), true);
14097     if (!O)
14098       return VisitExpr(UO);
14099 
14100     notePreMod(O, UO);
14101     Visit(UO->getSubExpr());
14102     notePostMod(O, UO, UK_ModAsSideEffect);
14103   }
14104 
14105   void VisitBinLOr(const BinaryOperator *BO) {
14106     // C++11 [expr.log.or]p2:
14107     //  If the second expression is evaluated, every value computation and
14108     //  side effect associated with the first expression is sequenced before
14109     //  every value computation and side effect associated with the
14110     //  second expression.
14111     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14112     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14113     SequenceTree::Seq OldRegion = Region;
14114 
14115     EvaluationTracker Eval(*this);
14116     {
14117       SequencedSubexpression Sequenced(*this);
14118       Region = LHSRegion;
14119       Visit(BO->getLHS());
14120     }
14121 
14122     // C++11 [expr.log.or]p1:
14123     //  [...] the second operand is not evaluated if the first operand
14124     //  evaluates to true.
14125     bool EvalResult = false;
14126     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14127     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14128     if (ShouldVisitRHS) {
14129       Region = RHSRegion;
14130       Visit(BO->getRHS());
14131     }
14132 
14133     Region = OldRegion;
14134     Tree.merge(LHSRegion);
14135     Tree.merge(RHSRegion);
14136   }
14137 
14138   void VisitBinLAnd(const BinaryOperator *BO) {
14139     // C++11 [expr.log.and]p2:
14140     //  If the second expression is evaluated, every value computation and
14141     //  side effect associated with the first expression is sequenced before
14142     //  every value computation and side effect associated with the
14143     //  second expression.
14144     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14145     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14146     SequenceTree::Seq OldRegion = Region;
14147 
14148     EvaluationTracker Eval(*this);
14149     {
14150       SequencedSubexpression Sequenced(*this);
14151       Region = LHSRegion;
14152       Visit(BO->getLHS());
14153     }
14154 
14155     // C++11 [expr.log.and]p1:
14156     //  [...] the second operand is not evaluated if the first operand is false.
14157     bool EvalResult = false;
14158     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14159     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14160     if (ShouldVisitRHS) {
14161       Region = RHSRegion;
14162       Visit(BO->getRHS());
14163     }
14164 
14165     Region = OldRegion;
14166     Tree.merge(LHSRegion);
14167     Tree.merge(RHSRegion);
14168   }
14169 
14170   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14171     // C++11 [expr.cond]p1:
14172     //  [...] Every value computation and side effect associated with the first
14173     //  expression is sequenced before every value computation and side effect
14174     //  associated with the second or third expression.
14175     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14176 
14177     // No sequencing is specified between the true and false expression.
14178     // However since exactly one of both is going to be evaluated we can
14179     // consider them to be sequenced. This is needed to avoid warning on
14180     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14181     // both the true and false expressions because we can't evaluate x.
14182     // This will still allow us to detect an expression like (pre C++17)
14183     // "(x ? y += 1 : y += 2) = y".
14184     //
14185     // We don't wrap the visitation of the true and false expression with
14186     // SequencedSubexpression because we don't want to downgrade modifications
14187     // as side effect in the true and false expressions after the visition
14188     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14189     // not warn between the two "y++", but we should warn between the "y++"
14190     // and the "y".
14191     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14192     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14193     SequenceTree::Seq OldRegion = Region;
14194 
14195     EvaluationTracker Eval(*this);
14196     {
14197       SequencedSubexpression Sequenced(*this);
14198       Region = ConditionRegion;
14199       Visit(CO->getCond());
14200     }
14201 
14202     // C++11 [expr.cond]p1:
14203     // [...] The first expression is contextually converted to bool (Clause 4).
14204     // It is evaluated and if it is true, the result of the conditional
14205     // expression is the value of the second expression, otherwise that of the
14206     // third expression. Only one of the second and third expressions is
14207     // evaluated. [...]
14208     bool EvalResult = false;
14209     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14210     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14211     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14212     if (ShouldVisitTrueExpr) {
14213       Region = TrueRegion;
14214       Visit(CO->getTrueExpr());
14215     }
14216     if (ShouldVisitFalseExpr) {
14217       Region = FalseRegion;
14218       Visit(CO->getFalseExpr());
14219     }
14220 
14221     Region = OldRegion;
14222     Tree.merge(ConditionRegion);
14223     Tree.merge(TrueRegion);
14224     Tree.merge(FalseRegion);
14225   }
14226 
14227   void VisitCallExpr(const CallExpr *CE) {
14228     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14229 
14230     if (CE->isUnevaluatedBuiltinCall(Context))
14231       return;
14232 
14233     // C++11 [intro.execution]p15:
14234     //   When calling a function [...], every value computation and side effect
14235     //   associated with any argument expression, or with the postfix expression
14236     //   designating the called function, is sequenced before execution of every
14237     //   expression or statement in the body of the function [and thus before
14238     //   the value computation of its result].
14239     SequencedSubexpression Sequenced(*this);
14240     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14241       // C++17 [expr.call]p5
14242       //   The postfix-expression is sequenced before each expression in the
14243       //   expression-list and any default argument. [...]
14244       SequenceTree::Seq CalleeRegion;
14245       SequenceTree::Seq OtherRegion;
14246       if (SemaRef.getLangOpts().CPlusPlus17) {
14247         CalleeRegion = Tree.allocate(Region);
14248         OtherRegion = Tree.allocate(Region);
14249       } else {
14250         CalleeRegion = Region;
14251         OtherRegion = Region;
14252       }
14253       SequenceTree::Seq OldRegion = Region;
14254 
14255       // Visit the callee expression first.
14256       Region = CalleeRegion;
14257       if (SemaRef.getLangOpts().CPlusPlus17) {
14258         SequencedSubexpression Sequenced(*this);
14259         Visit(CE->getCallee());
14260       } else {
14261         Visit(CE->getCallee());
14262       }
14263 
14264       // Then visit the argument expressions.
14265       Region = OtherRegion;
14266       for (const Expr *Argument : CE->arguments())
14267         Visit(Argument);
14268 
14269       Region = OldRegion;
14270       if (SemaRef.getLangOpts().CPlusPlus17) {
14271         Tree.merge(CalleeRegion);
14272         Tree.merge(OtherRegion);
14273       }
14274     });
14275   }
14276 
14277   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14278     // C++17 [over.match.oper]p2:
14279     //   [...] the operator notation is first transformed to the equivalent
14280     //   function-call notation as summarized in Table 12 (where @ denotes one
14281     //   of the operators covered in the specified subclause). However, the
14282     //   operands are sequenced in the order prescribed for the built-in
14283     //   operator (Clause 8).
14284     //
14285     // From the above only overloaded binary operators and overloaded call
14286     // operators have sequencing rules in C++17 that we need to handle
14287     // separately.
14288     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14289         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14290       return VisitCallExpr(CXXOCE);
14291 
14292     enum {
14293       NoSequencing,
14294       LHSBeforeRHS,
14295       RHSBeforeLHS,
14296       LHSBeforeRest
14297     } SequencingKind;
14298     switch (CXXOCE->getOperator()) {
14299     case OO_Equal:
14300     case OO_PlusEqual:
14301     case OO_MinusEqual:
14302     case OO_StarEqual:
14303     case OO_SlashEqual:
14304     case OO_PercentEqual:
14305     case OO_CaretEqual:
14306     case OO_AmpEqual:
14307     case OO_PipeEqual:
14308     case OO_LessLessEqual:
14309     case OO_GreaterGreaterEqual:
14310       SequencingKind = RHSBeforeLHS;
14311       break;
14312 
14313     case OO_LessLess:
14314     case OO_GreaterGreater:
14315     case OO_AmpAmp:
14316     case OO_PipePipe:
14317     case OO_Comma:
14318     case OO_ArrowStar:
14319     case OO_Subscript:
14320       SequencingKind = LHSBeforeRHS;
14321       break;
14322 
14323     case OO_Call:
14324       SequencingKind = LHSBeforeRest;
14325       break;
14326 
14327     default:
14328       SequencingKind = NoSequencing;
14329       break;
14330     }
14331 
14332     if (SequencingKind == NoSequencing)
14333       return VisitCallExpr(CXXOCE);
14334 
14335     // This is a call, so all subexpressions are sequenced before the result.
14336     SequencedSubexpression Sequenced(*this);
14337 
14338     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14339       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14340              "Should only get there with C++17 and above!");
14341       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14342              "Should only get there with an overloaded binary operator"
14343              " or an overloaded call operator!");
14344 
14345       if (SequencingKind == LHSBeforeRest) {
14346         assert(CXXOCE->getOperator() == OO_Call &&
14347                "We should only have an overloaded call operator here!");
14348 
14349         // This is very similar to VisitCallExpr, except that we only have the
14350         // C++17 case. The postfix-expression is the first argument of the
14351         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14352         // are in the following arguments.
14353         //
14354         // Note that we intentionally do not visit the callee expression since
14355         // it is just a decayed reference to a function.
14356         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14357         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14358         SequenceTree::Seq OldRegion = Region;
14359 
14360         assert(CXXOCE->getNumArgs() >= 1 &&
14361                "An overloaded call operator must have at least one argument"
14362                " for the postfix-expression!");
14363         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14364         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14365                                           CXXOCE->getNumArgs() - 1);
14366 
14367         // Visit the postfix-expression first.
14368         {
14369           Region = PostfixExprRegion;
14370           SequencedSubexpression Sequenced(*this);
14371           Visit(PostfixExpr);
14372         }
14373 
14374         // Then visit the argument expressions.
14375         Region = ArgsRegion;
14376         for (const Expr *Arg : Args)
14377           Visit(Arg);
14378 
14379         Region = OldRegion;
14380         Tree.merge(PostfixExprRegion);
14381         Tree.merge(ArgsRegion);
14382       } else {
14383         assert(CXXOCE->getNumArgs() == 2 &&
14384                "Should only have two arguments here!");
14385         assert((SequencingKind == LHSBeforeRHS ||
14386                 SequencingKind == RHSBeforeLHS) &&
14387                "Unexpected sequencing kind!");
14388 
14389         // We do not visit the callee expression since it is just a decayed
14390         // reference to a function.
14391         const Expr *E1 = CXXOCE->getArg(0);
14392         const Expr *E2 = CXXOCE->getArg(1);
14393         if (SequencingKind == RHSBeforeLHS)
14394           std::swap(E1, E2);
14395 
14396         return VisitSequencedExpressions(E1, E2);
14397       }
14398     });
14399   }
14400 
14401   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14402     // This is a call, so all subexpressions are sequenced before the result.
14403     SequencedSubexpression Sequenced(*this);
14404 
14405     if (!CCE->isListInitialization())
14406       return VisitExpr(CCE);
14407 
14408     // In C++11, list initializations are sequenced.
14409     SmallVector<SequenceTree::Seq, 32> Elts;
14410     SequenceTree::Seq Parent = Region;
14411     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14412                                               E = CCE->arg_end();
14413          I != E; ++I) {
14414       Region = Tree.allocate(Parent);
14415       Elts.push_back(Region);
14416       Visit(*I);
14417     }
14418 
14419     // Forget that the initializers are sequenced.
14420     Region = Parent;
14421     for (unsigned I = 0; I < Elts.size(); ++I)
14422       Tree.merge(Elts[I]);
14423   }
14424 
14425   void VisitInitListExpr(const InitListExpr *ILE) {
14426     if (!SemaRef.getLangOpts().CPlusPlus11)
14427       return VisitExpr(ILE);
14428 
14429     // In C++11, list initializations are sequenced.
14430     SmallVector<SequenceTree::Seq, 32> Elts;
14431     SequenceTree::Seq Parent = Region;
14432     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14433       const Expr *E = ILE->getInit(I);
14434       if (!E)
14435         continue;
14436       Region = Tree.allocate(Parent);
14437       Elts.push_back(Region);
14438       Visit(E);
14439     }
14440 
14441     // Forget that the initializers are sequenced.
14442     Region = Parent;
14443     for (unsigned I = 0; I < Elts.size(); ++I)
14444       Tree.merge(Elts[I]);
14445   }
14446 };
14447 
14448 } // namespace
14449 
14450 void Sema::CheckUnsequencedOperations(const Expr *E) {
14451   SmallVector<const Expr *, 8> WorkList;
14452   WorkList.push_back(E);
14453   while (!WorkList.empty()) {
14454     const Expr *Item = WorkList.pop_back_val();
14455     SequenceChecker(*this, Item, WorkList);
14456   }
14457 }
14458 
14459 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14460                               bool IsConstexpr) {
14461   llvm::SaveAndRestore<bool> ConstantContext(
14462       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14463   CheckImplicitConversions(E, CheckLoc);
14464   if (!E->isInstantiationDependent())
14465     CheckUnsequencedOperations(E);
14466   if (!IsConstexpr && !E->isValueDependent())
14467     CheckForIntOverflow(E);
14468   DiagnoseMisalignedMembers();
14469 }
14470 
14471 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14472                                        FieldDecl *BitField,
14473                                        Expr *Init) {
14474   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14475 }
14476 
14477 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14478                                          SourceLocation Loc) {
14479   if (!PType->isVariablyModifiedType())
14480     return;
14481   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14482     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14483     return;
14484   }
14485   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14486     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14487     return;
14488   }
14489   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14490     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14491     return;
14492   }
14493 
14494   const ArrayType *AT = S.Context.getAsArrayType(PType);
14495   if (!AT)
14496     return;
14497 
14498   if (AT->getSizeModifier() != ArrayType::Star) {
14499     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14500     return;
14501   }
14502 
14503   S.Diag(Loc, diag::err_array_star_in_function_definition);
14504 }
14505 
14506 /// CheckParmsForFunctionDef - Check that the parameters of the given
14507 /// function are appropriate for the definition of a function. This
14508 /// takes care of any checks that cannot be performed on the
14509 /// declaration itself, e.g., that the types of each of the function
14510 /// parameters are complete.
14511 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14512                                     bool CheckParameterNames) {
14513   bool HasInvalidParm = false;
14514   for (ParmVarDecl *Param : Parameters) {
14515     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14516     // function declarator that is part of a function definition of
14517     // that function shall not have incomplete type.
14518     //
14519     // This is also C++ [dcl.fct]p6.
14520     if (!Param->isInvalidDecl() &&
14521         RequireCompleteType(Param->getLocation(), Param->getType(),
14522                             diag::err_typecheck_decl_incomplete_type)) {
14523       Param->setInvalidDecl();
14524       HasInvalidParm = true;
14525     }
14526 
14527     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14528     // declaration of each parameter shall include an identifier.
14529     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14530         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14531       // Diagnose this as an extension in C17 and earlier.
14532       if (!getLangOpts().C2x)
14533         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14534     }
14535 
14536     // C99 6.7.5.3p12:
14537     //   If the function declarator is not part of a definition of that
14538     //   function, parameters may have incomplete type and may use the [*]
14539     //   notation in their sequences of declarator specifiers to specify
14540     //   variable length array types.
14541     QualType PType = Param->getOriginalType();
14542     // FIXME: This diagnostic should point the '[*]' if source-location
14543     // information is added for it.
14544     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14545 
14546     // If the parameter is a c++ class type and it has to be destructed in the
14547     // callee function, declare the destructor so that it can be called by the
14548     // callee function. Do not perform any direct access check on the dtor here.
14549     if (!Param->isInvalidDecl()) {
14550       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14551         if (!ClassDecl->isInvalidDecl() &&
14552             !ClassDecl->hasIrrelevantDestructor() &&
14553             !ClassDecl->isDependentContext() &&
14554             ClassDecl->isParamDestroyedInCallee()) {
14555           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14556           MarkFunctionReferenced(Param->getLocation(), Destructor);
14557           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14558         }
14559       }
14560     }
14561 
14562     // Parameters with the pass_object_size attribute only need to be marked
14563     // constant at function definitions. Because we lack information about
14564     // whether we're on a declaration or definition when we're instantiating the
14565     // attribute, we need to check for constness here.
14566     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14567       if (!Param->getType().isConstQualified())
14568         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14569             << Attr->getSpelling() << 1;
14570 
14571     // Check for parameter names shadowing fields from the class.
14572     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14573       // The owning context for the parameter should be the function, but we
14574       // want to see if this function's declaration context is a record.
14575       DeclContext *DC = Param->getDeclContext();
14576       if (DC && DC->isFunctionOrMethod()) {
14577         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14578           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14579                                      RD, /*DeclIsField*/ false);
14580       }
14581     }
14582   }
14583 
14584   return HasInvalidParm;
14585 }
14586 
14587 Optional<std::pair<CharUnits, CharUnits>>
14588 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14589 
14590 /// Compute the alignment and offset of the base class object given the
14591 /// derived-to-base cast expression and the alignment and offset of the derived
14592 /// class object.
14593 static std::pair<CharUnits, CharUnits>
14594 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14595                                    CharUnits BaseAlignment, CharUnits Offset,
14596                                    ASTContext &Ctx) {
14597   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14598        ++PathI) {
14599     const CXXBaseSpecifier *Base = *PathI;
14600     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14601     if (Base->isVirtual()) {
14602       // The complete object may have a lower alignment than the non-virtual
14603       // alignment of the base, in which case the base may be misaligned. Choose
14604       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14605       // conservative lower bound of the complete object alignment.
14606       CharUnits NonVirtualAlignment =
14607           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14608       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14609       Offset = CharUnits::Zero();
14610     } else {
14611       const ASTRecordLayout &RL =
14612           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14613       Offset += RL.getBaseClassOffset(BaseDecl);
14614     }
14615     DerivedType = Base->getType();
14616   }
14617 
14618   return std::make_pair(BaseAlignment, Offset);
14619 }
14620 
14621 /// Compute the alignment and offset of a binary additive operator.
14622 static Optional<std::pair<CharUnits, CharUnits>>
14623 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14624                                      bool IsSub, ASTContext &Ctx) {
14625   QualType PointeeType = PtrE->getType()->getPointeeType();
14626 
14627   if (!PointeeType->isConstantSizeType())
14628     return llvm::None;
14629 
14630   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14631 
14632   if (!P)
14633     return llvm::None;
14634 
14635   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14636   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14637     CharUnits Offset = EltSize * IdxRes->getExtValue();
14638     if (IsSub)
14639       Offset = -Offset;
14640     return std::make_pair(P->first, P->second + Offset);
14641   }
14642 
14643   // If the integer expression isn't a constant expression, compute the lower
14644   // bound of the alignment using the alignment and offset of the pointer
14645   // expression and the element size.
14646   return std::make_pair(
14647       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14648       CharUnits::Zero());
14649 }
14650 
14651 /// This helper function takes an lvalue expression and returns the alignment of
14652 /// a VarDecl and a constant offset from the VarDecl.
14653 Optional<std::pair<CharUnits, CharUnits>>
14654 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14655   E = E->IgnoreParens();
14656   switch (E->getStmtClass()) {
14657   default:
14658     break;
14659   case Stmt::CStyleCastExprClass:
14660   case Stmt::CXXStaticCastExprClass:
14661   case Stmt::ImplicitCastExprClass: {
14662     auto *CE = cast<CastExpr>(E);
14663     const Expr *From = CE->getSubExpr();
14664     switch (CE->getCastKind()) {
14665     default:
14666       break;
14667     case CK_NoOp:
14668       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14669     case CK_UncheckedDerivedToBase:
14670     case CK_DerivedToBase: {
14671       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14672       if (!P)
14673         break;
14674       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14675                                                 P->second, Ctx);
14676     }
14677     }
14678     break;
14679   }
14680   case Stmt::ArraySubscriptExprClass: {
14681     auto *ASE = cast<ArraySubscriptExpr>(E);
14682     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14683                                                 false, Ctx);
14684   }
14685   case Stmt::DeclRefExprClass: {
14686     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14687       // FIXME: If VD is captured by copy or is an escaping __block variable,
14688       // use the alignment of VD's type.
14689       if (!VD->getType()->isReferenceType())
14690         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14691       if (VD->hasInit())
14692         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14693     }
14694     break;
14695   }
14696   case Stmt::MemberExprClass: {
14697     auto *ME = cast<MemberExpr>(E);
14698     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14699     if (!FD || FD->getType()->isReferenceType() ||
14700         FD->getParent()->isInvalidDecl())
14701       break;
14702     Optional<std::pair<CharUnits, CharUnits>> P;
14703     if (ME->isArrow())
14704       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14705     else
14706       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14707     if (!P)
14708       break;
14709     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14710     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14711     return std::make_pair(P->first,
14712                           P->second + CharUnits::fromQuantity(Offset));
14713   }
14714   case Stmt::UnaryOperatorClass: {
14715     auto *UO = cast<UnaryOperator>(E);
14716     switch (UO->getOpcode()) {
14717     default:
14718       break;
14719     case UO_Deref:
14720       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14721     }
14722     break;
14723   }
14724   case Stmt::BinaryOperatorClass: {
14725     auto *BO = cast<BinaryOperator>(E);
14726     auto Opcode = BO->getOpcode();
14727     switch (Opcode) {
14728     default:
14729       break;
14730     case BO_Comma:
14731       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14732     }
14733     break;
14734   }
14735   }
14736   return llvm::None;
14737 }
14738 
14739 /// This helper function takes a pointer expression and returns the alignment of
14740 /// a VarDecl and a constant offset from the VarDecl.
14741 Optional<std::pair<CharUnits, CharUnits>>
14742 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14743   E = E->IgnoreParens();
14744   switch (E->getStmtClass()) {
14745   default:
14746     break;
14747   case Stmt::CStyleCastExprClass:
14748   case Stmt::CXXStaticCastExprClass:
14749   case Stmt::ImplicitCastExprClass: {
14750     auto *CE = cast<CastExpr>(E);
14751     const Expr *From = CE->getSubExpr();
14752     switch (CE->getCastKind()) {
14753     default:
14754       break;
14755     case CK_NoOp:
14756       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14757     case CK_ArrayToPointerDecay:
14758       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14759     case CK_UncheckedDerivedToBase:
14760     case CK_DerivedToBase: {
14761       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14762       if (!P)
14763         break;
14764       return getDerivedToBaseAlignmentAndOffset(
14765           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14766     }
14767     }
14768     break;
14769   }
14770   case Stmt::CXXThisExprClass: {
14771     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14772     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14773     return std::make_pair(Alignment, CharUnits::Zero());
14774   }
14775   case Stmt::UnaryOperatorClass: {
14776     auto *UO = cast<UnaryOperator>(E);
14777     if (UO->getOpcode() == UO_AddrOf)
14778       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14779     break;
14780   }
14781   case Stmt::BinaryOperatorClass: {
14782     auto *BO = cast<BinaryOperator>(E);
14783     auto Opcode = BO->getOpcode();
14784     switch (Opcode) {
14785     default:
14786       break;
14787     case BO_Add:
14788     case BO_Sub: {
14789       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14790       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14791         std::swap(LHS, RHS);
14792       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14793                                                   Ctx);
14794     }
14795     case BO_Comma:
14796       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14797     }
14798     break;
14799   }
14800   }
14801   return llvm::None;
14802 }
14803 
14804 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14805   // See if we can compute the alignment of a VarDecl and an offset from it.
14806   Optional<std::pair<CharUnits, CharUnits>> P =
14807       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14808 
14809   if (P)
14810     return P->first.alignmentAtOffset(P->second);
14811 
14812   // If that failed, return the type's alignment.
14813   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14814 }
14815 
14816 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14817 /// pointer cast increases the alignment requirements.
14818 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14819   // This is actually a lot of work to potentially be doing on every
14820   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14821   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14822     return;
14823 
14824   // Ignore dependent types.
14825   if (T->isDependentType() || Op->getType()->isDependentType())
14826     return;
14827 
14828   // Require that the destination be a pointer type.
14829   const PointerType *DestPtr = T->getAs<PointerType>();
14830   if (!DestPtr) return;
14831 
14832   // If the destination has alignment 1, we're done.
14833   QualType DestPointee = DestPtr->getPointeeType();
14834   if (DestPointee->isIncompleteType()) return;
14835   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14836   if (DestAlign.isOne()) return;
14837 
14838   // Require that the source be a pointer type.
14839   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14840   if (!SrcPtr) return;
14841   QualType SrcPointee = SrcPtr->getPointeeType();
14842 
14843   // Explicitly allow casts from cv void*.  We already implicitly
14844   // allowed casts to cv void*, since they have alignment 1.
14845   // Also allow casts involving incomplete types, which implicitly
14846   // includes 'void'.
14847   if (SrcPointee->isIncompleteType()) return;
14848 
14849   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14850 
14851   if (SrcAlign >= DestAlign) return;
14852 
14853   Diag(TRange.getBegin(), diag::warn_cast_align)
14854     << Op->getType() << T
14855     << static_cast<unsigned>(SrcAlign.getQuantity())
14856     << static_cast<unsigned>(DestAlign.getQuantity())
14857     << TRange << Op->getSourceRange();
14858 }
14859 
14860 /// Check whether this array fits the idiom of a size-one tail padded
14861 /// array member of a struct.
14862 ///
14863 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14864 /// commonly used to emulate flexible arrays in C89 code.
14865 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14866                                     const NamedDecl *ND) {
14867   if (Size != 1 || !ND) return false;
14868 
14869   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14870   if (!FD) return false;
14871 
14872   // Don't consider sizes resulting from macro expansions or template argument
14873   // substitution to form C89 tail-padded arrays.
14874 
14875   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14876   while (TInfo) {
14877     TypeLoc TL = TInfo->getTypeLoc();
14878     // Look through typedefs.
14879     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14880       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14881       TInfo = TDL->getTypeSourceInfo();
14882       continue;
14883     }
14884     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14885       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14886       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14887         return false;
14888     }
14889     break;
14890   }
14891 
14892   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14893   if (!RD) return false;
14894   if (RD->isUnion()) return false;
14895   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14896     if (!CRD->isStandardLayout()) return false;
14897   }
14898 
14899   // See if this is the last field decl in the record.
14900   const Decl *D = FD;
14901   while ((D = D->getNextDeclInContext()))
14902     if (isa<FieldDecl>(D))
14903       return false;
14904   return true;
14905 }
14906 
14907 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14908                             const ArraySubscriptExpr *ASE,
14909                             bool AllowOnePastEnd, bool IndexNegated) {
14910   // Already diagnosed by the constant evaluator.
14911   if (isConstantEvaluated())
14912     return;
14913 
14914   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14915   if (IndexExpr->isValueDependent())
14916     return;
14917 
14918   const Type *EffectiveType =
14919       BaseExpr->getType()->getPointeeOrArrayElementType();
14920   BaseExpr = BaseExpr->IgnoreParenCasts();
14921   const ConstantArrayType *ArrayTy =
14922       Context.getAsConstantArrayType(BaseExpr->getType());
14923 
14924   const Type *BaseType =
14925       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14926   bool IsUnboundedArray = (BaseType == nullptr);
14927   if (EffectiveType->isDependentType() ||
14928       (!IsUnboundedArray && BaseType->isDependentType()))
14929     return;
14930 
14931   Expr::EvalResult Result;
14932   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14933     return;
14934 
14935   llvm::APSInt index = Result.Val.getInt();
14936   if (IndexNegated) {
14937     index.setIsUnsigned(false);
14938     index = -index;
14939   }
14940 
14941   const NamedDecl *ND = nullptr;
14942   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14943     ND = DRE->getDecl();
14944   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14945     ND = ME->getMemberDecl();
14946 
14947   if (IsUnboundedArray) {
14948     if (index.isUnsigned() || !index.isNegative()) {
14949       const auto &ASTC = getASTContext();
14950       unsigned AddrBits =
14951           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14952               EffectiveType->getCanonicalTypeInternal()));
14953       if (index.getBitWidth() < AddrBits)
14954         index = index.zext(AddrBits);
14955       Optional<CharUnits> ElemCharUnits =
14956           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14957       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14958       // pointer) bounds-checking isn't meaningful.
14959       if (!ElemCharUnits)
14960         return;
14961       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14962       // If index has more active bits than address space, we already know
14963       // we have a bounds violation to warn about.  Otherwise, compute
14964       // address of (index + 1)th element, and warn about bounds violation
14965       // only if that address exceeds address space.
14966       if (index.getActiveBits() <= AddrBits) {
14967         bool Overflow;
14968         llvm::APInt Product(index);
14969         Product += 1;
14970         Product = Product.umul_ov(ElemBytes, Overflow);
14971         if (!Overflow && Product.getActiveBits() <= AddrBits)
14972           return;
14973       }
14974 
14975       // Need to compute max possible elements in address space, since that
14976       // is included in diag message.
14977       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14978       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14979       MaxElems += 1;
14980       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14981       MaxElems = MaxElems.udiv(ElemBytes);
14982 
14983       unsigned DiagID =
14984           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14985               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14986 
14987       // Diag message shows element size in bits and in "bytes" (platform-
14988       // dependent CharUnits)
14989       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14990                           PDiag(DiagID)
14991                               << toString(index, 10, true) << AddrBits
14992                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14993                               << toString(ElemBytes, 10, false)
14994                               << toString(MaxElems, 10, false)
14995                               << (unsigned)MaxElems.getLimitedValue(~0U)
14996                               << IndexExpr->getSourceRange());
14997 
14998       if (!ND) {
14999         // Try harder to find a NamedDecl to point at in the note.
15000         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15001           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15002         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15003           ND = DRE->getDecl();
15004         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15005           ND = ME->getMemberDecl();
15006       }
15007 
15008       if (ND)
15009         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15010                             PDiag(diag::note_array_declared_here) << ND);
15011     }
15012     return;
15013   }
15014 
15015   if (index.isUnsigned() || !index.isNegative()) {
15016     // It is possible that the type of the base expression after
15017     // IgnoreParenCasts is incomplete, even though the type of the base
15018     // expression before IgnoreParenCasts is complete (see PR39746 for an
15019     // example). In this case we have no information about whether the array
15020     // access exceeds the array bounds. However we can still diagnose an array
15021     // access which precedes the array bounds.
15022     if (BaseType->isIncompleteType())
15023       return;
15024 
15025     llvm::APInt size = ArrayTy->getSize();
15026     if (!size.isStrictlyPositive())
15027       return;
15028 
15029     if (BaseType != EffectiveType) {
15030       // Make sure we're comparing apples to apples when comparing index to size
15031       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15032       uint64_t array_typesize = Context.getTypeSize(BaseType);
15033       // Handle ptrarith_typesize being zero, such as when casting to void*
15034       if (!ptrarith_typesize) ptrarith_typesize = 1;
15035       if (ptrarith_typesize != array_typesize) {
15036         // There's a cast to a different size type involved
15037         uint64_t ratio = array_typesize / ptrarith_typesize;
15038         // TODO: Be smarter about handling cases where array_typesize is not a
15039         // multiple of ptrarith_typesize
15040         if (ptrarith_typesize * ratio == array_typesize)
15041           size *= llvm::APInt(size.getBitWidth(), ratio);
15042       }
15043     }
15044 
15045     if (size.getBitWidth() > index.getBitWidth())
15046       index = index.zext(size.getBitWidth());
15047     else if (size.getBitWidth() < index.getBitWidth())
15048       size = size.zext(index.getBitWidth());
15049 
15050     // For array subscripting the index must be less than size, but for pointer
15051     // arithmetic also allow the index (offset) to be equal to size since
15052     // computing the next address after the end of the array is legal and
15053     // commonly done e.g. in C++ iterators and range-based for loops.
15054     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15055       return;
15056 
15057     // Also don't warn for arrays of size 1 which are members of some
15058     // structure. These are often used to approximate flexible arrays in C89
15059     // code.
15060     if (IsTailPaddedMemberArray(*this, size, ND))
15061       return;
15062 
15063     // Suppress the warning if the subscript expression (as identified by the
15064     // ']' location) and the index expression are both from macro expansions
15065     // within a system header.
15066     if (ASE) {
15067       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15068           ASE->getRBracketLoc());
15069       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15070         SourceLocation IndexLoc =
15071             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15072         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15073           return;
15074       }
15075     }
15076 
15077     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15078                           : diag::warn_ptr_arith_exceeds_bounds;
15079 
15080     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15081                         PDiag(DiagID) << toString(index, 10, true)
15082                                       << toString(size, 10, true)
15083                                       << (unsigned)size.getLimitedValue(~0U)
15084                                       << IndexExpr->getSourceRange());
15085   } else {
15086     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15087     if (!ASE) {
15088       DiagID = diag::warn_ptr_arith_precedes_bounds;
15089       if (index.isNegative()) index = -index;
15090     }
15091 
15092     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15093                         PDiag(DiagID) << toString(index, 10, true)
15094                                       << IndexExpr->getSourceRange());
15095   }
15096 
15097   if (!ND) {
15098     // Try harder to find a NamedDecl to point at in the note.
15099     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15100       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15101     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15102       ND = DRE->getDecl();
15103     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15104       ND = ME->getMemberDecl();
15105   }
15106 
15107   if (ND)
15108     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15109                         PDiag(diag::note_array_declared_here) << ND);
15110 }
15111 
15112 void Sema::CheckArrayAccess(const Expr *expr) {
15113   int AllowOnePastEnd = 0;
15114   while (expr) {
15115     expr = expr->IgnoreParenImpCasts();
15116     switch (expr->getStmtClass()) {
15117       case Stmt::ArraySubscriptExprClass: {
15118         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15119         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15120                          AllowOnePastEnd > 0);
15121         expr = ASE->getBase();
15122         break;
15123       }
15124       case Stmt::MemberExprClass: {
15125         expr = cast<MemberExpr>(expr)->getBase();
15126         break;
15127       }
15128       case Stmt::OMPArraySectionExprClass: {
15129         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15130         if (ASE->getLowerBound())
15131           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15132                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15133         return;
15134       }
15135       case Stmt::UnaryOperatorClass: {
15136         // Only unwrap the * and & unary operators
15137         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15138         expr = UO->getSubExpr();
15139         switch (UO->getOpcode()) {
15140           case UO_AddrOf:
15141             AllowOnePastEnd++;
15142             break;
15143           case UO_Deref:
15144             AllowOnePastEnd--;
15145             break;
15146           default:
15147             return;
15148         }
15149         break;
15150       }
15151       case Stmt::ConditionalOperatorClass: {
15152         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15153         if (const Expr *lhs = cond->getLHS())
15154           CheckArrayAccess(lhs);
15155         if (const Expr *rhs = cond->getRHS())
15156           CheckArrayAccess(rhs);
15157         return;
15158       }
15159       case Stmt::CXXOperatorCallExprClass: {
15160         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15161         for (const auto *Arg : OCE->arguments())
15162           CheckArrayAccess(Arg);
15163         return;
15164       }
15165       default:
15166         return;
15167     }
15168   }
15169 }
15170 
15171 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15172 
15173 namespace {
15174 
15175 struct RetainCycleOwner {
15176   VarDecl *Variable = nullptr;
15177   SourceRange Range;
15178   SourceLocation Loc;
15179   bool Indirect = false;
15180 
15181   RetainCycleOwner() = default;
15182 
15183   void setLocsFrom(Expr *e) {
15184     Loc = e->getExprLoc();
15185     Range = e->getSourceRange();
15186   }
15187 };
15188 
15189 } // namespace
15190 
15191 /// Consider whether capturing the given variable can possibly lead to
15192 /// a retain cycle.
15193 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15194   // In ARC, it's captured strongly iff the variable has __strong
15195   // lifetime.  In MRR, it's captured strongly if the variable is
15196   // __block and has an appropriate type.
15197   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15198     return false;
15199 
15200   owner.Variable = var;
15201   if (ref)
15202     owner.setLocsFrom(ref);
15203   return true;
15204 }
15205 
15206 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15207   while (true) {
15208     e = e->IgnoreParens();
15209     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15210       switch (cast->getCastKind()) {
15211       case CK_BitCast:
15212       case CK_LValueBitCast:
15213       case CK_LValueToRValue:
15214       case CK_ARCReclaimReturnedObject:
15215         e = cast->getSubExpr();
15216         continue;
15217 
15218       default:
15219         return false;
15220       }
15221     }
15222 
15223     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15224       ObjCIvarDecl *ivar = ref->getDecl();
15225       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15226         return false;
15227 
15228       // Try to find a retain cycle in the base.
15229       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15230         return false;
15231 
15232       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15233       owner.Indirect = true;
15234       return true;
15235     }
15236 
15237     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15238       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15239       if (!var) return false;
15240       return considerVariable(var, ref, owner);
15241     }
15242 
15243     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15244       if (member->isArrow()) return false;
15245 
15246       // Don't count this as an indirect ownership.
15247       e = member->getBase();
15248       continue;
15249     }
15250 
15251     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15252       // Only pay attention to pseudo-objects on property references.
15253       ObjCPropertyRefExpr *pre
15254         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15255                                               ->IgnoreParens());
15256       if (!pre) return false;
15257       if (pre->isImplicitProperty()) return false;
15258       ObjCPropertyDecl *property = pre->getExplicitProperty();
15259       if (!property->isRetaining() &&
15260           !(property->getPropertyIvarDecl() &&
15261             property->getPropertyIvarDecl()->getType()
15262               .getObjCLifetime() == Qualifiers::OCL_Strong))
15263           return false;
15264 
15265       owner.Indirect = true;
15266       if (pre->isSuperReceiver()) {
15267         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15268         if (!owner.Variable)
15269           return false;
15270         owner.Loc = pre->getLocation();
15271         owner.Range = pre->getSourceRange();
15272         return true;
15273       }
15274       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15275                               ->getSourceExpr());
15276       continue;
15277     }
15278 
15279     // Array ivars?
15280 
15281     return false;
15282   }
15283 }
15284 
15285 namespace {
15286 
15287   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15288     ASTContext &Context;
15289     VarDecl *Variable;
15290     Expr *Capturer = nullptr;
15291     bool VarWillBeReased = false;
15292 
15293     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15294         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15295           Context(Context), Variable(variable) {}
15296 
15297     void VisitDeclRefExpr(DeclRefExpr *ref) {
15298       if (ref->getDecl() == Variable && !Capturer)
15299         Capturer = ref;
15300     }
15301 
15302     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15303       if (Capturer) return;
15304       Visit(ref->getBase());
15305       if (Capturer && ref->isFreeIvar())
15306         Capturer = ref;
15307     }
15308 
15309     void VisitBlockExpr(BlockExpr *block) {
15310       // Look inside nested blocks
15311       if (block->getBlockDecl()->capturesVariable(Variable))
15312         Visit(block->getBlockDecl()->getBody());
15313     }
15314 
15315     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15316       if (Capturer) return;
15317       if (OVE->getSourceExpr())
15318         Visit(OVE->getSourceExpr());
15319     }
15320 
15321     void VisitBinaryOperator(BinaryOperator *BinOp) {
15322       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15323         return;
15324       Expr *LHS = BinOp->getLHS();
15325       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15326         if (DRE->getDecl() != Variable)
15327           return;
15328         if (Expr *RHS = BinOp->getRHS()) {
15329           RHS = RHS->IgnoreParenCasts();
15330           Optional<llvm::APSInt> Value;
15331           VarWillBeReased =
15332               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15333                *Value == 0);
15334         }
15335       }
15336     }
15337   };
15338 
15339 } // namespace
15340 
15341 /// Check whether the given argument is a block which captures a
15342 /// variable.
15343 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15344   assert(owner.Variable && owner.Loc.isValid());
15345 
15346   e = e->IgnoreParenCasts();
15347 
15348   // Look through [^{...} copy] and Block_copy(^{...}).
15349   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15350     Selector Cmd = ME->getSelector();
15351     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15352       e = ME->getInstanceReceiver();
15353       if (!e)
15354         return nullptr;
15355       e = e->IgnoreParenCasts();
15356     }
15357   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15358     if (CE->getNumArgs() == 1) {
15359       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15360       if (Fn) {
15361         const IdentifierInfo *FnI = Fn->getIdentifier();
15362         if (FnI && FnI->isStr("_Block_copy")) {
15363           e = CE->getArg(0)->IgnoreParenCasts();
15364         }
15365       }
15366     }
15367   }
15368 
15369   BlockExpr *block = dyn_cast<BlockExpr>(e);
15370   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15371     return nullptr;
15372 
15373   FindCaptureVisitor visitor(S.Context, owner.Variable);
15374   visitor.Visit(block->getBlockDecl()->getBody());
15375   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15376 }
15377 
15378 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15379                                 RetainCycleOwner &owner) {
15380   assert(capturer);
15381   assert(owner.Variable && owner.Loc.isValid());
15382 
15383   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15384     << owner.Variable << capturer->getSourceRange();
15385   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15386     << owner.Indirect << owner.Range;
15387 }
15388 
15389 /// Check for a keyword selector that starts with the word 'add' or
15390 /// 'set'.
15391 static bool isSetterLikeSelector(Selector sel) {
15392   if (sel.isUnarySelector()) return false;
15393 
15394   StringRef str = sel.getNameForSlot(0);
15395   while (!str.empty() && str.front() == '_') str = str.substr(1);
15396   if (str.startswith("set"))
15397     str = str.substr(3);
15398   else if (str.startswith("add")) {
15399     // Specially allow 'addOperationWithBlock:'.
15400     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15401       return false;
15402     str = str.substr(3);
15403   }
15404   else
15405     return false;
15406 
15407   if (str.empty()) return true;
15408   return !isLowercase(str.front());
15409 }
15410 
15411 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15412                                                     ObjCMessageExpr *Message) {
15413   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15414                                                 Message->getReceiverInterface(),
15415                                                 NSAPI::ClassId_NSMutableArray);
15416   if (!IsMutableArray) {
15417     return None;
15418   }
15419 
15420   Selector Sel = Message->getSelector();
15421 
15422   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15423     S.NSAPIObj->getNSArrayMethodKind(Sel);
15424   if (!MKOpt) {
15425     return None;
15426   }
15427 
15428   NSAPI::NSArrayMethodKind MK = *MKOpt;
15429 
15430   switch (MK) {
15431     case NSAPI::NSMutableArr_addObject:
15432     case NSAPI::NSMutableArr_insertObjectAtIndex:
15433     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15434       return 0;
15435     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15436       return 1;
15437 
15438     default:
15439       return None;
15440   }
15441 
15442   return None;
15443 }
15444 
15445 static
15446 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15447                                                   ObjCMessageExpr *Message) {
15448   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15449                                             Message->getReceiverInterface(),
15450                                             NSAPI::ClassId_NSMutableDictionary);
15451   if (!IsMutableDictionary) {
15452     return None;
15453   }
15454 
15455   Selector Sel = Message->getSelector();
15456 
15457   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15458     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15459   if (!MKOpt) {
15460     return None;
15461   }
15462 
15463   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15464 
15465   switch (MK) {
15466     case NSAPI::NSMutableDict_setObjectForKey:
15467     case NSAPI::NSMutableDict_setValueForKey:
15468     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15469       return 0;
15470 
15471     default:
15472       return None;
15473   }
15474 
15475   return None;
15476 }
15477 
15478 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15479   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15480                                                 Message->getReceiverInterface(),
15481                                                 NSAPI::ClassId_NSMutableSet);
15482 
15483   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15484                                             Message->getReceiverInterface(),
15485                                             NSAPI::ClassId_NSMutableOrderedSet);
15486   if (!IsMutableSet && !IsMutableOrderedSet) {
15487     return None;
15488   }
15489 
15490   Selector Sel = Message->getSelector();
15491 
15492   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15493   if (!MKOpt) {
15494     return None;
15495   }
15496 
15497   NSAPI::NSSetMethodKind MK = *MKOpt;
15498 
15499   switch (MK) {
15500     case NSAPI::NSMutableSet_addObject:
15501     case NSAPI::NSOrderedSet_setObjectAtIndex:
15502     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15503     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15504       return 0;
15505     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15506       return 1;
15507   }
15508 
15509   return None;
15510 }
15511 
15512 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15513   if (!Message->isInstanceMessage()) {
15514     return;
15515   }
15516 
15517   Optional<int> ArgOpt;
15518 
15519   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15520       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15521       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15522     return;
15523   }
15524 
15525   int ArgIndex = *ArgOpt;
15526 
15527   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15528   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15529     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15530   }
15531 
15532   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15533     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15534       if (ArgRE->isObjCSelfExpr()) {
15535         Diag(Message->getSourceRange().getBegin(),
15536              diag::warn_objc_circular_container)
15537           << ArgRE->getDecl() << StringRef("'super'");
15538       }
15539     }
15540   } else {
15541     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15542 
15543     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15544       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15545     }
15546 
15547     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15548       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15549         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15550           ValueDecl *Decl = ReceiverRE->getDecl();
15551           Diag(Message->getSourceRange().getBegin(),
15552                diag::warn_objc_circular_container)
15553             << Decl << Decl;
15554           if (!ArgRE->isObjCSelfExpr()) {
15555             Diag(Decl->getLocation(),
15556                  diag::note_objc_circular_container_declared_here)
15557               << Decl;
15558           }
15559         }
15560       }
15561     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15562       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15563         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15564           ObjCIvarDecl *Decl = IvarRE->getDecl();
15565           Diag(Message->getSourceRange().getBegin(),
15566                diag::warn_objc_circular_container)
15567             << Decl << Decl;
15568           Diag(Decl->getLocation(),
15569                diag::note_objc_circular_container_declared_here)
15570             << Decl;
15571         }
15572       }
15573     }
15574   }
15575 }
15576 
15577 /// Check a message send to see if it's likely to cause a retain cycle.
15578 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15579   // Only check instance methods whose selector looks like a setter.
15580   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15581     return;
15582 
15583   // Try to find a variable that the receiver is strongly owned by.
15584   RetainCycleOwner owner;
15585   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15586     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15587       return;
15588   } else {
15589     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15590     owner.Variable = getCurMethodDecl()->getSelfDecl();
15591     owner.Loc = msg->getSuperLoc();
15592     owner.Range = msg->getSuperLoc();
15593   }
15594 
15595   // Check whether the receiver is captured by any of the arguments.
15596   const ObjCMethodDecl *MD = msg->getMethodDecl();
15597   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15598     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15599       // noescape blocks should not be retained by the method.
15600       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15601         continue;
15602       return diagnoseRetainCycle(*this, capturer, owner);
15603     }
15604   }
15605 }
15606 
15607 /// Check a property assign to see if it's likely to cause a retain cycle.
15608 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15609   RetainCycleOwner owner;
15610   if (!findRetainCycleOwner(*this, receiver, owner))
15611     return;
15612 
15613   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15614     diagnoseRetainCycle(*this, capturer, owner);
15615 }
15616 
15617 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15618   RetainCycleOwner Owner;
15619   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15620     return;
15621 
15622   // Because we don't have an expression for the variable, we have to set the
15623   // location explicitly here.
15624   Owner.Loc = Var->getLocation();
15625   Owner.Range = Var->getSourceRange();
15626 
15627   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15628     diagnoseRetainCycle(*this, Capturer, Owner);
15629 }
15630 
15631 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15632                                      Expr *RHS, bool isProperty) {
15633   // Check if RHS is an Objective-C object literal, which also can get
15634   // immediately zapped in a weak reference.  Note that we explicitly
15635   // allow ObjCStringLiterals, since those are designed to never really die.
15636   RHS = RHS->IgnoreParenImpCasts();
15637 
15638   // This enum needs to match with the 'select' in
15639   // warn_objc_arc_literal_assign (off-by-1).
15640   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15641   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15642     return false;
15643 
15644   S.Diag(Loc, diag::warn_arc_literal_assign)
15645     << (unsigned) Kind
15646     << (isProperty ? 0 : 1)
15647     << RHS->getSourceRange();
15648 
15649   return true;
15650 }
15651 
15652 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15653                                     Qualifiers::ObjCLifetime LT,
15654                                     Expr *RHS, bool isProperty) {
15655   // Strip off any implicit cast added to get to the one ARC-specific.
15656   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15657     if (cast->getCastKind() == CK_ARCConsumeObject) {
15658       S.Diag(Loc, diag::warn_arc_retained_assign)
15659         << (LT == Qualifiers::OCL_ExplicitNone)
15660         << (isProperty ? 0 : 1)
15661         << RHS->getSourceRange();
15662       return true;
15663     }
15664     RHS = cast->getSubExpr();
15665   }
15666 
15667   if (LT == Qualifiers::OCL_Weak &&
15668       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15669     return true;
15670 
15671   return false;
15672 }
15673 
15674 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15675                               QualType LHS, Expr *RHS) {
15676   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15677 
15678   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15679     return false;
15680 
15681   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15682     return true;
15683 
15684   return false;
15685 }
15686 
15687 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15688                               Expr *LHS, Expr *RHS) {
15689   QualType LHSType;
15690   // PropertyRef on LHS type need be directly obtained from
15691   // its declaration as it has a PseudoType.
15692   ObjCPropertyRefExpr *PRE
15693     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15694   if (PRE && !PRE->isImplicitProperty()) {
15695     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15696     if (PD)
15697       LHSType = PD->getType();
15698   }
15699 
15700   if (LHSType.isNull())
15701     LHSType = LHS->getType();
15702 
15703   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15704 
15705   if (LT == Qualifiers::OCL_Weak) {
15706     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15707       getCurFunction()->markSafeWeakUse(LHS);
15708   }
15709 
15710   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15711     return;
15712 
15713   // FIXME. Check for other life times.
15714   if (LT != Qualifiers::OCL_None)
15715     return;
15716 
15717   if (PRE) {
15718     if (PRE->isImplicitProperty())
15719       return;
15720     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15721     if (!PD)
15722       return;
15723 
15724     unsigned Attributes = PD->getPropertyAttributes();
15725     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15726       // when 'assign' attribute was not explicitly specified
15727       // by user, ignore it and rely on property type itself
15728       // for lifetime info.
15729       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15730       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15731           LHSType->isObjCRetainableType())
15732         return;
15733 
15734       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15735         if (cast->getCastKind() == CK_ARCConsumeObject) {
15736           Diag(Loc, diag::warn_arc_retained_property_assign)
15737           << RHS->getSourceRange();
15738           return;
15739         }
15740         RHS = cast->getSubExpr();
15741       }
15742     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15743       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15744         return;
15745     }
15746   }
15747 }
15748 
15749 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15750 
15751 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15752                                         SourceLocation StmtLoc,
15753                                         const NullStmt *Body) {
15754   // Do not warn if the body is a macro that expands to nothing, e.g:
15755   //
15756   // #define CALL(x)
15757   // if (condition)
15758   //   CALL(0);
15759   if (Body->hasLeadingEmptyMacro())
15760     return false;
15761 
15762   // Get line numbers of statement and body.
15763   bool StmtLineInvalid;
15764   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15765                                                       &StmtLineInvalid);
15766   if (StmtLineInvalid)
15767     return false;
15768 
15769   bool BodyLineInvalid;
15770   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15771                                                       &BodyLineInvalid);
15772   if (BodyLineInvalid)
15773     return false;
15774 
15775   // Warn if null statement and body are on the same line.
15776   if (StmtLine != BodyLine)
15777     return false;
15778 
15779   return true;
15780 }
15781 
15782 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15783                                  const Stmt *Body,
15784                                  unsigned DiagID) {
15785   // Since this is a syntactic check, don't emit diagnostic for template
15786   // instantiations, this just adds noise.
15787   if (CurrentInstantiationScope)
15788     return;
15789 
15790   // The body should be a null statement.
15791   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15792   if (!NBody)
15793     return;
15794 
15795   // Do the usual checks.
15796   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15797     return;
15798 
15799   Diag(NBody->getSemiLoc(), DiagID);
15800   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15801 }
15802 
15803 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15804                                  const Stmt *PossibleBody) {
15805   assert(!CurrentInstantiationScope); // Ensured by caller
15806 
15807   SourceLocation StmtLoc;
15808   const Stmt *Body;
15809   unsigned DiagID;
15810   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15811     StmtLoc = FS->getRParenLoc();
15812     Body = FS->getBody();
15813     DiagID = diag::warn_empty_for_body;
15814   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15815     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15816     Body = WS->getBody();
15817     DiagID = diag::warn_empty_while_body;
15818   } else
15819     return; // Neither `for' nor `while'.
15820 
15821   // The body should be a null statement.
15822   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15823   if (!NBody)
15824     return;
15825 
15826   // Skip expensive checks if diagnostic is disabled.
15827   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15828     return;
15829 
15830   // Do the usual checks.
15831   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15832     return;
15833 
15834   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15835   // noise level low, emit diagnostics only if for/while is followed by a
15836   // CompoundStmt, e.g.:
15837   //    for (int i = 0; i < n; i++);
15838   //    {
15839   //      a(i);
15840   //    }
15841   // or if for/while is followed by a statement with more indentation
15842   // than for/while itself:
15843   //    for (int i = 0; i < n; i++);
15844   //      a(i);
15845   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15846   if (!ProbableTypo) {
15847     bool BodyColInvalid;
15848     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15849         PossibleBody->getBeginLoc(), &BodyColInvalid);
15850     if (BodyColInvalid)
15851       return;
15852 
15853     bool StmtColInvalid;
15854     unsigned StmtCol =
15855         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15856     if (StmtColInvalid)
15857       return;
15858 
15859     if (BodyCol > StmtCol)
15860       ProbableTypo = true;
15861   }
15862 
15863   if (ProbableTypo) {
15864     Diag(NBody->getSemiLoc(), DiagID);
15865     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15866   }
15867 }
15868 
15869 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15870 
15871 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15872 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15873                              SourceLocation OpLoc) {
15874   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15875     return;
15876 
15877   if (inTemplateInstantiation())
15878     return;
15879 
15880   // Strip parens and casts away.
15881   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15882   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15883 
15884   // Check for a call expression
15885   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15886   if (!CE || CE->getNumArgs() != 1)
15887     return;
15888 
15889   // Check for a call to std::move
15890   if (!CE->isCallToStdMove())
15891     return;
15892 
15893   // Get argument from std::move
15894   RHSExpr = CE->getArg(0);
15895 
15896   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15897   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15898 
15899   // Two DeclRefExpr's, check that the decls are the same.
15900   if (LHSDeclRef && RHSDeclRef) {
15901     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15902       return;
15903     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15904         RHSDeclRef->getDecl()->getCanonicalDecl())
15905       return;
15906 
15907     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15908                                         << LHSExpr->getSourceRange()
15909                                         << RHSExpr->getSourceRange();
15910     return;
15911   }
15912 
15913   // Member variables require a different approach to check for self moves.
15914   // MemberExpr's are the same if every nested MemberExpr refers to the same
15915   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15916   // the base Expr's are CXXThisExpr's.
15917   const Expr *LHSBase = LHSExpr;
15918   const Expr *RHSBase = RHSExpr;
15919   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15920   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15921   if (!LHSME || !RHSME)
15922     return;
15923 
15924   while (LHSME && RHSME) {
15925     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15926         RHSME->getMemberDecl()->getCanonicalDecl())
15927       return;
15928 
15929     LHSBase = LHSME->getBase();
15930     RHSBase = RHSME->getBase();
15931     LHSME = dyn_cast<MemberExpr>(LHSBase);
15932     RHSME = dyn_cast<MemberExpr>(RHSBase);
15933   }
15934 
15935   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15936   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15937   if (LHSDeclRef && RHSDeclRef) {
15938     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15939       return;
15940     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15941         RHSDeclRef->getDecl()->getCanonicalDecl())
15942       return;
15943 
15944     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15945                                         << LHSExpr->getSourceRange()
15946                                         << RHSExpr->getSourceRange();
15947     return;
15948   }
15949 
15950   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15951     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15952                                         << LHSExpr->getSourceRange()
15953                                         << RHSExpr->getSourceRange();
15954 }
15955 
15956 //===--- Layout compatibility ----------------------------------------------//
15957 
15958 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15959 
15960 /// Check if two enumeration types are layout-compatible.
15961 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15962   // C++11 [dcl.enum] p8:
15963   // Two enumeration types are layout-compatible if they have the same
15964   // underlying type.
15965   return ED1->isComplete() && ED2->isComplete() &&
15966          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15967 }
15968 
15969 /// Check if two fields are layout-compatible.
15970 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15971                                FieldDecl *Field2) {
15972   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15973     return false;
15974 
15975   if (Field1->isBitField() != Field2->isBitField())
15976     return false;
15977 
15978   if (Field1->isBitField()) {
15979     // Make sure that the bit-fields are the same length.
15980     unsigned Bits1 = Field1->getBitWidthValue(C);
15981     unsigned Bits2 = Field2->getBitWidthValue(C);
15982 
15983     if (Bits1 != Bits2)
15984       return false;
15985   }
15986 
15987   return true;
15988 }
15989 
15990 /// Check if two standard-layout structs are layout-compatible.
15991 /// (C++11 [class.mem] p17)
15992 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15993                                      RecordDecl *RD2) {
15994   // If both records are C++ classes, check that base classes match.
15995   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15996     // If one of records is a CXXRecordDecl we are in C++ mode,
15997     // thus the other one is a CXXRecordDecl, too.
15998     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15999     // Check number of base classes.
16000     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16001       return false;
16002 
16003     // Check the base classes.
16004     for (CXXRecordDecl::base_class_const_iterator
16005                Base1 = D1CXX->bases_begin(),
16006            BaseEnd1 = D1CXX->bases_end(),
16007               Base2 = D2CXX->bases_begin();
16008          Base1 != BaseEnd1;
16009          ++Base1, ++Base2) {
16010       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16011         return false;
16012     }
16013   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16014     // If only RD2 is a C++ class, it should have zero base classes.
16015     if (D2CXX->getNumBases() > 0)
16016       return false;
16017   }
16018 
16019   // Check the fields.
16020   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16021                              Field2End = RD2->field_end(),
16022                              Field1 = RD1->field_begin(),
16023                              Field1End = RD1->field_end();
16024   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16025     if (!isLayoutCompatible(C, *Field1, *Field2))
16026       return false;
16027   }
16028   if (Field1 != Field1End || Field2 != Field2End)
16029     return false;
16030 
16031   return true;
16032 }
16033 
16034 /// Check if two standard-layout unions are layout-compatible.
16035 /// (C++11 [class.mem] p18)
16036 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16037                                     RecordDecl *RD2) {
16038   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16039   for (auto *Field2 : RD2->fields())
16040     UnmatchedFields.insert(Field2);
16041 
16042   for (auto *Field1 : RD1->fields()) {
16043     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16044         I = UnmatchedFields.begin(),
16045         E = UnmatchedFields.end();
16046 
16047     for ( ; I != E; ++I) {
16048       if (isLayoutCompatible(C, Field1, *I)) {
16049         bool Result = UnmatchedFields.erase(*I);
16050         (void) Result;
16051         assert(Result);
16052         break;
16053       }
16054     }
16055     if (I == E)
16056       return false;
16057   }
16058 
16059   return UnmatchedFields.empty();
16060 }
16061 
16062 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16063                                RecordDecl *RD2) {
16064   if (RD1->isUnion() != RD2->isUnion())
16065     return false;
16066 
16067   if (RD1->isUnion())
16068     return isLayoutCompatibleUnion(C, RD1, RD2);
16069   else
16070     return isLayoutCompatibleStruct(C, RD1, RD2);
16071 }
16072 
16073 /// Check if two types are layout-compatible in C++11 sense.
16074 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16075   if (T1.isNull() || T2.isNull())
16076     return false;
16077 
16078   // C++11 [basic.types] p11:
16079   // If two types T1 and T2 are the same type, then T1 and T2 are
16080   // layout-compatible types.
16081   if (C.hasSameType(T1, T2))
16082     return true;
16083 
16084   T1 = T1.getCanonicalType().getUnqualifiedType();
16085   T2 = T2.getCanonicalType().getUnqualifiedType();
16086 
16087   const Type::TypeClass TC1 = T1->getTypeClass();
16088   const Type::TypeClass TC2 = T2->getTypeClass();
16089 
16090   if (TC1 != TC2)
16091     return false;
16092 
16093   if (TC1 == Type::Enum) {
16094     return isLayoutCompatible(C,
16095                               cast<EnumType>(T1)->getDecl(),
16096                               cast<EnumType>(T2)->getDecl());
16097   } else if (TC1 == Type::Record) {
16098     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16099       return false;
16100 
16101     return isLayoutCompatible(C,
16102                               cast<RecordType>(T1)->getDecl(),
16103                               cast<RecordType>(T2)->getDecl());
16104   }
16105 
16106   return false;
16107 }
16108 
16109 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16110 
16111 /// Given a type tag expression find the type tag itself.
16112 ///
16113 /// \param TypeExpr Type tag expression, as it appears in user's code.
16114 ///
16115 /// \param VD Declaration of an identifier that appears in a type tag.
16116 ///
16117 /// \param MagicValue Type tag magic value.
16118 ///
16119 /// \param isConstantEvaluated whether the evalaution should be performed in
16120 
16121 /// constant context.
16122 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16123                             const ValueDecl **VD, uint64_t *MagicValue,
16124                             bool isConstantEvaluated) {
16125   while(true) {
16126     if (!TypeExpr)
16127       return false;
16128 
16129     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16130 
16131     switch (TypeExpr->getStmtClass()) {
16132     case Stmt::UnaryOperatorClass: {
16133       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16134       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16135         TypeExpr = UO->getSubExpr();
16136         continue;
16137       }
16138       return false;
16139     }
16140 
16141     case Stmt::DeclRefExprClass: {
16142       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16143       *VD = DRE->getDecl();
16144       return true;
16145     }
16146 
16147     case Stmt::IntegerLiteralClass: {
16148       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16149       llvm::APInt MagicValueAPInt = IL->getValue();
16150       if (MagicValueAPInt.getActiveBits() <= 64) {
16151         *MagicValue = MagicValueAPInt.getZExtValue();
16152         return true;
16153       } else
16154         return false;
16155     }
16156 
16157     case Stmt::BinaryConditionalOperatorClass:
16158     case Stmt::ConditionalOperatorClass: {
16159       const AbstractConditionalOperator *ACO =
16160           cast<AbstractConditionalOperator>(TypeExpr);
16161       bool Result;
16162       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16163                                                      isConstantEvaluated)) {
16164         if (Result)
16165           TypeExpr = ACO->getTrueExpr();
16166         else
16167           TypeExpr = ACO->getFalseExpr();
16168         continue;
16169       }
16170       return false;
16171     }
16172 
16173     case Stmt::BinaryOperatorClass: {
16174       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16175       if (BO->getOpcode() == BO_Comma) {
16176         TypeExpr = BO->getRHS();
16177         continue;
16178       }
16179       return false;
16180     }
16181 
16182     default:
16183       return false;
16184     }
16185   }
16186 }
16187 
16188 /// Retrieve the C type corresponding to type tag TypeExpr.
16189 ///
16190 /// \param TypeExpr Expression that specifies a type tag.
16191 ///
16192 /// \param MagicValues Registered magic values.
16193 ///
16194 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16195 ///        kind.
16196 ///
16197 /// \param TypeInfo Information about the corresponding C type.
16198 ///
16199 /// \param isConstantEvaluated whether the evalaution should be performed in
16200 /// constant context.
16201 ///
16202 /// \returns true if the corresponding C type was found.
16203 static bool GetMatchingCType(
16204     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16205     const ASTContext &Ctx,
16206     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16207         *MagicValues,
16208     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16209     bool isConstantEvaluated) {
16210   FoundWrongKind = false;
16211 
16212   // Variable declaration that has type_tag_for_datatype attribute.
16213   const ValueDecl *VD = nullptr;
16214 
16215   uint64_t MagicValue;
16216 
16217   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16218     return false;
16219 
16220   if (VD) {
16221     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16222       if (I->getArgumentKind() != ArgumentKind) {
16223         FoundWrongKind = true;
16224         return false;
16225       }
16226       TypeInfo.Type = I->getMatchingCType();
16227       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16228       TypeInfo.MustBeNull = I->getMustBeNull();
16229       return true;
16230     }
16231     return false;
16232   }
16233 
16234   if (!MagicValues)
16235     return false;
16236 
16237   llvm::DenseMap<Sema::TypeTagMagicValue,
16238                  Sema::TypeTagData>::const_iterator I =
16239       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16240   if (I == MagicValues->end())
16241     return false;
16242 
16243   TypeInfo = I->second;
16244   return true;
16245 }
16246 
16247 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16248                                       uint64_t MagicValue, QualType Type,
16249                                       bool LayoutCompatible,
16250                                       bool MustBeNull) {
16251   if (!TypeTagForDatatypeMagicValues)
16252     TypeTagForDatatypeMagicValues.reset(
16253         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16254 
16255   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16256   (*TypeTagForDatatypeMagicValues)[Magic] =
16257       TypeTagData(Type, LayoutCompatible, MustBeNull);
16258 }
16259 
16260 static bool IsSameCharType(QualType T1, QualType T2) {
16261   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16262   if (!BT1)
16263     return false;
16264 
16265   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16266   if (!BT2)
16267     return false;
16268 
16269   BuiltinType::Kind T1Kind = BT1->getKind();
16270   BuiltinType::Kind T2Kind = BT2->getKind();
16271 
16272   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16273          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16274          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16275          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16276 }
16277 
16278 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16279                                     const ArrayRef<const Expr *> ExprArgs,
16280                                     SourceLocation CallSiteLoc) {
16281   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16282   bool IsPointerAttr = Attr->getIsPointer();
16283 
16284   // Retrieve the argument representing the 'type_tag'.
16285   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16286   if (TypeTagIdxAST >= ExprArgs.size()) {
16287     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16288         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16289     return;
16290   }
16291   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16292   bool FoundWrongKind;
16293   TypeTagData TypeInfo;
16294   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16295                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16296                         TypeInfo, isConstantEvaluated())) {
16297     if (FoundWrongKind)
16298       Diag(TypeTagExpr->getExprLoc(),
16299            diag::warn_type_tag_for_datatype_wrong_kind)
16300         << TypeTagExpr->getSourceRange();
16301     return;
16302   }
16303 
16304   // Retrieve the argument representing the 'arg_idx'.
16305   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16306   if (ArgumentIdxAST >= ExprArgs.size()) {
16307     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16308         << 1 << Attr->getArgumentIdx().getSourceIndex();
16309     return;
16310   }
16311   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16312   if (IsPointerAttr) {
16313     // Skip implicit cast of pointer to `void *' (as a function argument).
16314     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16315       if (ICE->getType()->isVoidPointerType() &&
16316           ICE->getCastKind() == CK_BitCast)
16317         ArgumentExpr = ICE->getSubExpr();
16318   }
16319   QualType ArgumentType = ArgumentExpr->getType();
16320 
16321   // Passing a `void*' pointer shouldn't trigger a warning.
16322   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16323     return;
16324 
16325   if (TypeInfo.MustBeNull) {
16326     // Type tag with matching void type requires a null pointer.
16327     if (!ArgumentExpr->isNullPointerConstant(Context,
16328                                              Expr::NPC_ValueDependentIsNotNull)) {
16329       Diag(ArgumentExpr->getExprLoc(),
16330            diag::warn_type_safety_null_pointer_required)
16331           << ArgumentKind->getName()
16332           << ArgumentExpr->getSourceRange()
16333           << TypeTagExpr->getSourceRange();
16334     }
16335     return;
16336   }
16337 
16338   QualType RequiredType = TypeInfo.Type;
16339   if (IsPointerAttr)
16340     RequiredType = Context.getPointerType(RequiredType);
16341 
16342   bool mismatch = false;
16343   if (!TypeInfo.LayoutCompatible) {
16344     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16345 
16346     // C++11 [basic.fundamental] p1:
16347     // Plain char, signed char, and unsigned char are three distinct types.
16348     //
16349     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16350     // char' depending on the current char signedness mode.
16351     if (mismatch)
16352       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16353                                            RequiredType->getPointeeType())) ||
16354           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16355         mismatch = false;
16356   } else
16357     if (IsPointerAttr)
16358       mismatch = !isLayoutCompatible(Context,
16359                                      ArgumentType->getPointeeType(),
16360                                      RequiredType->getPointeeType());
16361     else
16362       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16363 
16364   if (mismatch)
16365     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16366         << ArgumentType << ArgumentKind
16367         << TypeInfo.LayoutCompatible << RequiredType
16368         << ArgumentExpr->getSourceRange()
16369         << TypeTagExpr->getSourceRange();
16370 }
16371 
16372 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16373                                          CharUnits Alignment) {
16374   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16375 }
16376 
16377 void Sema::DiagnoseMisalignedMembers() {
16378   for (MisalignedMember &m : MisalignedMembers) {
16379     const NamedDecl *ND = m.RD;
16380     if (ND->getName().empty()) {
16381       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16382         ND = TD;
16383     }
16384     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16385         << m.MD << ND << m.E->getSourceRange();
16386   }
16387   MisalignedMembers.clear();
16388 }
16389 
16390 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16391   E = E->IgnoreParens();
16392   if (!T->isPointerType() && !T->isIntegerType())
16393     return;
16394   if (isa<UnaryOperator>(E) &&
16395       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16396     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16397     if (isa<MemberExpr>(Op)) {
16398       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16399       if (MA != MisalignedMembers.end() &&
16400           (T->isIntegerType() ||
16401            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16402                                    Context.getTypeAlignInChars(
16403                                        T->getPointeeType()) <= MA->Alignment))))
16404         MisalignedMembers.erase(MA);
16405     }
16406   }
16407 }
16408 
16409 void Sema::RefersToMemberWithReducedAlignment(
16410     Expr *E,
16411     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16412         Action) {
16413   const auto *ME = dyn_cast<MemberExpr>(E);
16414   if (!ME)
16415     return;
16416 
16417   // No need to check expressions with an __unaligned-qualified type.
16418   if (E->getType().getQualifiers().hasUnaligned())
16419     return;
16420 
16421   // For a chain of MemberExpr like "a.b.c.d" this list
16422   // will keep FieldDecl's like [d, c, b].
16423   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16424   const MemberExpr *TopME = nullptr;
16425   bool AnyIsPacked = false;
16426   do {
16427     QualType BaseType = ME->getBase()->getType();
16428     if (BaseType->isDependentType())
16429       return;
16430     if (ME->isArrow())
16431       BaseType = BaseType->getPointeeType();
16432     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16433     if (RD->isInvalidDecl())
16434       return;
16435 
16436     ValueDecl *MD = ME->getMemberDecl();
16437     auto *FD = dyn_cast<FieldDecl>(MD);
16438     // We do not care about non-data members.
16439     if (!FD || FD->isInvalidDecl())
16440       return;
16441 
16442     AnyIsPacked =
16443         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16444     ReverseMemberChain.push_back(FD);
16445 
16446     TopME = ME;
16447     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16448   } while (ME);
16449   assert(TopME && "We did not compute a topmost MemberExpr!");
16450 
16451   // Not the scope of this diagnostic.
16452   if (!AnyIsPacked)
16453     return;
16454 
16455   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16456   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16457   // TODO: The innermost base of the member expression may be too complicated.
16458   // For now, just disregard these cases. This is left for future
16459   // improvement.
16460   if (!DRE && !isa<CXXThisExpr>(TopBase))
16461       return;
16462 
16463   // Alignment expected by the whole expression.
16464   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16465 
16466   // No need to do anything else with this case.
16467   if (ExpectedAlignment.isOne())
16468     return;
16469 
16470   // Synthesize offset of the whole access.
16471   CharUnits Offset;
16472   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16473        I++) {
16474     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16475   }
16476 
16477   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16478   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16479       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16480 
16481   // The base expression of the innermost MemberExpr may give
16482   // stronger guarantees than the class containing the member.
16483   if (DRE && !TopME->isArrow()) {
16484     const ValueDecl *VD = DRE->getDecl();
16485     if (!VD->getType()->isReferenceType())
16486       CompleteObjectAlignment =
16487           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16488   }
16489 
16490   // Check if the synthesized offset fulfills the alignment.
16491   if (Offset % ExpectedAlignment != 0 ||
16492       // It may fulfill the offset it but the effective alignment may still be
16493       // lower than the expected expression alignment.
16494       CompleteObjectAlignment < ExpectedAlignment) {
16495     // If this happens, we want to determine a sensible culprit of this.
16496     // Intuitively, watching the chain of member expressions from right to
16497     // left, we start with the required alignment (as required by the field
16498     // type) but some packed attribute in that chain has reduced the alignment.
16499     // It may happen that another packed structure increases it again. But if
16500     // we are here such increase has not been enough. So pointing the first
16501     // FieldDecl that either is packed or else its RecordDecl is,
16502     // seems reasonable.
16503     FieldDecl *FD = nullptr;
16504     CharUnits Alignment;
16505     for (FieldDecl *FDI : ReverseMemberChain) {
16506       if (FDI->hasAttr<PackedAttr>() ||
16507           FDI->getParent()->hasAttr<PackedAttr>()) {
16508         FD = FDI;
16509         Alignment = std::min(
16510             Context.getTypeAlignInChars(FD->getType()),
16511             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16512         break;
16513       }
16514     }
16515     assert(FD && "We did not find a packed FieldDecl!");
16516     Action(E, FD->getParent(), FD, Alignment);
16517   }
16518 }
16519 
16520 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16521   using namespace std::placeholders;
16522 
16523   RefersToMemberWithReducedAlignment(
16524       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16525                      _2, _3, _4));
16526 }
16527 
16528 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16529                                             ExprResult CallResult) {
16530   if (checkArgCount(*this, TheCall, 1))
16531     return ExprError();
16532 
16533   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16534   if (MatrixArg.isInvalid())
16535     return MatrixArg;
16536   Expr *Matrix = MatrixArg.get();
16537 
16538   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16539   if (!MType) {
16540     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16541     return ExprError();
16542   }
16543 
16544   // Create returned matrix type by swapping rows and columns of the argument
16545   // matrix type.
16546   QualType ResultType = Context.getConstantMatrixType(
16547       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16548 
16549   // Change the return type to the type of the returned matrix.
16550   TheCall->setType(ResultType);
16551 
16552   // Update call argument to use the possibly converted matrix argument.
16553   TheCall->setArg(0, Matrix);
16554   return CallResult;
16555 }
16556 
16557 // Get and verify the matrix dimensions.
16558 static llvm::Optional<unsigned>
16559 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16560   SourceLocation ErrorPos;
16561   Optional<llvm::APSInt> Value =
16562       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16563   if (!Value) {
16564     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16565         << Name;
16566     return {};
16567   }
16568   uint64_t Dim = Value->getZExtValue();
16569   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16570     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16571         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16572     return {};
16573   }
16574   return Dim;
16575 }
16576 
16577 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16578                                                   ExprResult CallResult) {
16579   if (!getLangOpts().MatrixTypes) {
16580     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16581     return ExprError();
16582   }
16583 
16584   if (checkArgCount(*this, TheCall, 4))
16585     return ExprError();
16586 
16587   unsigned PtrArgIdx = 0;
16588   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16589   Expr *RowsExpr = TheCall->getArg(1);
16590   Expr *ColumnsExpr = TheCall->getArg(2);
16591   Expr *StrideExpr = TheCall->getArg(3);
16592 
16593   bool ArgError = false;
16594 
16595   // Check pointer argument.
16596   {
16597     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16598     if (PtrConv.isInvalid())
16599       return PtrConv;
16600     PtrExpr = PtrConv.get();
16601     TheCall->setArg(0, PtrExpr);
16602     if (PtrExpr->isTypeDependent()) {
16603       TheCall->setType(Context.DependentTy);
16604       return TheCall;
16605     }
16606   }
16607 
16608   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16609   QualType ElementTy;
16610   if (!PtrTy) {
16611     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16612         << PtrArgIdx + 1;
16613     ArgError = true;
16614   } else {
16615     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16616 
16617     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16618       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16619           << PtrArgIdx + 1;
16620       ArgError = true;
16621     }
16622   }
16623 
16624   // Apply default Lvalue conversions and convert the expression to size_t.
16625   auto ApplyArgumentConversions = [this](Expr *E) {
16626     ExprResult Conv = DefaultLvalueConversion(E);
16627     if (Conv.isInvalid())
16628       return Conv;
16629 
16630     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16631   };
16632 
16633   // Apply conversion to row and column expressions.
16634   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16635   if (!RowsConv.isInvalid()) {
16636     RowsExpr = RowsConv.get();
16637     TheCall->setArg(1, RowsExpr);
16638   } else
16639     RowsExpr = nullptr;
16640 
16641   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16642   if (!ColumnsConv.isInvalid()) {
16643     ColumnsExpr = ColumnsConv.get();
16644     TheCall->setArg(2, ColumnsExpr);
16645   } else
16646     ColumnsExpr = nullptr;
16647 
16648   // If any any part of the result matrix type is still pending, just use
16649   // Context.DependentTy, until all parts are resolved.
16650   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16651       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16652     TheCall->setType(Context.DependentTy);
16653     return CallResult;
16654   }
16655 
16656   // Check row and column dimenions.
16657   llvm::Optional<unsigned> MaybeRows;
16658   if (RowsExpr)
16659     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16660 
16661   llvm::Optional<unsigned> MaybeColumns;
16662   if (ColumnsExpr)
16663     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16664 
16665   // Check stride argument.
16666   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16667   if (StrideConv.isInvalid())
16668     return ExprError();
16669   StrideExpr = StrideConv.get();
16670   TheCall->setArg(3, StrideExpr);
16671 
16672   if (MaybeRows) {
16673     if (Optional<llvm::APSInt> Value =
16674             StrideExpr->getIntegerConstantExpr(Context)) {
16675       uint64_t Stride = Value->getZExtValue();
16676       if (Stride < *MaybeRows) {
16677         Diag(StrideExpr->getBeginLoc(),
16678              diag::err_builtin_matrix_stride_too_small);
16679         ArgError = true;
16680       }
16681     }
16682   }
16683 
16684   if (ArgError || !MaybeRows || !MaybeColumns)
16685     return ExprError();
16686 
16687   TheCall->setType(
16688       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16689   return CallResult;
16690 }
16691 
16692 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16693                                                    ExprResult CallResult) {
16694   if (checkArgCount(*this, TheCall, 3))
16695     return ExprError();
16696 
16697   unsigned PtrArgIdx = 1;
16698   Expr *MatrixExpr = TheCall->getArg(0);
16699   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16700   Expr *StrideExpr = TheCall->getArg(2);
16701 
16702   bool ArgError = false;
16703 
16704   {
16705     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16706     if (MatrixConv.isInvalid())
16707       return MatrixConv;
16708     MatrixExpr = MatrixConv.get();
16709     TheCall->setArg(0, MatrixExpr);
16710   }
16711   if (MatrixExpr->isTypeDependent()) {
16712     TheCall->setType(Context.DependentTy);
16713     return TheCall;
16714   }
16715 
16716   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16717   if (!MatrixTy) {
16718     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16719     ArgError = true;
16720   }
16721 
16722   {
16723     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16724     if (PtrConv.isInvalid())
16725       return PtrConv;
16726     PtrExpr = PtrConv.get();
16727     TheCall->setArg(1, PtrExpr);
16728     if (PtrExpr->isTypeDependent()) {
16729       TheCall->setType(Context.DependentTy);
16730       return TheCall;
16731     }
16732   }
16733 
16734   // Check pointer argument.
16735   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16736   if (!PtrTy) {
16737     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16738         << PtrArgIdx + 1;
16739     ArgError = true;
16740   } else {
16741     QualType ElementTy = PtrTy->getPointeeType();
16742     if (ElementTy.isConstQualified()) {
16743       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16744       ArgError = true;
16745     }
16746     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16747     if (MatrixTy &&
16748         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16749       Diag(PtrExpr->getBeginLoc(),
16750            diag::err_builtin_matrix_pointer_arg_mismatch)
16751           << ElementTy << MatrixTy->getElementType();
16752       ArgError = true;
16753     }
16754   }
16755 
16756   // Apply default Lvalue conversions and convert the stride expression to
16757   // size_t.
16758   {
16759     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16760     if (StrideConv.isInvalid())
16761       return StrideConv;
16762 
16763     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16764     if (StrideConv.isInvalid())
16765       return StrideConv;
16766     StrideExpr = StrideConv.get();
16767     TheCall->setArg(2, StrideExpr);
16768   }
16769 
16770   // Check stride argument.
16771   if (MatrixTy) {
16772     if (Optional<llvm::APSInt> Value =
16773             StrideExpr->getIntegerConstantExpr(Context)) {
16774       uint64_t Stride = Value->getZExtValue();
16775       if (Stride < MatrixTy->getNumRows()) {
16776         Diag(StrideExpr->getBeginLoc(),
16777              diag::err_builtin_matrix_stride_too_small);
16778         ArgError = true;
16779       }
16780     }
16781   }
16782 
16783   if (ArgError)
16784     return ExprError();
16785 
16786   return CallResult;
16787 }
16788 
16789 /// \brief Enforce the bounds of a TCB
16790 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16791 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16792 /// and enforce_tcb_leaf attributes.
16793 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16794                                const FunctionDecl *Callee) {
16795   const FunctionDecl *Caller = getCurFunctionDecl();
16796 
16797   // Calls to builtins are not enforced.
16798   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16799       Callee->getBuiltinID() != 0)
16800     return;
16801 
16802   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16803   // all TCBs the callee is a part of.
16804   llvm::StringSet<> CalleeTCBs;
16805   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16806            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16807   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16808            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16809 
16810   // Go through the TCBs the caller is a part of and emit warnings if Caller
16811   // is in a TCB that the Callee is not.
16812   for_each(
16813       Caller->specific_attrs<EnforceTCBAttr>(),
16814       [&](const auto *A) {
16815         StringRef CallerTCB = A->getTCBName();
16816         if (CalleeTCBs.count(CallerTCB) == 0) {
16817           this->Diag(TheCall->getExprLoc(),
16818                      diag::warn_tcb_enforcement_violation) << Callee
16819                                                            << CallerTCB;
16820         }
16821       });
16822 }
16823