1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
592                                                CallExpr *TheCall) {
593   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
594       isConstantEvaluated())
595     return;
596 
597   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
598   if (!BuiltinID)
599     return;
600 
601   const TargetInfo &TI = getASTContext().getTargetInfo();
602   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
603 
604   auto ComputeExplicitObjectSizeArgument =
605       [&](unsigned Index) -> Optional<llvm::APSInt> {
606     Expr::EvalResult Result;
607     Expr *SizeArg = TheCall->getArg(Index);
608     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
609       return llvm::None;
610     return Result.Val.getInt();
611   };
612 
613   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
614     // If the parameter has a pass_object_size attribute, then we should use its
615     // (potentially) more strict checking mode. Otherwise, conservatively assume
616     // type 0.
617     int BOSType = 0;
618     if (const auto *POS =
619             FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
620       BOSType = POS->getType();
621 
622     const Expr *ObjArg = TheCall->getArg(Index);
623     uint64_t Result;
624     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
625       return llvm::None;
626 
627     // Get the object size in the target's size_t width.
628     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
629   };
630 
631   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
632     Expr *ObjArg = TheCall->getArg(Index);
633     uint64_t Result;
634     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
635       return llvm::None;
636     // Add 1 for null byte.
637     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
638   };
639 
640   Optional<llvm::APSInt> SourceSize;
641   Optional<llvm::APSInt> DestinationSize;
642   unsigned DiagID = 0;
643   bool IsChkVariant = false;
644 
645   switch (BuiltinID) {
646   default:
647     return;
648   case Builtin::BI__builtin_strcpy:
649   case Builtin::BIstrcpy: {
650     DiagID = diag::warn_fortify_strlen_overflow;
651     SourceSize = ComputeStrLenArgument(1);
652     DestinationSize = ComputeSizeArgument(0);
653     break;
654   }
655 
656   case Builtin::BI__builtin___strcpy_chk: {
657     DiagID = diag::warn_fortify_strlen_overflow;
658     SourceSize = ComputeStrLenArgument(1);
659     DestinationSize = ComputeExplicitObjectSizeArgument(2);
660     IsChkVariant = true;
661     break;
662   }
663 
664   case Builtin::BIsprintf:
665   case Builtin::BI__builtin___sprintf_chk: {
666     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
667     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
668 
669     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
670 
671       if (!Format->isAscii() && !Format->isUTF8())
672         return;
673 
674       StringRef FormatStrRef = Format->getString();
675       EstimateSizeFormatHandler H(FormatStrRef);
676       const char *FormatBytes = FormatStrRef.data();
677       const ConstantArrayType *T =
678           Context.getAsConstantArrayType(Format->getType());
679       assert(T && "String literal not of constant array type!");
680       size_t TypeSize = T->getSize().getZExtValue();
681 
682       // In case there's a null byte somewhere.
683       size_t StrLen =
684           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
685       if (!analyze_format_string::ParsePrintfString(
686               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
687               Context.getTargetInfo(), false)) {
688         DiagID = diag::warn_fortify_source_format_overflow;
689         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
690                          .extOrTrunc(SizeTypeWidth);
691         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
692           DestinationSize = ComputeExplicitObjectSizeArgument(2);
693           IsChkVariant = true;
694         } else {
695           DestinationSize = ComputeSizeArgument(0);
696         }
697         break;
698       }
699     }
700     return;
701   }
702   case Builtin::BI__builtin___memcpy_chk:
703   case Builtin::BI__builtin___memmove_chk:
704   case Builtin::BI__builtin___memset_chk:
705   case Builtin::BI__builtin___strlcat_chk:
706   case Builtin::BI__builtin___strlcpy_chk:
707   case Builtin::BI__builtin___strncat_chk:
708   case Builtin::BI__builtin___strncpy_chk:
709   case Builtin::BI__builtin___stpncpy_chk:
710   case Builtin::BI__builtin___memccpy_chk:
711   case Builtin::BI__builtin___mempcpy_chk: {
712     DiagID = diag::warn_builtin_chk_overflow;
713     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
714     DestinationSize =
715         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
716     IsChkVariant = true;
717     break;
718   }
719 
720   case Builtin::BI__builtin___snprintf_chk:
721   case Builtin::BI__builtin___vsnprintf_chk: {
722     DiagID = diag::warn_builtin_chk_overflow;
723     SourceSize = ComputeExplicitObjectSizeArgument(1);
724     DestinationSize = ComputeExplicitObjectSizeArgument(3);
725     IsChkVariant = true;
726     break;
727   }
728 
729   case Builtin::BIstrncat:
730   case Builtin::BI__builtin_strncat:
731   case Builtin::BIstrncpy:
732   case Builtin::BI__builtin_strncpy:
733   case Builtin::BIstpncpy:
734   case Builtin::BI__builtin_stpncpy: {
735     // Whether these functions overflow depends on the runtime strlen of the
736     // string, not just the buffer size, so emitting the "always overflow"
737     // diagnostic isn't quite right. We should still diagnose passing a buffer
738     // size larger than the destination buffer though; this is a runtime abort
739     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
740     DiagID = diag::warn_fortify_source_size_mismatch;
741     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
742     DestinationSize = ComputeSizeArgument(0);
743     break;
744   }
745 
746   case Builtin::BImemcpy:
747   case Builtin::BI__builtin_memcpy:
748   case Builtin::BImemmove:
749   case Builtin::BI__builtin_memmove:
750   case Builtin::BImemset:
751   case Builtin::BI__builtin_memset:
752   case Builtin::BImempcpy:
753   case Builtin::BI__builtin_mempcpy: {
754     DiagID = diag::warn_fortify_source_overflow;
755     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
756     DestinationSize = ComputeSizeArgument(0);
757     break;
758   }
759   case Builtin::BIsnprintf:
760   case Builtin::BI__builtin_snprintf:
761   case Builtin::BIvsnprintf:
762   case Builtin::BI__builtin_vsnprintf: {
763     DiagID = diag::warn_fortify_source_size_mismatch;
764     SourceSize = ComputeExplicitObjectSizeArgument(1);
765     DestinationSize = ComputeSizeArgument(0);
766     break;
767   }
768   }
769 
770   if (!SourceSize || !DestinationSize ||
771       SourceSize.getValue().ule(DestinationSize.getValue()))
772     return;
773 
774   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775   // Skim off the details of whichever builtin was called to produce a better
776   // diagnostic, as it's unlikely that the user wrote the __builtin explicitly.
777   if (IsChkVariant) {
778     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780   } else if (FunctionName.startswith("__builtin_")) {
781     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782   }
783 
784   SmallString<16> DestinationStr;
785   SmallString<16> SourceStr;
786   DestinationSize->toString(DestinationStr, /*Radix=*/10);
787   SourceSize->toString(SourceStr, /*Radix=*/10);
788   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
789                       PDiag(DiagID)
790                           << FunctionName << DestinationStr << SourceStr);
791 }
792 
793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
794                                      Scope::ScopeFlags NeededScopeFlags,
795                                      unsigned DiagID) {
796   // Scopes aren't available during instantiation. Fortunately, builtin
797   // functions cannot be template args so they cannot be formed through template
798   // instantiation. Therefore checking once during the parse is sufficient.
799   if (SemaRef.inTemplateInstantiation())
800     return false;
801 
802   Scope *S = SemaRef.getCurScope();
803   while (S && !S->isSEHExceptScope())
804     S = S->getParent();
805   if (!S || !(S->getFlags() & NeededScopeFlags)) {
806     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
807     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
808         << DRE->getDecl()->getIdentifier();
809     return true;
810   }
811 
812   return false;
813 }
814 
815 static inline bool isBlockPointer(Expr *Arg) {
816   return Arg->getType()->isBlockPointerType();
817 }
818 
819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
820 /// void*, which is a requirement of device side enqueue.
821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
822   const BlockPointerType *BPT =
823       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
824   ArrayRef<QualType> Params =
825       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
826   unsigned ArgCounter = 0;
827   bool IllegalParams = false;
828   // Iterate through the block parameters until either one is found that is not
829   // a local void*, or the block is valid.
830   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
831        I != E; ++I, ++ArgCounter) {
832     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
833         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
834             LangAS::opencl_local) {
835       // Get the location of the error. If a block literal has been passed
836       // (BlockExpr) then we can point straight to the offending argument,
837       // else we just point to the variable reference.
838       SourceLocation ErrorLoc;
839       if (isa<BlockExpr>(BlockArg)) {
840         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
841         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
842       } else if (isa<DeclRefExpr>(BlockArg)) {
843         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
844       }
845       S.Diag(ErrorLoc,
846              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
847       IllegalParams = true;
848     }
849   }
850 
851   return IllegalParams;
852 }
853 
854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
855   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
856     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
857         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
858     return true;
859   }
860   return false;
861 }
862 
863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
864   if (checkArgCount(S, TheCall, 2))
865     return true;
866 
867   if (checkOpenCLSubgroupExt(S, TheCall))
868     return true;
869 
870   // First argument is an ndrange_t type.
871   Expr *NDRangeArg = TheCall->getArg(0);
872   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
873     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
874         << TheCall->getDirectCallee() << "'ndrange_t'";
875     return true;
876   }
877 
878   Expr *BlockArg = TheCall->getArg(1);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
888 /// get_kernel_work_group_size
889 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
891   if (checkArgCount(S, TheCall, 1))
892     return true;
893 
894   Expr *BlockArg = TheCall->getArg(0);
895   if (!isBlockPointer(BlockArg)) {
896     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
897         << TheCall->getDirectCallee() << "block";
898     return true;
899   }
900   return checkOpenCLBlockArgs(S, BlockArg);
901 }
902 
903 /// Diagnose integer type and any valid implicit conversion to it.
904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
905                                       const QualType &IntType);
906 
907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
908                                             unsigned Start, unsigned End) {
909   bool IllegalParams = false;
910   for (unsigned I = Start; I <= End; ++I)
911     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
912                                               S.Context.getSizeType());
913   return IllegalParams;
914 }
915 
916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
917 /// 'local void*' parameter of passed block.
918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
919                                            Expr *BlockArg,
920                                            unsigned NumNonVarArgs) {
921   const BlockPointerType *BPT =
922       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
923   unsigned NumBlockParams =
924       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
925   unsigned TotalNumArgs = TheCall->getNumArgs();
926 
927   // For each argument passed to the block, a corresponding uint needs to
928   // be passed to describe the size of the local memory.
929   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
930     S.Diag(TheCall->getBeginLoc(),
931            diag::err_opencl_enqueue_kernel_local_size_args);
932     return true;
933   }
934 
935   // Check that the sizes of the local memory are specified by integers.
936   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
937                                          TotalNumArgs - 1);
938 }
939 
940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
941 /// overload formats specified in Table 6.13.17.1.
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    void (^block)(void))
946 /// int enqueue_kernel(queue_t queue,
947 ///                    kernel_enqueue_flags_t flags,
948 ///                    const ndrange_t ndrange,
949 ///                    uint num_events_in_wait_list,
950 ///                    clk_event_t *event_wait_list,
951 ///                    clk_event_t *event_ret,
952 ///                    void (^block)(void))
953 /// int enqueue_kernel(queue_t queue,
954 ///                    kernel_enqueue_flags_t flags,
955 ///                    const ndrange_t ndrange,
956 ///                    void (^block)(local void*, ...),
957 ///                    uint size0, ...)
958 /// int enqueue_kernel(queue_t queue,
959 ///                    kernel_enqueue_flags_t flags,
960 ///                    const ndrange_t ndrange,
961 ///                    uint num_events_in_wait_list,
962 ///                    clk_event_t *event_wait_list,
963 ///                    clk_event_t *event_ret,
964 ///                    void (^block)(local void*, ...),
965 ///                    uint size0, ...)
966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
967   unsigned NumArgs = TheCall->getNumArgs();
968 
969   if (NumArgs < 4) {
970     S.Diag(TheCall->getBeginLoc(),
971            diag::err_typecheck_call_too_few_args_at_least)
972         << 0 << 4 << NumArgs;
973     return true;
974   }
975 
976   Expr *Arg0 = TheCall->getArg(0);
977   Expr *Arg1 = TheCall->getArg(1);
978   Expr *Arg2 = TheCall->getArg(2);
979   Expr *Arg3 = TheCall->getArg(3);
980 
981   // First argument always needs to be a queue_t type.
982   if (!Arg0->getType()->isQueueT()) {
983     S.Diag(TheCall->getArg(0)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
986     return true;
987   }
988 
989   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
990   if (!Arg1->getType()->isIntegerType()) {
991     S.Diag(TheCall->getArg(1)->getBeginLoc(),
992            diag::err_opencl_builtin_expected_type)
993         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
994     return true;
995   }
996 
997   // Third argument is always an ndrange_t type.
998   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
999     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1000            diag::err_opencl_builtin_expected_type)
1001         << TheCall->getDirectCallee() << "'ndrange_t'";
1002     return true;
1003   }
1004 
1005   // With four arguments, there is only one form that the function could be
1006   // called in: no events and no variable arguments.
1007   if (NumArgs == 4) {
1008     // check that the last argument is the right block type.
1009     if (!isBlockPointer(Arg3)) {
1010       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1011           << TheCall->getDirectCallee() << "block";
1012       return true;
1013     }
1014     // we have a block type, check the prototype
1015     const BlockPointerType *BPT =
1016         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1017     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1018       S.Diag(Arg3->getBeginLoc(),
1019              diag::err_opencl_enqueue_kernel_blocks_no_args);
1020       return true;
1021     }
1022     return false;
1023   }
1024   // we can have block + varargs.
1025   if (isBlockPointer(Arg3))
1026     return (checkOpenCLBlockArgs(S, Arg3) ||
1027             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1028   // last two cases with either exactly 7 args or 7 args and varargs.
1029   if (NumArgs >= 7) {
1030     // check common block argument.
1031     Expr *Arg6 = TheCall->getArg(6);
1032     if (!isBlockPointer(Arg6)) {
1033       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1034           << TheCall->getDirectCallee() << "block";
1035       return true;
1036     }
1037     if (checkOpenCLBlockArgs(S, Arg6))
1038       return true;
1039 
1040     // Forth argument has to be any integer type.
1041     if (!Arg3->getType()->isIntegerType()) {
1042       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee() << "integer";
1045       return true;
1046     }
1047     // check remaining common arguments.
1048     Expr *Arg4 = TheCall->getArg(4);
1049     Expr *Arg5 = TheCall->getArg(5);
1050 
1051     // Fifth argument is always passed as a pointer to clk_event_t.
1052     if (!Arg4->isNullPointerConstant(S.Context,
1053                                      Expr::NPC_ValueDependentIsNotNull) &&
1054         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1055       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1056              diag::err_opencl_builtin_expected_type)
1057           << TheCall->getDirectCallee()
1058           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1059       return true;
1060     }
1061 
1062     // Sixth argument is always passed as a pointer to clk_event_t.
1063     if (!Arg5->isNullPointerConstant(S.Context,
1064                                      Expr::NPC_ValueDependentIsNotNull) &&
1065         !(Arg5->getType()->isPointerType() &&
1066           Arg5->getType()->getPointeeType()->isClkEventT())) {
1067       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1068              diag::err_opencl_builtin_expected_type)
1069           << TheCall->getDirectCallee()
1070           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1071       return true;
1072     }
1073 
1074     if (NumArgs == 7)
1075       return false;
1076 
1077     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1078   }
1079 
1080   // None of the specific case has been detected, give generic error
1081   S.Diag(TheCall->getBeginLoc(),
1082          diag::err_opencl_enqueue_kernel_incorrect_args);
1083   return true;
1084 }
1085 
1086 /// Returns OpenCL access qual.
1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1088     return D->getAttr<OpenCLAccessAttr>();
1089 }
1090 
1091 /// Returns true if pipe element type is different from the pointer.
1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1093   const Expr *Arg0 = Call->getArg(0);
1094   // First argument type should always be pipe.
1095   if (!Arg0->getType()->isPipeType()) {
1096     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1097         << Call->getDirectCallee() << Arg0->getSourceRange();
1098     return true;
1099   }
1100   OpenCLAccessAttr *AccessQual =
1101       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1102   // Validates the access qualifier is compatible with the call.
1103   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1104   // read_only and write_only, and assumed to be read_only if no qualifier is
1105   // specified.
1106   switch (Call->getDirectCallee()->getBuiltinID()) {
1107   case Builtin::BIread_pipe:
1108   case Builtin::BIreserve_read_pipe:
1109   case Builtin::BIcommit_read_pipe:
1110   case Builtin::BIwork_group_reserve_read_pipe:
1111   case Builtin::BIsub_group_reserve_read_pipe:
1112   case Builtin::BIwork_group_commit_read_pipe:
1113   case Builtin::BIsub_group_commit_read_pipe:
1114     if (!(!AccessQual || AccessQual->isReadOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "read_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   case Builtin::BIwrite_pipe:
1122   case Builtin::BIreserve_write_pipe:
1123   case Builtin::BIcommit_write_pipe:
1124   case Builtin::BIwork_group_reserve_write_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126   case Builtin::BIwork_group_commit_write_pipe:
1127   case Builtin::BIsub_group_commit_write_pipe:
1128     if (!(AccessQual && AccessQual->isWriteOnly())) {
1129       S.Diag(Arg0->getBeginLoc(),
1130              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1131           << "write_only" << Arg0->getSourceRange();
1132       return true;
1133     }
1134     break;
1135   default:
1136     break;
1137   }
1138   return false;
1139 }
1140 
1141 /// Returns true if pipe element type is different from the pointer.
1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1143   const Expr *Arg0 = Call->getArg(0);
1144   const Expr *ArgIdx = Call->getArg(Idx);
1145   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1146   const QualType EltTy = PipeTy->getElementType();
1147   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1148   // The Idx argument should be a pointer and the type of the pointer and
1149   // the type of pipe element should also be the same.
1150   if (!ArgTy ||
1151       !S.Context.hasSameType(
1152           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1153     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1154         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1155         << ArgIdx->getType() << ArgIdx->getSourceRange();
1156     return true;
1157   }
1158   return false;
1159 }
1160 
1161 // Performs semantic analysis for the read/write_pipe call.
1162 // \param S Reference to the semantic analyzer.
1163 // \param Call A pointer to the builtin call.
1164 // \return True if a semantic error has been found, false otherwise.
1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1166   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1167   // functions have two forms.
1168   switch (Call->getNumArgs()) {
1169   case 2:
1170     if (checkOpenCLPipeArg(S, Call))
1171       return true;
1172     // The call with 2 arguments should be
1173     // read/write_pipe(pipe T, T*).
1174     // Check packet type T.
1175     if (checkOpenCLPipePacketType(S, Call, 1))
1176       return true;
1177     break;
1178 
1179   case 4: {
1180     if (checkOpenCLPipeArg(S, Call))
1181       return true;
1182     // The call with 4 arguments should be
1183     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1184     // Check reserve_id_t.
1185     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1186       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1187           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1188           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1189       return true;
1190     }
1191 
1192     // Check the index.
1193     const Expr *Arg2 = Call->getArg(2);
1194     if (!Arg2->getType()->isIntegerType() &&
1195         !Arg2->getType()->isUnsignedIntegerType()) {
1196       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1197           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1198           << Arg2->getType() << Arg2->getSourceRange();
1199       return true;
1200     }
1201 
1202     // Check packet type T.
1203     if (checkOpenCLPipePacketType(S, Call, 3))
1204       return true;
1205   } break;
1206   default:
1207     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1208         << Call->getDirectCallee() << Call->getSourceRange();
1209     return true;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on the {work_group_/sub_group_
1216 //        /_}reserve_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check the reserve size.
1228   if (!Call->getArg(1)->getType()->isIntegerType() &&
1229       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1230     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1231         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1232         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1233     return true;
1234   }
1235 
1236   // Since return type of reserve_read/write_pipe built-in function is
1237   // reserve_id_t, which is not defined in the builtin def file , we used int
1238   // as return type and need to override the return type of these functions.
1239   Call->setType(S.Context.OCLReserveIDTy);
1240 
1241   return false;
1242 }
1243 
1244 // Performs a semantic analysis on {work_group_/sub_group_
1245 //        /_}commit_{read/write}_pipe
1246 // \param S Reference to the semantic analyzer.
1247 // \param Call The call to the builtin function to be analyzed.
1248 // \return True if a semantic error was found, false otherwise.
1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1250   if (checkArgCount(S, Call, 2))
1251     return true;
1252 
1253   if (checkOpenCLPipeArg(S, Call))
1254     return true;
1255 
1256   // Check reserve_id_t.
1257   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1258     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1259         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1260         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 // Performs a semantic analysis on the call to built-in Pipe
1268 //        Query Functions.
1269 // \param S Reference to the semantic analyzer.
1270 // \param Call The call to the builtin function to be analyzed.
1271 // \return True if a semantic error was found, false otherwise.
1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1273   if (checkArgCount(S, Call, 1))
1274     return true;
1275 
1276   if (!Call->getArg(0)->getType()->isPipeType()) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1278         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1279     return true;
1280   }
1281 
1282   return false;
1283 }
1284 
1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1286 // Performs semantic analysis for the to_global/local/private call.
1287 // \param S Reference to the semantic analyzer.
1288 // \param BuiltinID ID of the builtin function.
1289 // \param Call A pointer to the builtin call.
1290 // \return True if a semantic error has been found, false otherwise.
1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1292                                     CallExpr *Call) {
1293   if (checkArgCount(S, Call, 1))
1294     return true;
1295 
1296   auto RT = Call->getArg(0)->getType();
1297   if (!RT->isPointerType() || RT->getPointeeType()
1298       .getAddressSpace() == LangAS::opencl_constant) {
1299     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1300         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1301     return true;
1302   }
1303 
1304   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1305     S.Diag(Call->getArg(0)->getBeginLoc(),
1306            diag::warn_opencl_generic_address_space_arg)
1307         << Call->getDirectCallee()->getNameInfo().getAsString()
1308         << Call->getArg(0)->getSourceRange();
1309   }
1310 
1311   RT = RT->getPointeeType();
1312   auto Qual = RT.getQualifiers();
1313   switch (BuiltinID) {
1314   case Builtin::BIto_global:
1315     Qual.setAddressSpace(LangAS::opencl_global);
1316     break;
1317   case Builtin::BIto_local:
1318     Qual.setAddressSpace(LangAS::opencl_local);
1319     break;
1320   case Builtin::BIto_private:
1321     Qual.setAddressSpace(LangAS::opencl_private);
1322     break;
1323   default:
1324     llvm_unreachable("Invalid builtin function");
1325   }
1326   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1327       RT.getUnqualifiedType(), Qual)));
1328 
1329   return false;
1330 }
1331 
1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1333   if (checkArgCount(S, TheCall, 1))
1334     return ExprError();
1335 
1336   // Compute __builtin_launder's parameter type from the argument.
1337   // The parameter type is:
1338   //  * The type of the argument if it's not an array or function type,
1339   //  Otherwise,
1340   //  * The decayed argument type.
1341   QualType ParamTy = [&]() {
1342     QualType ArgTy = TheCall->getArg(0)->getType();
1343     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1344       return S.Context.getPointerType(Ty->getElementType());
1345     if (ArgTy->isFunctionType()) {
1346       return S.Context.getPointerType(ArgTy);
1347     }
1348     return ArgTy;
1349   }();
1350 
1351   TheCall->setType(ParamTy);
1352 
1353   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1354     if (!ParamTy->isPointerType())
1355       return 0;
1356     if (ParamTy->isFunctionPointerType())
1357       return 1;
1358     if (ParamTy->isVoidPointerType())
1359       return 2;
1360     return llvm::Optional<unsigned>{};
1361   }();
1362   if (DiagSelect.hasValue()) {
1363     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1364         << DiagSelect.getValue() << TheCall->getSourceRange();
1365     return ExprError();
1366   }
1367 
1368   // We either have an incomplete class type, or we have a class template
1369   // whose instantiation has not been forced. Example:
1370   //
1371   //   template <class T> struct Foo { T value; };
1372   //   Foo<int> *p = nullptr;
1373   //   auto *d = __builtin_launder(p);
1374   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1375                             diag::err_incomplete_type))
1376     return ExprError();
1377 
1378   assert(ParamTy->getPointeeType()->isObjectType() &&
1379          "Unhandled non-object pointer case");
1380 
1381   InitializedEntity Entity =
1382       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1383   ExprResult Arg =
1384       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1385   if (Arg.isInvalid())
1386     return ExprError();
1387   TheCall->setArg(0, Arg.get());
1388 
1389   return TheCall;
1390 }
1391 
1392 // Emit an error and return true if the current architecture is not in the list
1393 // of supported architectures.
1394 static bool
1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1396                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1397   llvm::Triple::ArchType CurArch =
1398       S.getASTContext().getTargetInfo().getTriple().getArch();
1399   if (llvm::is_contained(SupportedArchs, CurArch))
1400     return false;
1401   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1402       << TheCall->getSourceRange();
1403   return true;
1404 }
1405 
1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1407                                  SourceLocation CallSiteLoc);
1408 
1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1410                                       CallExpr *TheCall) {
1411   switch (TI.getTriple().getArch()) {
1412   default:
1413     // Some builtins don't require additional checking, so just consider these
1414     // acceptable.
1415     return false;
1416   case llvm::Triple::arm:
1417   case llvm::Triple::armeb:
1418   case llvm::Triple::thumb:
1419   case llvm::Triple::thumbeb:
1420     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::aarch64:
1422   case llvm::Triple::aarch64_32:
1423   case llvm::Triple::aarch64_be:
1424     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::bpfeb:
1426   case llvm::Triple::bpfel:
1427     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1428   case llvm::Triple::hexagon:
1429     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1430   case llvm::Triple::mips:
1431   case llvm::Triple::mipsel:
1432   case llvm::Triple::mips64:
1433   case llvm::Triple::mips64el:
1434     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   case llvm::Triple::systemz:
1436     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1437   case llvm::Triple::x86:
1438   case llvm::Triple::x86_64:
1439     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1440   case llvm::Triple::ppc:
1441   case llvm::Triple::ppcle:
1442   case llvm::Triple::ppc64:
1443   case llvm::Triple::ppc64le:
1444     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1445   case llvm::Triple::amdgcn:
1446     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1447   case llvm::Triple::riscv32:
1448   case llvm::Triple::riscv64:
1449     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1450   }
1451 }
1452 
1453 ExprResult
1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1455                                CallExpr *TheCall) {
1456   ExprResult TheCallResult(TheCall);
1457 
1458   // Find out if any arguments are required to be integer constant expressions.
1459   unsigned ICEArguments = 0;
1460   ASTContext::GetBuiltinTypeError Error;
1461   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1462   if (Error != ASTContext::GE_None)
1463     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1464 
1465   // If any arguments are required to be ICE's, check and diagnose.
1466   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1467     // Skip arguments not required to be ICE's.
1468     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1469 
1470     llvm::APSInt Result;
1471     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1472       return true;
1473     ICEArguments &= ~(1 << ArgNo);
1474   }
1475 
1476   switch (BuiltinID) {
1477   case Builtin::BI__builtin___CFStringMakeConstantString:
1478     assert(TheCall->getNumArgs() == 1 &&
1479            "Wrong # arguments to builtin CFStringMakeConstantString");
1480     if (CheckObjCString(TheCall->getArg(0)))
1481       return ExprError();
1482     break;
1483   case Builtin::BI__builtin_ms_va_start:
1484   case Builtin::BI__builtin_stdarg_start:
1485   case Builtin::BI__builtin_va_start:
1486     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BI__va_start: {
1490     switch (Context.getTargetInfo().getTriple().getArch()) {
1491     case llvm::Triple::aarch64:
1492     case llvm::Triple::arm:
1493     case llvm::Triple::thumb:
1494       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1495         return ExprError();
1496       break;
1497     default:
1498       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1499         return ExprError();
1500       break;
1501     }
1502     break;
1503   }
1504 
1505   // The acquire, release, and no fence variants are ARM and AArch64 only.
1506   case Builtin::BI_interlockedbittestandset_acq:
1507   case Builtin::BI_interlockedbittestandset_rel:
1508   case Builtin::BI_interlockedbittestandset_nf:
1509   case Builtin::BI_interlockedbittestandreset_acq:
1510   case Builtin::BI_interlockedbittestandreset_rel:
1511   case Builtin::BI_interlockedbittestandreset_nf:
1512     if (CheckBuiltinTargetSupport(
1513             *this, BuiltinID, TheCall,
1514             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1519   case Builtin::BI_bittest64:
1520   case Builtin::BI_bittestandcomplement64:
1521   case Builtin::BI_bittestandreset64:
1522   case Builtin::BI_bittestandset64:
1523   case Builtin::BI_interlockedbittestandreset64:
1524   case Builtin::BI_interlockedbittestandset64:
1525     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1526                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1527                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1528       return ExprError();
1529     break;
1530 
1531   case Builtin::BI__builtin_isgreater:
1532   case Builtin::BI__builtin_isgreaterequal:
1533   case Builtin::BI__builtin_isless:
1534   case Builtin::BI__builtin_islessequal:
1535   case Builtin::BI__builtin_islessgreater:
1536   case Builtin::BI__builtin_isunordered:
1537     if (SemaBuiltinUnorderedCompare(TheCall))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_fpclassify:
1541     if (SemaBuiltinFPClassification(TheCall, 6))
1542       return ExprError();
1543     break;
1544   case Builtin::BI__builtin_isfinite:
1545   case Builtin::BI__builtin_isinf:
1546   case Builtin::BI__builtin_isinf_sign:
1547   case Builtin::BI__builtin_isnan:
1548   case Builtin::BI__builtin_isnormal:
1549   case Builtin::BI__builtin_signbit:
1550   case Builtin::BI__builtin_signbitf:
1551   case Builtin::BI__builtin_signbitl:
1552     if (SemaBuiltinFPClassification(TheCall, 1))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_shufflevector:
1556     return SemaBuiltinShuffleVector(TheCall);
1557     // TheCall will be freed by the smart pointer here, but that's fine, since
1558     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1559   case Builtin::BI__builtin_prefetch:
1560     if (SemaBuiltinPrefetch(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_alloca_with_align:
1564     if (SemaBuiltinAllocaWithAlign(TheCall))
1565       return ExprError();
1566     LLVM_FALLTHROUGH;
1567   case Builtin::BI__builtin_alloca:
1568     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1569         << TheCall->getDirectCallee();
1570     break;
1571   case Builtin::BI__arithmetic_fence:
1572     if (SemaBuiltinArithmeticFence(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__assume:
1576   case Builtin::BI__builtin_assume:
1577     if (SemaBuiltinAssume(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_assume_aligned:
1581     if (SemaBuiltinAssumeAligned(TheCall))
1582       return ExprError();
1583     break;
1584   case Builtin::BI__builtin_dynamic_object_size:
1585   case Builtin::BI__builtin_object_size:
1586     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1587       return ExprError();
1588     break;
1589   case Builtin::BI__builtin_longjmp:
1590     if (SemaBuiltinLongjmp(TheCall))
1591       return ExprError();
1592     break;
1593   case Builtin::BI__builtin_setjmp:
1594     if (SemaBuiltinSetjmp(TheCall))
1595       return ExprError();
1596     break;
1597   case Builtin::BI__builtin_classify_type:
1598     if (checkArgCount(*this, TheCall, 1)) return true;
1599     TheCall->setType(Context.IntTy);
1600     break;
1601   case Builtin::BI__builtin_complex:
1602     if (SemaBuiltinComplex(TheCall))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_constant_p: {
1606     if (checkArgCount(*this, TheCall, 1)) return true;
1607     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1608     if (Arg.isInvalid()) return true;
1609     TheCall->setArg(0, Arg.get());
1610     TheCall->setType(Context.IntTy);
1611     break;
1612   }
1613   case Builtin::BI__builtin_launder:
1614     return SemaBuiltinLaunder(*this, TheCall);
1615   case Builtin::BI__sync_fetch_and_add:
1616   case Builtin::BI__sync_fetch_and_add_1:
1617   case Builtin::BI__sync_fetch_and_add_2:
1618   case Builtin::BI__sync_fetch_and_add_4:
1619   case Builtin::BI__sync_fetch_and_add_8:
1620   case Builtin::BI__sync_fetch_and_add_16:
1621   case Builtin::BI__sync_fetch_and_sub:
1622   case Builtin::BI__sync_fetch_and_sub_1:
1623   case Builtin::BI__sync_fetch_and_sub_2:
1624   case Builtin::BI__sync_fetch_and_sub_4:
1625   case Builtin::BI__sync_fetch_and_sub_8:
1626   case Builtin::BI__sync_fetch_and_sub_16:
1627   case Builtin::BI__sync_fetch_and_or:
1628   case Builtin::BI__sync_fetch_and_or_1:
1629   case Builtin::BI__sync_fetch_and_or_2:
1630   case Builtin::BI__sync_fetch_and_or_4:
1631   case Builtin::BI__sync_fetch_and_or_8:
1632   case Builtin::BI__sync_fetch_and_or_16:
1633   case Builtin::BI__sync_fetch_and_and:
1634   case Builtin::BI__sync_fetch_and_and_1:
1635   case Builtin::BI__sync_fetch_and_and_2:
1636   case Builtin::BI__sync_fetch_and_and_4:
1637   case Builtin::BI__sync_fetch_and_and_8:
1638   case Builtin::BI__sync_fetch_and_and_16:
1639   case Builtin::BI__sync_fetch_and_xor:
1640   case Builtin::BI__sync_fetch_and_xor_1:
1641   case Builtin::BI__sync_fetch_and_xor_2:
1642   case Builtin::BI__sync_fetch_and_xor_4:
1643   case Builtin::BI__sync_fetch_and_xor_8:
1644   case Builtin::BI__sync_fetch_and_xor_16:
1645   case Builtin::BI__sync_fetch_and_nand:
1646   case Builtin::BI__sync_fetch_and_nand_1:
1647   case Builtin::BI__sync_fetch_and_nand_2:
1648   case Builtin::BI__sync_fetch_and_nand_4:
1649   case Builtin::BI__sync_fetch_and_nand_8:
1650   case Builtin::BI__sync_fetch_and_nand_16:
1651   case Builtin::BI__sync_add_and_fetch:
1652   case Builtin::BI__sync_add_and_fetch_1:
1653   case Builtin::BI__sync_add_and_fetch_2:
1654   case Builtin::BI__sync_add_and_fetch_4:
1655   case Builtin::BI__sync_add_and_fetch_8:
1656   case Builtin::BI__sync_add_and_fetch_16:
1657   case Builtin::BI__sync_sub_and_fetch:
1658   case Builtin::BI__sync_sub_and_fetch_1:
1659   case Builtin::BI__sync_sub_and_fetch_2:
1660   case Builtin::BI__sync_sub_and_fetch_4:
1661   case Builtin::BI__sync_sub_and_fetch_8:
1662   case Builtin::BI__sync_sub_and_fetch_16:
1663   case Builtin::BI__sync_and_and_fetch:
1664   case Builtin::BI__sync_and_and_fetch_1:
1665   case Builtin::BI__sync_and_and_fetch_2:
1666   case Builtin::BI__sync_and_and_fetch_4:
1667   case Builtin::BI__sync_and_and_fetch_8:
1668   case Builtin::BI__sync_and_and_fetch_16:
1669   case Builtin::BI__sync_or_and_fetch:
1670   case Builtin::BI__sync_or_and_fetch_1:
1671   case Builtin::BI__sync_or_and_fetch_2:
1672   case Builtin::BI__sync_or_and_fetch_4:
1673   case Builtin::BI__sync_or_and_fetch_8:
1674   case Builtin::BI__sync_or_and_fetch_16:
1675   case Builtin::BI__sync_xor_and_fetch:
1676   case Builtin::BI__sync_xor_and_fetch_1:
1677   case Builtin::BI__sync_xor_and_fetch_2:
1678   case Builtin::BI__sync_xor_and_fetch_4:
1679   case Builtin::BI__sync_xor_and_fetch_8:
1680   case Builtin::BI__sync_xor_and_fetch_16:
1681   case Builtin::BI__sync_nand_and_fetch:
1682   case Builtin::BI__sync_nand_and_fetch_1:
1683   case Builtin::BI__sync_nand_and_fetch_2:
1684   case Builtin::BI__sync_nand_and_fetch_4:
1685   case Builtin::BI__sync_nand_and_fetch_8:
1686   case Builtin::BI__sync_nand_and_fetch_16:
1687   case Builtin::BI__sync_val_compare_and_swap:
1688   case Builtin::BI__sync_val_compare_and_swap_1:
1689   case Builtin::BI__sync_val_compare_and_swap_2:
1690   case Builtin::BI__sync_val_compare_and_swap_4:
1691   case Builtin::BI__sync_val_compare_and_swap_8:
1692   case Builtin::BI__sync_val_compare_and_swap_16:
1693   case Builtin::BI__sync_bool_compare_and_swap:
1694   case Builtin::BI__sync_bool_compare_and_swap_1:
1695   case Builtin::BI__sync_bool_compare_and_swap_2:
1696   case Builtin::BI__sync_bool_compare_and_swap_4:
1697   case Builtin::BI__sync_bool_compare_and_swap_8:
1698   case Builtin::BI__sync_bool_compare_and_swap_16:
1699   case Builtin::BI__sync_lock_test_and_set:
1700   case Builtin::BI__sync_lock_test_and_set_1:
1701   case Builtin::BI__sync_lock_test_and_set_2:
1702   case Builtin::BI__sync_lock_test_and_set_4:
1703   case Builtin::BI__sync_lock_test_and_set_8:
1704   case Builtin::BI__sync_lock_test_and_set_16:
1705   case Builtin::BI__sync_lock_release:
1706   case Builtin::BI__sync_lock_release_1:
1707   case Builtin::BI__sync_lock_release_2:
1708   case Builtin::BI__sync_lock_release_4:
1709   case Builtin::BI__sync_lock_release_8:
1710   case Builtin::BI__sync_lock_release_16:
1711   case Builtin::BI__sync_swap:
1712   case Builtin::BI__sync_swap_1:
1713   case Builtin::BI__sync_swap_2:
1714   case Builtin::BI__sync_swap_4:
1715   case Builtin::BI__sync_swap_8:
1716   case Builtin::BI__sync_swap_16:
1717     return SemaBuiltinAtomicOverloaded(TheCallResult);
1718   case Builtin::BI__sync_synchronize:
1719     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1720         << TheCall->getCallee()->getSourceRange();
1721     break;
1722   case Builtin::BI__builtin_nontemporal_load:
1723   case Builtin::BI__builtin_nontemporal_store:
1724     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1725   case Builtin::BI__builtin_memcpy_inline: {
1726     clang::Expr *SizeOp = TheCall->getArg(2);
1727     // We warn about copying to or from `nullptr` pointers when `size` is
1728     // greater than 0. When `size` is value dependent we cannot evaluate its
1729     // value so we bail out.
1730     if (SizeOp->isValueDependent())
1731       break;
1732     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
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_elementwise_abs:
1980     if (SemaBuiltinElementwiseMathOneArg(TheCall))
1981       return ExprError();
1982     break;
1983   case Builtin::BI__builtin_elementwise_min:
1984   case Builtin::BI__builtin_elementwise_max:
1985     if (SemaBuiltinElementwiseMath(TheCall))
1986       return ExprError();
1987     break;
1988   case Builtin::BI__builtin_reduce_max:
1989   case Builtin::BI__builtin_reduce_min:
1990     if (SemaBuiltinReduceMath(TheCall))
1991       return ExprError();
1992     break;
1993   case Builtin::BI__builtin_matrix_transpose:
1994     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1995 
1996   case Builtin::BI__builtin_matrix_column_major_load:
1997     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1998 
1999   case Builtin::BI__builtin_matrix_column_major_store:
2000     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
2001 
2002   case Builtin::BI__builtin_get_device_side_mangled_name: {
2003     auto Check = [](CallExpr *TheCall) {
2004       if (TheCall->getNumArgs() != 1)
2005         return false;
2006       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
2007       if (!DRE)
2008         return false;
2009       auto *D = DRE->getDecl();
2010       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
2011         return false;
2012       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
2013              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2014     };
2015     if (!Check(TheCall)) {
2016       Diag(TheCall->getBeginLoc(),
2017            diag::err_hip_invalid_args_builtin_mangled_name);
2018       return ExprError();
2019     }
2020   }
2021   }
2022 
2023   // Since the target specific builtins for each arch overlap, only check those
2024   // of the arch we are compiling for.
2025   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2026     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2027       assert(Context.getAuxTargetInfo() &&
2028              "Aux Target Builtin, but not an aux target?");
2029 
2030       if (CheckTSBuiltinFunctionCall(
2031               *Context.getAuxTargetInfo(),
2032               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2033         return ExprError();
2034     } else {
2035       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2036                                      TheCall))
2037         return ExprError();
2038     }
2039   }
2040 
2041   return TheCallResult;
2042 }
2043 
2044 // Get the valid immediate range for the specified NEON type code.
2045 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2046   NeonTypeFlags Type(t);
2047   int IsQuad = ForceQuad ? true : Type.isQuad();
2048   switch (Type.getEltType()) {
2049   case NeonTypeFlags::Int8:
2050   case NeonTypeFlags::Poly8:
2051     return shift ? 7 : (8 << IsQuad) - 1;
2052   case NeonTypeFlags::Int16:
2053   case NeonTypeFlags::Poly16:
2054     return shift ? 15 : (4 << IsQuad) - 1;
2055   case NeonTypeFlags::Int32:
2056     return shift ? 31 : (2 << IsQuad) - 1;
2057   case NeonTypeFlags::Int64:
2058   case NeonTypeFlags::Poly64:
2059     return shift ? 63 : (1 << IsQuad) - 1;
2060   case NeonTypeFlags::Poly128:
2061     return shift ? 127 : (1 << IsQuad) - 1;
2062   case NeonTypeFlags::Float16:
2063     assert(!shift && "cannot shift float types!");
2064     return (4 << IsQuad) - 1;
2065   case NeonTypeFlags::Float32:
2066     assert(!shift && "cannot shift float types!");
2067     return (2 << IsQuad) - 1;
2068   case NeonTypeFlags::Float64:
2069     assert(!shift && "cannot shift float types!");
2070     return (1 << IsQuad) - 1;
2071   case NeonTypeFlags::BFloat16:
2072     assert(!shift && "cannot shift float types!");
2073     return (4 << IsQuad) - 1;
2074   }
2075   llvm_unreachable("Invalid NeonTypeFlag!");
2076 }
2077 
2078 /// getNeonEltType - Return the QualType corresponding to the elements of
2079 /// the vector type specified by the NeonTypeFlags.  This is used to check
2080 /// the pointer arguments for Neon load/store intrinsics.
2081 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2082                                bool IsPolyUnsigned, bool IsInt64Long) {
2083   switch (Flags.getEltType()) {
2084   case NeonTypeFlags::Int8:
2085     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2086   case NeonTypeFlags::Int16:
2087     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2088   case NeonTypeFlags::Int32:
2089     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2090   case NeonTypeFlags::Int64:
2091     if (IsInt64Long)
2092       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2093     else
2094       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2095                                 : Context.LongLongTy;
2096   case NeonTypeFlags::Poly8:
2097     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2098   case NeonTypeFlags::Poly16:
2099     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2100   case NeonTypeFlags::Poly64:
2101     if (IsInt64Long)
2102       return Context.UnsignedLongTy;
2103     else
2104       return Context.UnsignedLongLongTy;
2105   case NeonTypeFlags::Poly128:
2106     break;
2107   case NeonTypeFlags::Float16:
2108     return Context.HalfTy;
2109   case NeonTypeFlags::Float32:
2110     return Context.FloatTy;
2111   case NeonTypeFlags::Float64:
2112     return Context.DoubleTy;
2113   case NeonTypeFlags::BFloat16:
2114     return Context.BFloat16Ty;
2115   }
2116   llvm_unreachable("Invalid NeonTypeFlag!");
2117 }
2118 
2119 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2120   // Range check SVE intrinsics that take immediate values.
2121   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2122 
2123   switch (BuiltinID) {
2124   default:
2125     return false;
2126 #define GET_SVE_IMMEDIATE_CHECK
2127 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2128 #undef GET_SVE_IMMEDIATE_CHECK
2129   }
2130 
2131   // Perform all the immediate checks for this builtin call.
2132   bool HasError = false;
2133   for (auto &I : ImmChecks) {
2134     int ArgNum, CheckTy, ElementSizeInBits;
2135     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2136 
2137     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2138 
2139     // Function that checks whether the operand (ArgNum) is an immediate
2140     // that is one of the predefined values.
2141     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2142                                    int ErrDiag) -> bool {
2143       // We can't check the value of a dependent argument.
2144       Expr *Arg = TheCall->getArg(ArgNum);
2145       if (Arg->isTypeDependent() || Arg->isValueDependent())
2146         return false;
2147 
2148       // Check constant-ness first.
2149       llvm::APSInt Imm;
2150       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2151         return true;
2152 
2153       if (!CheckImm(Imm.getSExtValue()))
2154         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2155       return false;
2156     };
2157 
2158     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2159     case SVETypeFlags::ImmCheck0_31:
2160       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2161         HasError = true;
2162       break;
2163     case SVETypeFlags::ImmCheck0_13:
2164       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheck1_16:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheck0_7:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheckExtract:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2177                                       (2048 / ElementSizeInBits) - 1))
2178         HasError = true;
2179       break;
2180     case SVETypeFlags::ImmCheckShiftRight:
2181       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2182         HasError = true;
2183       break;
2184     case SVETypeFlags::ImmCheckShiftRightNarrow:
2185       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2186                                       ElementSizeInBits / 2))
2187         HasError = true;
2188       break;
2189     case SVETypeFlags::ImmCheckShiftLeft:
2190       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2191                                       ElementSizeInBits - 1))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheckLaneIndex:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2196                                       (128 / (1 * ElementSizeInBits)) - 1))
2197         HasError = true;
2198       break;
2199     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2200       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2201                                       (128 / (2 * ElementSizeInBits)) - 1))
2202         HasError = true;
2203       break;
2204     case SVETypeFlags::ImmCheckLaneIndexDot:
2205       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2206                                       (128 / (4 * ElementSizeInBits)) - 1))
2207         HasError = true;
2208       break;
2209     case SVETypeFlags::ImmCheckComplexRot90_270:
2210       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2211                               diag::err_rotation_argument_to_cadd))
2212         HasError = true;
2213       break;
2214     case SVETypeFlags::ImmCheckComplexRotAll90:
2215       if (CheckImmediateInSet(
2216               [](int64_t V) {
2217                 return V == 0 || V == 90 || V == 180 || V == 270;
2218               },
2219               diag::err_rotation_argument_to_cmla))
2220         HasError = true;
2221       break;
2222     case SVETypeFlags::ImmCheck0_1:
2223       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2224         HasError = true;
2225       break;
2226     case SVETypeFlags::ImmCheck0_2:
2227       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2228         HasError = true;
2229       break;
2230     case SVETypeFlags::ImmCheck0_3:
2231       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2232         HasError = true;
2233       break;
2234     }
2235   }
2236 
2237   return HasError;
2238 }
2239 
2240 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2241                                         unsigned BuiltinID, CallExpr *TheCall) {
2242   llvm::APSInt Result;
2243   uint64_t mask = 0;
2244   unsigned TV = 0;
2245   int PtrArgNum = -1;
2246   bool HasConstPtr = false;
2247   switch (BuiltinID) {
2248 #define GET_NEON_OVERLOAD_CHECK
2249 #include "clang/Basic/arm_neon.inc"
2250 #include "clang/Basic/arm_fp16.inc"
2251 #undef GET_NEON_OVERLOAD_CHECK
2252   }
2253 
2254   // For NEON intrinsics which are overloaded on vector element type, validate
2255   // the immediate which specifies which variant to emit.
2256   unsigned ImmArg = TheCall->getNumArgs()-1;
2257   if (mask) {
2258     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2259       return true;
2260 
2261     TV = Result.getLimitedValue(64);
2262     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2263       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2264              << TheCall->getArg(ImmArg)->getSourceRange();
2265   }
2266 
2267   if (PtrArgNum >= 0) {
2268     // Check that pointer arguments have the specified type.
2269     Expr *Arg = TheCall->getArg(PtrArgNum);
2270     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2271       Arg = ICE->getSubExpr();
2272     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2273     QualType RHSTy = RHS.get()->getType();
2274 
2275     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2276     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2277                           Arch == llvm::Triple::aarch64_32 ||
2278                           Arch == llvm::Triple::aarch64_be;
2279     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2280     QualType EltTy =
2281         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2282     if (HasConstPtr)
2283       EltTy = EltTy.withConst();
2284     QualType LHSTy = Context.getPointerType(EltTy);
2285     AssignConvertType ConvTy;
2286     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2287     if (RHS.isInvalid())
2288       return true;
2289     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2290                                  RHS.get(), AA_Assigning))
2291       return true;
2292   }
2293 
2294   // For NEON intrinsics which take an immediate value as part of the
2295   // instruction, range check them here.
2296   unsigned i = 0, l = 0, u = 0;
2297   switch (BuiltinID) {
2298   default:
2299     return false;
2300   #define GET_NEON_IMMEDIATE_CHECK
2301   #include "clang/Basic/arm_neon.inc"
2302   #include "clang/Basic/arm_fp16.inc"
2303   #undef GET_NEON_IMMEDIATE_CHECK
2304   }
2305 
2306   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2307 }
2308 
2309 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2310   switch (BuiltinID) {
2311   default:
2312     return false;
2313   #include "clang/Basic/arm_mve_builtin_sema.inc"
2314   }
2315 }
2316 
2317 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2318                                        CallExpr *TheCall) {
2319   bool Err = false;
2320   switch (BuiltinID) {
2321   default:
2322     return false;
2323 #include "clang/Basic/arm_cde_builtin_sema.inc"
2324   }
2325 
2326   if (Err)
2327     return true;
2328 
2329   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2330 }
2331 
2332 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2333                                         const Expr *CoprocArg, bool WantCDE) {
2334   if (isConstantEvaluated())
2335     return false;
2336 
2337   // We can't check the value of a dependent argument.
2338   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2339     return false;
2340 
2341   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2342   int64_t CoprocNo = CoprocNoAP.getExtValue();
2343   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2344 
2345   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2346   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2347 
2348   if (IsCDECoproc != WantCDE)
2349     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2350            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2351 
2352   return false;
2353 }
2354 
2355 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2356                                         unsigned MaxWidth) {
2357   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2358           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2359           BuiltinID == ARM::BI__builtin_arm_strex ||
2360           BuiltinID == ARM::BI__builtin_arm_stlex ||
2361           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2362           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2363           BuiltinID == AArch64::BI__builtin_arm_strex ||
2364           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2365          "unexpected ARM builtin");
2366   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2367                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2368                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2369                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2370 
2371   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2372 
2373   // Ensure that we have the proper number of arguments.
2374   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2375     return true;
2376 
2377   // Inspect the pointer argument of the atomic builtin.  This should always be
2378   // a pointer type, whose element is an integral scalar or pointer type.
2379   // Because it is a pointer type, we don't have to worry about any implicit
2380   // casts here.
2381   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2382   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2383   if (PointerArgRes.isInvalid())
2384     return true;
2385   PointerArg = PointerArgRes.get();
2386 
2387   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2388   if (!pointerType) {
2389     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2390         << PointerArg->getType() << PointerArg->getSourceRange();
2391     return true;
2392   }
2393 
2394   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2395   // task is to insert the appropriate casts into the AST. First work out just
2396   // what the appropriate type is.
2397   QualType ValType = pointerType->getPointeeType();
2398   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2399   if (IsLdrex)
2400     AddrType.addConst();
2401 
2402   // Issue a warning if the cast is dodgy.
2403   CastKind CastNeeded = CK_NoOp;
2404   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2405     CastNeeded = CK_BitCast;
2406     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2407         << PointerArg->getType() << Context.getPointerType(AddrType)
2408         << AA_Passing << PointerArg->getSourceRange();
2409   }
2410 
2411   // Finally, do the cast and replace the argument with the corrected version.
2412   AddrType = Context.getPointerType(AddrType);
2413   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2414   if (PointerArgRes.isInvalid())
2415     return true;
2416   PointerArg = PointerArgRes.get();
2417 
2418   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2419 
2420   // In general, we allow ints, floats and pointers to be loaded and stored.
2421   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2422       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2423     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2424         << PointerArg->getType() << PointerArg->getSourceRange();
2425     return true;
2426   }
2427 
2428   // But ARM doesn't have instructions to deal with 128-bit versions.
2429   if (Context.getTypeSize(ValType) > MaxWidth) {
2430     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2431     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2432         << PointerArg->getType() << PointerArg->getSourceRange();
2433     return true;
2434   }
2435 
2436   switch (ValType.getObjCLifetime()) {
2437   case Qualifiers::OCL_None:
2438   case Qualifiers::OCL_ExplicitNone:
2439     // okay
2440     break;
2441 
2442   case Qualifiers::OCL_Weak:
2443   case Qualifiers::OCL_Strong:
2444   case Qualifiers::OCL_Autoreleasing:
2445     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2446         << ValType << PointerArg->getSourceRange();
2447     return true;
2448   }
2449 
2450   if (IsLdrex) {
2451     TheCall->setType(ValType);
2452     return false;
2453   }
2454 
2455   // Initialize the argument to be stored.
2456   ExprResult ValArg = TheCall->getArg(0);
2457   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2458       Context, ValType, /*consume*/ false);
2459   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2460   if (ValArg.isInvalid())
2461     return true;
2462   TheCall->setArg(0, ValArg.get());
2463 
2464   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2465   // but the custom checker bypasses all default analysis.
2466   TheCall->setType(Context.IntTy);
2467   return false;
2468 }
2469 
2470 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2471                                        CallExpr *TheCall) {
2472   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2473       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2474       BuiltinID == ARM::BI__builtin_arm_strex ||
2475       BuiltinID == ARM::BI__builtin_arm_stlex) {
2476     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2477   }
2478 
2479   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2480     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2481       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2482   }
2483 
2484   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2485       BuiltinID == ARM::BI__builtin_arm_wsr64)
2486     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2487 
2488   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2489       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2490       BuiltinID == ARM::BI__builtin_arm_wsr ||
2491       BuiltinID == ARM::BI__builtin_arm_wsrp)
2492     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2493 
2494   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2495     return true;
2496   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2497     return true;
2498   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2499     return true;
2500 
2501   // For intrinsics which take an immediate value as part of the instruction,
2502   // range check them here.
2503   // FIXME: VFP Intrinsics should error if VFP not present.
2504   switch (BuiltinID) {
2505   default: return false;
2506   case ARM::BI__builtin_arm_ssat:
2507     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2508   case ARM::BI__builtin_arm_usat:
2509     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2510   case ARM::BI__builtin_arm_ssat16:
2511     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2512   case ARM::BI__builtin_arm_usat16:
2513     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2514   case ARM::BI__builtin_arm_vcvtr_f:
2515   case ARM::BI__builtin_arm_vcvtr_d:
2516     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2517   case ARM::BI__builtin_arm_dmb:
2518   case ARM::BI__builtin_arm_dsb:
2519   case ARM::BI__builtin_arm_isb:
2520   case ARM::BI__builtin_arm_dbg:
2521     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2522   case ARM::BI__builtin_arm_cdp:
2523   case ARM::BI__builtin_arm_cdp2:
2524   case ARM::BI__builtin_arm_mcr:
2525   case ARM::BI__builtin_arm_mcr2:
2526   case ARM::BI__builtin_arm_mrc:
2527   case ARM::BI__builtin_arm_mrc2:
2528   case ARM::BI__builtin_arm_mcrr:
2529   case ARM::BI__builtin_arm_mcrr2:
2530   case ARM::BI__builtin_arm_mrrc:
2531   case ARM::BI__builtin_arm_mrrc2:
2532   case ARM::BI__builtin_arm_ldc:
2533   case ARM::BI__builtin_arm_ldcl:
2534   case ARM::BI__builtin_arm_ldc2:
2535   case ARM::BI__builtin_arm_ldc2l:
2536   case ARM::BI__builtin_arm_stc:
2537   case ARM::BI__builtin_arm_stcl:
2538   case ARM::BI__builtin_arm_stc2:
2539   case ARM::BI__builtin_arm_stc2l:
2540     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2541            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2542                                         /*WantCDE*/ false);
2543   }
2544 }
2545 
2546 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2547                                            unsigned BuiltinID,
2548                                            CallExpr *TheCall) {
2549   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2550       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2551       BuiltinID == AArch64::BI__builtin_arm_strex ||
2552       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2553     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2554   }
2555 
2556   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2557     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2558       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2559       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2560       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2561   }
2562 
2563   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2564       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2565     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2566 
2567   // Memory Tagging Extensions (MTE) Intrinsics
2568   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2569       BuiltinID == AArch64::BI__builtin_arm_addg ||
2570       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2571       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2572       BuiltinID == AArch64::BI__builtin_arm_stg ||
2573       BuiltinID == AArch64::BI__builtin_arm_subp) {
2574     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2575   }
2576 
2577   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2578       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2579       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2580       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2581     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2582 
2583   // Only check the valid encoding range. Any constant in this range would be
2584   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2585   // an exception for incorrect registers. This matches MSVC behavior.
2586   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2587       BuiltinID == AArch64::BI_WriteStatusReg)
2588     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2589 
2590   if (BuiltinID == AArch64::BI__getReg)
2591     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2592 
2593   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2594     return true;
2595 
2596   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2597     return true;
2598 
2599   // For intrinsics which take an immediate value as part of the instruction,
2600   // range check them here.
2601   unsigned i = 0, l = 0, u = 0;
2602   switch (BuiltinID) {
2603   default: return false;
2604   case AArch64::BI__builtin_arm_dmb:
2605   case AArch64::BI__builtin_arm_dsb:
2606   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2607   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2608   }
2609 
2610   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2611 }
2612 
2613 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2614   if (Arg->getType()->getAsPlaceholderType())
2615     return false;
2616 
2617   // The first argument needs to be a record field access.
2618   // If it is an array element access, we delay decision
2619   // to BPF backend to check whether the access is a
2620   // field access or not.
2621   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2622           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2623           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2624 }
2625 
2626 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2627                             QualType VectorTy, QualType EltTy) {
2628   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2629   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2630     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2631         << Call->getSourceRange() << VectorEltTy << EltTy;
2632     return false;
2633   }
2634   return true;
2635 }
2636 
2637 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2638   QualType ArgType = Arg->getType();
2639   if (ArgType->getAsPlaceholderType())
2640     return false;
2641 
2642   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2643   // format:
2644   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2645   //   2. <type> var;
2646   //      __builtin_preserve_type_info(var, flag);
2647   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2648       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2649     return false;
2650 
2651   // Typedef type.
2652   if (ArgType->getAs<TypedefType>())
2653     return true;
2654 
2655   // Record type or Enum type.
2656   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2657   if (const auto *RT = Ty->getAs<RecordType>()) {
2658     if (!RT->getDecl()->getDeclName().isEmpty())
2659       return true;
2660   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2661     if (!ET->getDecl()->getDeclName().isEmpty())
2662       return true;
2663   }
2664 
2665   return false;
2666 }
2667 
2668 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2669   QualType ArgType = Arg->getType();
2670   if (ArgType->getAsPlaceholderType())
2671     return false;
2672 
2673   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2674   // format:
2675   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2676   //                                 flag);
2677   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2678   if (!UO)
2679     return false;
2680 
2681   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2682   if (!CE)
2683     return false;
2684   if (CE->getCastKind() != CK_IntegralToPointer &&
2685       CE->getCastKind() != CK_NullToPointer)
2686     return false;
2687 
2688   // The integer must be from an EnumConstantDecl.
2689   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2690   if (!DR)
2691     return false;
2692 
2693   const EnumConstantDecl *Enumerator =
2694       dyn_cast<EnumConstantDecl>(DR->getDecl());
2695   if (!Enumerator)
2696     return false;
2697 
2698   // The type must be EnumType.
2699   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2700   const auto *ET = Ty->getAs<EnumType>();
2701   if (!ET)
2702     return false;
2703 
2704   // The enum value must be supported.
2705   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2706 }
2707 
2708 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2709                                        CallExpr *TheCall) {
2710   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2711           BuiltinID == BPF::BI__builtin_btf_type_id ||
2712           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2713           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2714          "unexpected BPF builtin");
2715 
2716   if (checkArgCount(*this, TheCall, 2))
2717     return true;
2718 
2719   // The second argument needs to be a constant int
2720   Expr *Arg = TheCall->getArg(1);
2721   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2722   diag::kind kind;
2723   if (!Value) {
2724     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2725       kind = diag::err_preserve_field_info_not_const;
2726     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2727       kind = diag::err_btf_type_id_not_const;
2728     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2729       kind = diag::err_preserve_type_info_not_const;
2730     else
2731       kind = diag::err_preserve_enum_value_not_const;
2732     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2733     return true;
2734   }
2735 
2736   // The first argument
2737   Arg = TheCall->getArg(0);
2738   bool InvalidArg = false;
2739   bool ReturnUnsignedInt = true;
2740   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2741     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2742       InvalidArg = true;
2743       kind = diag::err_preserve_field_info_not_field;
2744     }
2745   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2746     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2747       InvalidArg = true;
2748       kind = diag::err_preserve_type_info_invalid;
2749     }
2750   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2751     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2752       InvalidArg = true;
2753       kind = diag::err_preserve_enum_value_invalid;
2754     }
2755     ReturnUnsignedInt = false;
2756   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2757     ReturnUnsignedInt = false;
2758   }
2759 
2760   if (InvalidArg) {
2761     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2762     return true;
2763   }
2764 
2765   if (ReturnUnsignedInt)
2766     TheCall->setType(Context.UnsignedIntTy);
2767   else
2768     TheCall->setType(Context.UnsignedLongTy);
2769   return false;
2770 }
2771 
2772 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2773   struct ArgInfo {
2774     uint8_t OpNum;
2775     bool IsSigned;
2776     uint8_t BitWidth;
2777     uint8_t Align;
2778   };
2779   struct BuiltinInfo {
2780     unsigned BuiltinID;
2781     ArgInfo Infos[2];
2782   };
2783 
2784   static BuiltinInfo Infos[] = {
2785     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2786     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2787     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2788     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2789     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2790     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2791     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2792     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2793     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2794     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2795     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2796 
2797     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2800     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2801     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2802     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2808 
2809     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2861                                                       {{ 1, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2869                                                       {{ 1, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2876                                                        { 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2878                                                        { 2, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2882                                                        { 3, false, 6,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2899                                                       {{ 2, false, 4,  0 },
2900                                                        { 3, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2902                                                       {{ 2, false, 4,  0 },
2903                                                        { 3, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2905                                                       {{ 2, false, 4,  0 },
2906                                                        { 3, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2908                                                       {{ 2, false, 4,  0 },
2909                                                        { 3, false, 5,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2921                                                        { 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2923                                                        { 2, false, 6,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2933                                                       {{ 1, false, 4,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2936                                                       {{ 1, false, 4,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2948     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2953     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2954     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2955     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2956     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2957                                                       {{ 3, false, 1,  0 }} },
2958     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2959     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2960     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2961     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2962                                                       {{ 3, false, 1,  0 }} },
2963     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2964     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2965     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2966     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2967                                                       {{ 3, false, 1,  0 }} },
2968   };
2969 
2970   // Use a dynamically initialized static to sort the table exactly once on
2971   // first run.
2972   static const bool SortOnce =
2973       (llvm::sort(Infos,
2974                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2975                    return LHS.BuiltinID < RHS.BuiltinID;
2976                  }),
2977        true);
2978   (void)SortOnce;
2979 
2980   const BuiltinInfo *F = llvm::partition_point(
2981       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2982   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2983     return false;
2984 
2985   bool Error = false;
2986 
2987   for (const ArgInfo &A : F->Infos) {
2988     // Ignore empty ArgInfo elements.
2989     if (A.BitWidth == 0)
2990       continue;
2991 
2992     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2993     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2994     if (!A.Align) {
2995       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2996     } else {
2997       unsigned M = 1 << A.Align;
2998       Min *= M;
2999       Max *= M;
3000       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
3001       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
3002     }
3003   }
3004   return Error;
3005 }
3006 
3007 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
3008                                            CallExpr *TheCall) {
3009   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
3010 }
3011 
3012 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
3013                                         unsigned BuiltinID, CallExpr *TheCall) {
3014   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3015          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3016 }
3017 
3018 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3019                                CallExpr *TheCall) {
3020 
3021   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3022       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3023     if (!TI.hasFeature("dsp"))
3024       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3025   }
3026 
3027   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3028       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3029     if (!TI.hasFeature("dspr2"))
3030       return Diag(TheCall->getBeginLoc(),
3031                   diag::err_mips_builtin_requires_dspr2);
3032   }
3033 
3034   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3035       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3036     if (!TI.hasFeature("msa"))
3037       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3038   }
3039 
3040   return false;
3041 }
3042 
3043 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3044 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3045 // ordering for DSP is unspecified. MSA is ordered by the data format used
3046 // by the underlying instruction i.e., df/m, df/n and then by size.
3047 //
3048 // FIXME: The size tests here should instead be tablegen'd along with the
3049 //        definitions from include/clang/Basic/BuiltinsMips.def.
3050 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3051 //        be too.
3052 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3053   unsigned i = 0, l = 0, u = 0, m = 0;
3054   switch (BuiltinID) {
3055   default: return false;
3056   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3057   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3058   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3059   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3060   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3061   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3062   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3063   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3064   // df/m field.
3065   // These intrinsics take an unsigned 3 bit immediate.
3066   case Mips::BI__builtin_msa_bclri_b:
3067   case Mips::BI__builtin_msa_bnegi_b:
3068   case Mips::BI__builtin_msa_bseti_b:
3069   case Mips::BI__builtin_msa_sat_s_b:
3070   case Mips::BI__builtin_msa_sat_u_b:
3071   case Mips::BI__builtin_msa_slli_b:
3072   case Mips::BI__builtin_msa_srai_b:
3073   case Mips::BI__builtin_msa_srari_b:
3074   case Mips::BI__builtin_msa_srli_b:
3075   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3076   case Mips::BI__builtin_msa_binsli_b:
3077   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3078   // These intrinsics take an unsigned 4 bit immediate.
3079   case Mips::BI__builtin_msa_bclri_h:
3080   case Mips::BI__builtin_msa_bnegi_h:
3081   case Mips::BI__builtin_msa_bseti_h:
3082   case Mips::BI__builtin_msa_sat_s_h:
3083   case Mips::BI__builtin_msa_sat_u_h:
3084   case Mips::BI__builtin_msa_slli_h:
3085   case Mips::BI__builtin_msa_srai_h:
3086   case Mips::BI__builtin_msa_srari_h:
3087   case Mips::BI__builtin_msa_srli_h:
3088   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3089   case Mips::BI__builtin_msa_binsli_h:
3090   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3091   // These intrinsics take an unsigned 5 bit immediate.
3092   // The first block of intrinsics actually have an unsigned 5 bit field,
3093   // not a df/n field.
3094   case Mips::BI__builtin_msa_cfcmsa:
3095   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3096   case Mips::BI__builtin_msa_clei_u_b:
3097   case Mips::BI__builtin_msa_clei_u_h:
3098   case Mips::BI__builtin_msa_clei_u_w:
3099   case Mips::BI__builtin_msa_clei_u_d:
3100   case Mips::BI__builtin_msa_clti_u_b:
3101   case Mips::BI__builtin_msa_clti_u_h:
3102   case Mips::BI__builtin_msa_clti_u_w:
3103   case Mips::BI__builtin_msa_clti_u_d:
3104   case Mips::BI__builtin_msa_maxi_u_b:
3105   case Mips::BI__builtin_msa_maxi_u_h:
3106   case Mips::BI__builtin_msa_maxi_u_w:
3107   case Mips::BI__builtin_msa_maxi_u_d:
3108   case Mips::BI__builtin_msa_mini_u_b:
3109   case Mips::BI__builtin_msa_mini_u_h:
3110   case Mips::BI__builtin_msa_mini_u_w:
3111   case Mips::BI__builtin_msa_mini_u_d:
3112   case Mips::BI__builtin_msa_addvi_b:
3113   case Mips::BI__builtin_msa_addvi_h:
3114   case Mips::BI__builtin_msa_addvi_w:
3115   case Mips::BI__builtin_msa_addvi_d:
3116   case Mips::BI__builtin_msa_bclri_w:
3117   case Mips::BI__builtin_msa_bnegi_w:
3118   case Mips::BI__builtin_msa_bseti_w:
3119   case Mips::BI__builtin_msa_sat_s_w:
3120   case Mips::BI__builtin_msa_sat_u_w:
3121   case Mips::BI__builtin_msa_slli_w:
3122   case Mips::BI__builtin_msa_srai_w:
3123   case Mips::BI__builtin_msa_srari_w:
3124   case Mips::BI__builtin_msa_srli_w:
3125   case Mips::BI__builtin_msa_srlri_w:
3126   case Mips::BI__builtin_msa_subvi_b:
3127   case Mips::BI__builtin_msa_subvi_h:
3128   case Mips::BI__builtin_msa_subvi_w:
3129   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3130   case Mips::BI__builtin_msa_binsli_w:
3131   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3132   // These intrinsics take an unsigned 6 bit immediate.
3133   case Mips::BI__builtin_msa_bclri_d:
3134   case Mips::BI__builtin_msa_bnegi_d:
3135   case Mips::BI__builtin_msa_bseti_d:
3136   case Mips::BI__builtin_msa_sat_s_d:
3137   case Mips::BI__builtin_msa_sat_u_d:
3138   case Mips::BI__builtin_msa_slli_d:
3139   case Mips::BI__builtin_msa_srai_d:
3140   case Mips::BI__builtin_msa_srari_d:
3141   case Mips::BI__builtin_msa_srli_d:
3142   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3143   case Mips::BI__builtin_msa_binsli_d:
3144   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3145   // These intrinsics take a signed 5 bit immediate.
3146   case Mips::BI__builtin_msa_ceqi_b:
3147   case Mips::BI__builtin_msa_ceqi_h:
3148   case Mips::BI__builtin_msa_ceqi_w:
3149   case Mips::BI__builtin_msa_ceqi_d:
3150   case Mips::BI__builtin_msa_clti_s_b:
3151   case Mips::BI__builtin_msa_clti_s_h:
3152   case Mips::BI__builtin_msa_clti_s_w:
3153   case Mips::BI__builtin_msa_clti_s_d:
3154   case Mips::BI__builtin_msa_clei_s_b:
3155   case Mips::BI__builtin_msa_clei_s_h:
3156   case Mips::BI__builtin_msa_clei_s_w:
3157   case Mips::BI__builtin_msa_clei_s_d:
3158   case Mips::BI__builtin_msa_maxi_s_b:
3159   case Mips::BI__builtin_msa_maxi_s_h:
3160   case Mips::BI__builtin_msa_maxi_s_w:
3161   case Mips::BI__builtin_msa_maxi_s_d:
3162   case Mips::BI__builtin_msa_mini_s_b:
3163   case Mips::BI__builtin_msa_mini_s_h:
3164   case Mips::BI__builtin_msa_mini_s_w:
3165   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3166   // These intrinsics take an unsigned 8 bit immediate.
3167   case Mips::BI__builtin_msa_andi_b:
3168   case Mips::BI__builtin_msa_nori_b:
3169   case Mips::BI__builtin_msa_ori_b:
3170   case Mips::BI__builtin_msa_shf_b:
3171   case Mips::BI__builtin_msa_shf_h:
3172   case Mips::BI__builtin_msa_shf_w:
3173   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3174   case Mips::BI__builtin_msa_bseli_b:
3175   case Mips::BI__builtin_msa_bmnzi_b:
3176   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3177   // df/n format
3178   // These intrinsics take an unsigned 4 bit immediate.
3179   case Mips::BI__builtin_msa_copy_s_b:
3180   case Mips::BI__builtin_msa_copy_u_b:
3181   case Mips::BI__builtin_msa_insve_b:
3182   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3183   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3184   // These intrinsics take an unsigned 3 bit immediate.
3185   case Mips::BI__builtin_msa_copy_s_h:
3186   case Mips::BI__builtin_msa_copy_u_h:
3187   case Mips::BI__builtin_msa_insve_h:
3188   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3189   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3190   // These intrinsics take an unsigned 2 bit immediate.
3191   case Mips::BI__builtin_msa_copy_s_w:
3192   case Mips::BI__builtin_msa_copy_u_w:
3193   case Mips::BI__builtin_msa_insve_w:
3194   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3195   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3196   // These intrinsics take an unsigned 1 bit immediate.
3197   case Mips::BI__builtin_msa_copy_s_d:
3198   case Mips::BI__builtin_msa_copy_u_d:
3199   case Mips::BI__builtin_msa_insve_d:
3200   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3201   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3202   // Memory offsets and immediate loads.
3203   // These intrinsics take a signed 10 bit immediate.
3204   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3205   case Mips::BI__builtin_msa_ldi_h:
3206   case Mips::BI__builtin_msa_ldi_w:
3207   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3208   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3209   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3210   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3211   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3212   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3213   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3214   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3215   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3216   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3217   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3218   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3219   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3220   }
3221 
3222   if (!m)
3223     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3224 
3225   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3226          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3227 }
3228 
3229 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3230 /// advancing the pointer over the consumed characters. The decoded type is
3231 /// returned. If the decoded type represents a constant integer with a
3232 /// constraint on its value then Mask is set to that value. The type descriptors
3233 /// used in Str are specific to PPC MMA builtins and are documented in the file
3234 /// defining the PPC builtins.
3235 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3236                                         unsigned &Mask) {
3237   bool RequireICE = false;
3238   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3239   switch (*Str++) {
3240   case 'V':
3241     return Context.getVectorType(Context.UnsignedCharTy, 16,
3242                                  VectorType::VectorKind::AltiVecVector);
3243   case 'i': {
3244     char *End;
3245     unsigned size = strtoul(Str, &End, 10);
3246     assert(End != Str && "Missing constant parameter constraint");
3247     Str = End;
3248     Mask = size;
3249     return Context.IntTy;
3250   }
3251   case 'W': {
3252     char *End;
3253     unsigned size = strtoul(Str, &End, 10);
3254     assert(End != Str && "Missing PowerPC MMA type size");
3255     Str = End;
3256     QualType Type;
3257     switch (size) {
3258   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3259     case size: Type = Context.Id##Ty; break;
3260   #include "clang/Basic/PPCTypes.def"
3261     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3262     }
3263     bool CheckVectorArgs = false;
3264     while (!CheckVectorArgs) {
3265       switch (*Str++) {
3266       case '*':
3267         Type = Context.getPointerType(Type);
3268         break;
3269       case 'C':
3270         Type = Type.withConst();
3271         break;
3272       default:
3273         CheckVectorArgs = true;
3274         --Str;
3275         break;
3276       }
3277     }
3278     return Type;
3279   }
3280   default:
3281     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3282   }
3283 }
3284 
3285 static bool isPPC_64Builtin(unsigned BuiltinID) {
3286   // These builtins only work on PPC 64bit targets.
3287   switch (BuiltinID) {
3288   case PPC::BI__builtin_divde:
3289   case PPC::BI__builtin_divdeu:
3290   case PPC::BI__builtin_bpermd:
3291   case PPC::BI__builtin_ppc_ldarx:
3292   case PPC::BI__builtin_ppc_stdcx:
3293   case PPC::BI__builtin_ppc_tdw:
3294   case PPC::BI__builtin_ppc_trapd:
3295   case PPC::BI__builtin_ppc_cmpeqb:
3296   case PPC::BI__builtin_ppc_setb:
3297   case PPC::BI__builtin_ppc_mulhd:
3298   case PPC::BI__builtin_ppc_mulhdu:
3299   case PPC::BI__builtin_ppc_maddhd:
3300   case PPC::BI__builtin_ppc_maddhdu:
3301   case PPC::BI__builtin_ppc_maddld:
3302   case PPC::BI__builtin_ppc_load8r:
3303   case PPC::BI__builtin_ppc_store8r:
3304   case PPC::BI__builtin_ppc_insert_exp:
3305   case PPC::BI__builtin_ppc_extract_sig:
3306   case PPC::BI__builtin_ppc_addex:
3307   case PPC::BI__builtin_darn:
3308   case PPC::BI__builtin_darn_raw:
3309   case PPC::BI__builtin_ppc_compare_and_swaplp:
3310   case PPC::BI__builtin_ppc_fetch_and_addlp:
3311   case PPC::BI__builtin_ppc_fetch_and_andlp:
3312   case PPC::BI__builtin_ppc_fetch_and_orlp:
3313   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3314     return true;
3315   }
3316   return false;
3317 }
3318 
3319 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3320                              StringRef FeatureToCheck, unsigned DiagID,
3321                              StringRef DiagArg = "") {
3322   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3323     return false;
3324 
3325   if (DiagArg.empty())
3326     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3327   else
3328     S.Diag(TheCall->getBeginLoc(), DiagID)
3329         << DiagArg << TheCall->getSourceRange();
3330 
3331   return true;
3332 }
3333 
3334 /// Returns true if the argument consists of one contiguous run of 1s with any
3335 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3336 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3337 /// since all 1s are not contiguous.
3338 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3339   llvm::APSInt Result;
3340   // We can't check the value of a dependent argument.
3341   Expr *Arg = TheCall->getArg(ArgNum);
3342   if (Arg->isTypeDependent() || Arg->isValueDependent())
3343     return false;
3344 
3345   // Check constant-ness first.
3346   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3347     return true;
3348 
3349   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3350   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3351     return false;
3352 
3353   return Diag(TheCall->getBeginLoc(),
3354               diag::err_argument_not_contiguous_bit_field)
3355          << ArgNum << Arg->getSourceRange();
3356 }
3357 
3358 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3359                                        CallExpr *TheCall) {
3360   unsigned i = 0, l = 0, u = 0;
3361   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3362   llvm::APSInt Result;
3363 
3364   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3365     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3366            << TheCall->getSourceRange();
3367 
3368   switch (BuiltinID) {
3369   default: return false;
3370   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3371   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3372     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3373            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3374   case PPC::BI__builtin_altivec_dss:
3375     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3376   case PPC::BI__builtin_tbegin:
3377   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3378   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3379   case PPC::BI__builtin_tabortwc:
3380   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3381   case PPC::BI__builtin_tabortwci:
3382   case PPC::BI__builtin_tabortdci:
3383     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3384            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3385   // According to GCC 'Basic PowerPC Built-in Functions Available on ISA 2.05',
3386   // __builtin_(un)pack_longdouble are available only if long double uses IBM
3387   // extended double representation.
3388   case PPC::BI__builtin_unpack_longdouble:
3389     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 1))
3390       return true;
3391     LLVM_FALLTHROUGH;
3392   case PPC::BI__builtin_pack_longdouble:
3393     if (&TI.getLongDoubleFormat() != &llvm::APFloat::PPCDoubleDouble())
3394       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_requires_abi)
3395              << "ibmlongdouble";
3396     return false;
3397   case PPC::BI__builtin_altivec_dst:
3398   case PPC::BI__builtin_altivec_dstt:
3399   case PPC::BI__builtin_altivec_dstst:
3400   case PPC::BI__builtin_altivec_dststt:
3401     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3402   case PPC::BI__builtin_vsx_xxpermdi:
3403   case PPC::BI__builtin_vsx_xxsldwi:
3404     return SemaBuiltinVSX(TheCall);
3405   case PPC::BI__builtin_divwe:
3406   case PPC::BI__builtin_divweu:
3407   case PPC::BI__builtin_divde:
3408   case PPC::BI__builtin_divdeu:
3409     return SemaFeatureCheck(*this, TheCall, "extdiv",
3410                             diag::err_ppc_builtin_only_on_arch, "7");
3411   case PPC::BI__builtin_bpermd:
3412     return SemaFeatureCheck(*this, TheCall, "bpermd",
3413                             diag::err_ppc_builtin_only_on_arch, "7");
3414   case PPC::BI__builtin_unpack_vector_int128:
3415     return SemaFeatureCheck(*this, TheCall, "vsx",
3416                             diag::err_ppc_builtin_only_on_arch, "7") ||
3417            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3418   case PPC::BI__builtin_pack_vector_int128:
3419     return SemaFeatureCheck(*this, TheCall, "vsx",
3420                             diag::err_ppc_builtin_only_on_arch, "7");
3421   case PPC::BI__builtin_altivec_vgnb:
3422      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3423   case PPC::BI__builtin_altivec_vec_replace_elt:
3424   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3425     QualType VecTy = TheCall->getArg(0)->getType();
3426     QualType EltTy = TheCall->getArg(1)->getType();
3427     unsigned Width = Context.getIntWidth(EltTy);
3428     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3429            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3430   }
3431   case PPC::BI__builtin_vsx_xxeval:
3432      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3433   case PPC::BI__builtin_altivec_vsldbi:
3434      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3435   case PPC::BI__builtin_altivec_vsrdbi:
3436      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3437   case PPC::BI__builtin_vsx_xxpermx:
3438      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3439   case PPC::BI__builtin_ppc_tw:
3440   case PPC::BI__builtin_ppc_tdw:
3441     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3442   case PPC::BI__builtin_ppc_cmpeqb:
3443   case PPC::BI__builtin_ppc_setb:
3444   case PPC::BI__builtin_ppc_maddhd:
3445   case PPC::BI__builtin_ppc_maddhdu:
3446   case PPC::BI__builtin_ppc_maddld:
3447     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3448                             diag::err_ppc_builtin_only_on_arch, "9");
3449   case PPC::BI__builtin_ppc_cmprb:
3450     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3451                             diag::err_ppc_builtin_only_on_arch, "9") ||
3452            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3453   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3454   // be a constant that represents a contiguous bit field.
3455   case PPC::BI__builtin_ppc_rlwnm:
3456     return SemaValueIsRunOfOnes(TheCall, 2);
3457   case PPC::BI__builtin_ppc_rlwimi:
3458   case PPC::BI__builtin_ppc_rldimi:
3459     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3460            SemaValueIsRunOfOnes(TheCall, 3);
3461   case PPC::BI__builtin_ppc_extract_exp:
3462   case PPC::BI__builtin_ppc_extract_sig:
3463   case PPC::BI__builtin_ppc_insert_exp:
3464     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3465                             diag::err_ppc_builtin_only_on_arch, "9");
3466   case PPC::BI__builtin_ppc_addex: {
3467     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3468                          diag::err_ppc_builtin_only_on_arch, "9") ||
3469         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3470       return true;
3471     // Output warning for reserved values 1 to 3.
3472     int ArgValue =
3473         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3474     if (ArgValue != 0)
3475       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3476           << ArgValue;
3477     return false;
3478   }
3479   case PPC::BI__builtin_ppc_mtfsb0:
3480   case PPC::BI__builtin_ppc_mtfsb1:
3481     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3482   case PPC::BI__builtin_ppc_mtfsf:
3483     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3484   case PPC::BI__builtin_ppc_mtfsfi:
3485     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3486            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3487   case PPC::BI__builtin_ppc_alignx:
3488     return SemaBuiltinConstantArgPower2(TheCall, 0);
3489   case PPC::BI__builtin_ppc_rdlam:
3490     return SemaValueIsRunOfOnes(TheCall, 2);
3491   case PPC::BI__builtin_ppc_icbt:
3492   case PPC::BI__builtin_ppc_sthcx:
3493   case PPC::BI__builtin_ppc_stbcx:
3494   case PPC::BI__builtin_ppc_lharx:
3495   case PPC::BI__builtin_ppc_lbarx:
3496     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3497                             diag::err_ppc_builtin_only_on_arch, "8");
3498   case PPC::BI__builtin_vsx_ldrmb:
3499   case PPC::BI__builtin_vsx_strmb:
3500     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3501                             diag::err_ppc_builtin_only_on_arch, "8") ||
3502            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3503   case PPC::BI__builtin_altivec_vcntmbb:
3504   case PPC::BI__builtin_altivec_vcntmbh:
3505   case PPC::BI__builtin_altivec_vcntmbw:
3506   case PPC::BI__builtin_altivec_vcntmbd:
3507     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3508   case PPC::BI__builtin_darn:
3509   case PPC::BI__builtin_darn_raw:
3510   case PPC::BI__builtin_darn_32:
3511     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3512                             diag::err_ppc_builtin_only_on_arch, "9");
3513   case PPC::BI__builtin_vsx_xxgenpcvbm:
3514   case PPC::BI__builtin_vsx_xxgenpcvhm:
3515   case PPC::BI__builtin_vsx_xxgenpcvwm:
3516   case PPC::BI__builtin_vsx_xxgenpcvdm:
3517     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3518   case PPC::BI__builtin_ppc_compare_exp_uo:
3519   case PPC::BI__builtin_ppc_compare_exp_lt:
3520   case PPC::BI__builtin_ppc_compare_exp_gt:
3521   case PPC::BI__builtin_ppc_compare_exp_eq:
3522     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3523                             diag::err_ppc_builtin_only_on_arch, "9") ||
3524            SemaFeatureCheck(*this, TheCall, "vsx",
3525                             diag::err_ppc_builtin_requires_vsx);
3526   case PPC::BI__builtin_ppc_test_data_class: {
3527     // Check if the first argument of the __builtin_ppc_test_data_class call is
3528     // valid. The argument must be either a 'float' or a 'double'.
3529     QualType ArgType = TheCall->getArg(0)->getType();
3530     if (ArgType != QualType(Context.FloatTy) &&
3531         ArgType != QualType(Context.DoubleTy))
3532       return Diag(TheCall->getBeginLoc(),
3533                   diag::err_ppc_invalid_test_data_class_type);
3534     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3535                             diag::err_ppc_builtin_only_on_arch, "9") ||
3536            SemaFeatureCheck(*this, TheCall, "vsx",
3537                             diag::err_ppc_builtin_requires_vsx) ||
3538            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3539   }
3540   case PPC::BI__builtin_ppc_load8r:
3541   case PPC::BI__builtin_ppc_store8r:
3542     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3543                             diag::err_ppc_builtin_only_on_arch, "7");
3544 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3545   case PPC::BI__builtin_##Name:                                                \
3546     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3547 #include "clang/Basic/BuiltinsPPC.def"
3548   }
3549   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3550 }
3551 
3552 // Check if the given type is a non-pointer PPC MMA type. This function is used
3553 // in Sema to prevent invalid uses of restricted PPC MMA types.
3554 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3555   if (Type->isPointerType() || Type->isArrayType())
3556     return false;
3557 
3558   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3559 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3560   if (false
3561 #include "clang/Basic/PPCTypes.def"
3562      ) {
3563     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3564     return true;
3565   }
3566   return false;
3567 }
3568 
3569 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3570                                           CallExpr *TheCall) {
3571   // position of memory order and scope arguments in the builtin
3572   unsigned OrderIndex, ScopeIndex;
3573   switch (BuiltinID) {
3574   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3575   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3576   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3577   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3578     OrderIndex = 2;
3579     ScopeIndex = 3;
3580     break;
3581   case AMDGPU::BI__builtin_amdgcn_fence:
3582     OrderIndex = 0;
3583     ScopeIndex = 1;
3584     break;
3585   default:
3586     return false;
3587   }
3588 
3589   ExprResult Arg = TheCall->getArg(OrderIndex);
3590   auto ArgExpr = Arg.get();
3591   Expr::EvalResult ArgResult;
3592 
3593   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3594     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3595            << ArgExpr->getType();
3596   auto Ord = ArgResult.Val.getInt().getZExtValue();
3597 
3598   // Check validity of memory ordering as per C11 / C++11's memody model.
3599   // Only fence needs check. Atomic dec/inc allow all memory orders.
3600   if (!llvm::isValidAtomicOrderingCABI(Ord))
3601     return Diag(ArgExpr->getBeginLoc(),
3602                 diag::warn_atomic_op_has_invalid_memory_order)
3603            << ArgExpr->getSourceRange();
3604   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3605   case llvm::AtomicOrderingCABI::relaxed:
3606   case llvm::AtomicOrderingCABI::consume:
3607     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3608       return Diag(ArgExpr->getBeginLoc(),
3609                   diag::warn_atomic_op_has_invalid_memory_order)
3610              << ArgExpr->getSourceRange();
3611     break;
3612   case llvm::AtomicOrderingCABI::acquire:
3613   case llvm::AtomicOrderingCABI::release:
3614   case llvm::AtomicOrderingCABI::acq_rel:
3615   case llvm::AtomicOrderingCABI::seq_cst:
3616     break;
3617   }
3618 
3619   Arg = TheCall->getArg(ScopeIndex);
3620   ArgExpr = Arg.get();
3621   Expr::EvalResult ArgResult1;
3622   // Check that sync scope is a constant literal
3623   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3624     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3625            << ArgExpr->getType();
3626 
3627   return false;
3628 }
3629 
3630 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3631   llvm::APSInt Result;
3632 
3633   // We can't check the value of a dependent argument.
3634   Expr *Arg = TheCall->getArg(ArgNum);
3635   if (Arg->isTypeDependent() || Arg->isValueDependent())
3636     return false;
3637 
3638   // Check constant-ness first.
3639   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3640     return true;
3641 
3642   int64_t Val = Result.getSExtValue();
3643   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3644     return false;
3645 
3646   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3647          << Arg->getSourceRange();
3648 }
3649 
3650 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3651                                          unsigned BuiltinID,
3652                                          CallExpr *TheCall) {
3653   // CodeGenFunction can also detect this, but this gives a better error
3654   // message.
3655   bool FeatureMissing = false;
3656   SmallVector<StringRef> ReqFeatures;
3657   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3658   Features.split(ReqFeatures, ',');
3659 
3660   // Check if each required feature is included
3661   for (StringRef F : ReqFeatures) {
3662     if (TI.hasFeature(F))
3663       continue;
3664 
3665     // If the feature is 64bit, alter the string so it will print better in
3666     // the diagnostic.
3667     if (F == "64bit")
3668       F = "RV64";
3669 
3670     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3671     F.consume_front("experimental-");
3672     std::string FeatureStr = F.str();
3673     FeatureStr[0] = std::toupper(FeatureStr[0]);
3674 
3675     // Error message
3676     FeatureMissing = true;
3677     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3678         << TheCall->getSourceRange() << StringRef(FeatureStr);
3679   }
3680 
3681   if (FeatureMissing)
3682     return true;
3683 
3684   switch (BuiltinID) {
3685   case RISCVVector::BI__builtin_rvv_vsetvli:
3686     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3687            CheckRISCVLMUL(TheCall, 2);
3688   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3689     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3690            CheckRISCVLMUL(TheCall, 1);
3691   }
3692 
3693   return false;
3694 }
3695 
3696 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3697                                            CallExpr *TheCall) {
3698   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3699     Expr *Arg = TheCall->getArg(0);
3700     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3701       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3702         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3703                << Arg->getSourceRange();
3704   }
3705 
3706   // For intrinsics which take an immediate value as part of the instruction,
3707   // range check them here.
3708   unsigned i = 0, l = 0, u = 0;
3709   switch (BuiltinID) {
3710   default: return false;
3711   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3712   case SystemZ::BI__builtin_s390_verimb:
3713   case SystemZ::BI__builtin_s390_verimh:
3714   case SystemZ::BI__builtin_s390_verimf:
3715   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3716   case SystemZ::BI__builtin_s390_vfaeb:
3717   case SystemZ::BI__builtin_s390_vfaeh:
3718   case SystemZ::BI__builtin_s390_vfaef:
3719   case SystemZ::BI__builtin_s390_vfaebs:
3720   case SystemZ::BI__builtin_s390_vfaehs:
3721   case SystemZ::BI__builtin_s390_vfaefs:
3722   case SystemZ::BI__builtin_s390_vfaezb:
3723   case SystemZ::BI__builtin_s390_vfaezh:
3724   case SystemZ::BI__builtin_s390_vfaezf:
3725   case SystemZ::BI__builtin_s390_vfaezbs:
3726   case SystemZ::BI__builtin_s390_vfaezhs:
3727   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3728   case SystemZ::BI__builtin_s390_vfisb:
3729   case SystemZ::BI__builtin_s390_vfidb:
3730     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3731            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3732   case SystemZ::BI__builtin_s390_vftcisb:
3733   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3734   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3735   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3736   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3737   case SystemZ::BI__builtin_s390_vstrcb:
3738   case SystemZ::BI__builtin_s390_vstrch:
3739   case SystemZ::BI__builtin_s390_vstrcf:
3740   case SystemZ::BI__builtin_s390_vstrczb:
3741   case SystemZ::BI__builtin_s390_vstrczh:
3742   case SystemZ::BI__builtin_s390_vstrczf:
3743   case SystemZ::BI__builtin_s390_vstrcbs:
3744   case SystemZ::BI__builtin_s390_vstrchs:
3745   case SystemZ::BI__builtin_s390_vstrcfs:
3746   case SystemZ::BI__builtin_s390_vstrczbs:
3747   case SystemZ::BI__builtin_s390_vstrczhs:
3748   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3749   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3750   case SystemZ::BI__builtin_s390_vfminsb:
3751   case SystemZ::BI__builtin_s390_vfmaxsb:
3752   case SystemZ::BI__builtin_s390_vfmindb:
3753   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3754   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3755   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3756   case SystemZ::BI__builtin_s390_vclfnhs:
3757   case SystemZ::BI__builtin_s390_vclfnls:
3758   case SystemZ::BI__builtin_s390_vcfn:
3759   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3760   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3761   }
3762   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3763 }
3764 
3765 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3766 /// This checks that the target supports __builtin_cpu_supports and
3767 /// that the string argument is constant and valid.
3768 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3769                                    CallExpr *TheCall) {
3770   Expr *Arg = TheCall->getArg(0);
3771 
3772   // Check if the argument is a string literal.
3773   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3774     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3775            << Arg->getSourceRange();
3776 
3777   // Check the contents of the string.
3778   StringRef Feature =
3779       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3780   if (!TI.validateCpuSupports(Feature))
3781     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3782            << Arg->getSourceRange();
3783   return false;
3784 }
3785 
3786 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3787 /// This checks that the target supports __builtin_cpu_is and
3788 /// that the string argument is constant and valid.
3789 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3790   Expr *Arg = TheCall->getArg(0);
3791 
3792   // Check if the argument is a string literal.
3793   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3794     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3795            << Arg->getSourceRange();
3796 
3797   // Check the contents of the string.
3798   StringRef Feature =
3799       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3800   if (!TI.validateCpuIs(Feature))
3801     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3802            << Arg->getSourceRange();
3803   return false;
3804 }
3805 
3806 // Check if the rounding mode is legal.
3807 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3808   // Indicates if this instruction has rounding control or just SAE.
3809   bool HasRC = false;
3810 
3811   unsigned ArgNum = 0;
3812   switch (BuiltinID) {
3813   default:
3814     return false;
3815   case X86::BI__builtin_ia32_vcvttsd2si32:
3816   case X86::BI__builtin_ia32_vcvttsd2si64:
3817   case X86::BI__builtin_ia32_vcvttsd2usi32:
3818   case X86::BI__builtin_ia32_vcvttsd2usi64:
3819   case X86::BI__builtin_ia32_vcvttss2si32:
3820   case X86::BI__builtin_ia32_vcvttss2si64:
3821   case X86::BI__builtin_ia32_vcvttss2usi32:
3822   case X86::BI__builtin_ia32_vcvttss2usi64:
3823   case X86::BI__builtin_ia32_vcvttsh2si32:
3824   case X86::BI__builtin_ia32_vcvttsh2si64:
3825   case X86::BI__builtin_ia32_vcvttsh2usi32:
3826   case X86::BI__builtin_ia32_vcvttsh2usi64:
3827     ArgNum = 1;
3828     break;
3829   case X86::BI__builtin_ia32_maxpd512:
3830   case X86::BI__builtin_ia32_maxps512:
3831   case X86::BI__builtin_ia32_minpd512:
3832   case X86::BI__builtin_ia32_minps512:
3833   case X86::BI__builtin_ia32_maxph512:
3834   case X86::BI__builtin_ia32_minph512:
3835     ArgNum = 2;
3836     break;
3837   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3838   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3839   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3840   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3841   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3842   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3843   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3844   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3845   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3846   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3847   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3848   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3849   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3850   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3851   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3852   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3853   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3854   case X86::BI__builtin_ia32_exp2pd_mask:
3855   case X86::BI__builtin_ia32_exp2ps_mask:
3856   case X86::BI__builtin_ia32_getexppd512_mask:
3857   case X86::BI__builtin_ia32_getexpps512_mask:
3858   case X86::BI__builtin_ia32_getexpph512_mask:
3859   case X86::BI__builtin_ia32_rcp28pd_mask:
3860   case X86::BI__builtin_ia32_rcp28ps_mask:
3861   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3862   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3863   case X86::BI__builtin_ia32_vcomisd:
3864   case X86::BI__builtin_ia32_vcomiss:
3865   case X86::BI__builtin_ia32_vcomish:
3866   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3867     ArgNum = 3;
3868     break;
3869   case X86::BI__builtin_ia32_cmppd512_mask:
3870   case X86::BI__builtin_ia32_cmpps512_mask:
3871   case X86::BI__builtin_ia32_cmpsd_mask:
3872   case X86::BI__builtin_ia32_cmpss_mask:
3873   case X86::BI__builtin_ia32_cmpsh_mask:
3874   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3875   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3876   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3877   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3878   case X86::BI__builtin_ia32_getexpss128_round_mask:
3879   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3880   case X86::BI__builtin_ia32_getmantpd512_mask:
3881   case X86::BI__builtin_ia32_getmantps512_mask:
3882   case X86::BI__builtin_ia32_getmantph512_mask:
3883   case X86::BI__builtin_ia32_maxsd_round_mask:
3884   case X86::BI__builtin_ia32_maxss_round_mask:
3885   case X86::BI__builtin_ia32_maxsh_round_mask:
3886   case X86::BI__builtin_ia32_minsd_round_mask:
3887   case X86::BI__builtin_ia32_minss_round_mask:
3888   case X86::BI__builtin_ia32_minsh_round_mask:
3889   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3890   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3891   case X86::BI__builtin_ia32_reducepd512_mask:
3892   case X86::BI__builtin_ia32_reduceps512_mask:
3893   case X86::BI__builtin_ia32_reduceph512_mask:
3894   case X86::BI__builtin_ia32_rndscalepd_mask:
3895   case X86::BI__builtin_ia32_rndscaleps_mask:
3896   case X86::BI__builtin_ia32_rndscaleph_mask:
3897   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3898   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3899     ArgNum = 4;
3900     break;
3901   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3902   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3903   case X86::BI__builtin_ia32_fixupimmps512_mask:
3904   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3905   case X86::BI__builtin_ia32_fixupimmsd_mask:
3906   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3907   case X86::BI__builtin_ia32_fixupimmss_mask:
3908   case X86::BI__builtin_ia32_fixupimmss_maskz:
3909   case X86::BI__builtin_ia32_getmantsd_round_mask:
3910   case X86::BI__builtin_ia32_getmantss_round_mask:
3911   case X86::BI__builtin_ia32_getmantsh_round_mask:
3912   case X86::BI__builtin_ia32_rangepd512_mask:
3913   case X86::BI__builtin_ia32_rangeps512_mask:
3914   case X86::BI__builtin_ia32_rangesd128_round_mask:
3915   case X86::BI__builtin_ia32_rangess128_round_mask:
3916   case X86::BI__builtin_ia32_reducesd_mask:
3917   case X86::BI__builtin_ia32_reducess_mask:
3918   case X86::BI__builtin_ia32_reducesh_mask:
3919   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3920   case X86::BI__builtin_ia32_rndscaless_round_mask:
3921   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3922     ArgNum = 5;
3923     break;
3924   case X86::BI__builtin_ia32_vcvtsd2si64:
3925   case X86::BI__builtin_ia32_vcvtsd2si32:
3926   case X86::BI__builtin_ia32_vcvtsd2usi32:
3927   case X86::BI__builtin_ia32_vcvtsd2usi64:
3928   case X86::BI__builtin_ia32_vcvtss2si32:
3929   case X86::BI__builtin_ia32_vcvtss2si64:
3930   case X86::BI__builtin_ia32_vcvtss2usi32:
3931   case X86::BI__builtin_ia32_vcvtss2usi64:
3932   case X86::BI__builtin_ia32_vcvtsh2si32:
3933   case X86::BI__builtin_ia32_vcvtsh2si64:
3934   case X86::BI__builtin_ia32_vcvtsh2usi32:
3935   case X86::BI__builtin_ia32_vcvtsh2usi64:
3936   case X86::BI__builtin_ia32_sqrtpd512:
3937   case X86::BI__builtin_ia32_sqrtps512:
3938   case X86::BI__builtin_ia32_sqrtph512:
3939     ArgNum = 1;
3940     HasRC = true;
3941     break;
3942   case X86::BI__builtin_ia32_addph512:
3943   case X86::BI__builtin_ia32_divph512:
3944   case X86::BI__builtin_ia32_mulph512:
3945   case X86::BI__builtin_ia32_subph512:
3946   case X86::BI__builtin_ia32_addpd512:
3947   case X86::BI__builtin_ia32_addps512:
3948   case X86::BI__builtin_ia32_divpd512:
3949   case X86::BI__builtin_ia32_divps512:
3950   case X86::BI__builtin_ia32_mulpd512:
3951   case X86::BI__builtin_ia32_mulps512:
3952   case X86::BI__builtin_ia32_subpd512:
3953   case X86::BI__builtin_ia32_subps512:
3954   case X86::BI__builtin_ia32_cvtsi2sd64:
3955   case X86::BI__builtin_ia32_cvtsi2ss32:
3956   case X86::BI__builtin_ia32_cvtsi2ss64:
3957   case X86::BI__builtin_ia32_cvtusi2sd64:
3958   case X86::BI__builtin_ia32_cvtusi2ss32:
3959   case X86::BI__builtin_ia32_cvtusi2ss64:
3960   case X86::BI__builtin_ia32_vcvtusi2sh:
3961   case X86::BI__builtin_ia32_vcvtusi642sh:
3962   case X86::BI__builtin_ia32_vcvtsi2sh:
3963   case X86::BI__builtin_ia32_vcvtsi642sh:
3964     ArgNum = 2;
3965     HasRC = true;
3966     break;
3967   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3968   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3969   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
3970   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
3971   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3972   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3973   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3974   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3975   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3976   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3977   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3978   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3979   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3980   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3981   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3982   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3983   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3984   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
3985   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
3986   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
3987   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
3988   case X86::BI__builtin_ia32_vcvtph2w512_mask:
3989   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
3990   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
3991   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
3992   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
3993   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
3994   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
3995   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
3996     ArgNum = 3;
3997     HasRC = true;
3998     break;
3999   case X86::BI__builtin_ia32_addsh_round_mask:
4000   case X86::BI__builtin_ia32_addss_round_mask:
4001   case X86::BI__builtin_ia32_addsd_round_mask:
4002   case X86::BI__builtin_ia32_divsh_round_mask:
4003   case X86::BI__builtin_ia32_divss_round_mask:
4004   case X86::BI__builtin_ia32_divsd_round_mask:
4005   case X86::BI__builtin_ia32_mulsh_round_mask:
4006   case X86::BI__builtin_ia32_mulss_round_mask:
4007   case X86::BI__builtin_ia32_mulsd_round_mask:
4008   case X86::BI__builtin_ia32_subsh_round_mask:
4009   case X86::BI__builtin_ia32_subss_round_mask:
4010   case X86::BI__builtin_ia32_subsd_round_mask:
4011   case X86::BI__builtin_ia32_scalefph512_mask:
4012   case X86::BI__builtin_ia32_scalefpd512_mask:
4013   case X86::BI__builtin_ia32_scalefps512_mask:
4014   case X86::BI__builtin_ia32_scalefsd_round_mask:
4015   case X86::BI__builtin_ia32_scalefss_round_mask:
4016   case X86::BI__builtin_ia32_scalefsh_round_mask:
4017   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
4018   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
4019   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
4020   case X86::BI__builtin_ia32_sqrtsd_round_mask:
4021   case X86::BI__builtin_ia32_sqrtss_round_mask:
4022   case X86::BI__builtin_ia32_sqrtsh_round_mask:
4023   case X86::BI__builtin_ia32_vfmaddsd3_mask:
4024   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
4025   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4026   case X86::BI__builtin_ia32_vfmaddss3_mask:
4027   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4028   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4029   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4030   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4031   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4032   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4033   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4034   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4035   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4036   case X86::BI__builtin_ia32_vfmaddps512_mask:
4037   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4038   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4039   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4040   case X86::BI__builtin_ia32_vfmaddph512_mask:
4041   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4042   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4043   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4044   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4045   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4046   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4047   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4048   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4049   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4050   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4051   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4052   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4053   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4054   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4055   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4056   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4057   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4058   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4059   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4060   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4061   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4062   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4063   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4064   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4065   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4066   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4067   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4068   case X86::BI__builtin_ia32_vfmulcsh_mask:
4069   case X86::BI__builtin_ia32_vfmulcph512_mask:
4070   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4071   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4072     ArgNum = 4;
4073     HasRC = true;
4074     break;
4075   }
4076 
4077   llvm::APSInt Result;
4078 
4079   // We can't check the value of a dependent argument.
4080   Expr *Arg = TheCall->getArg(ArgNum);
4081   if (Arg->isTypeDependent() || Arg->isValueDependent())
4082     return false;
4083 
4084   // Check constant-ness first.
4085   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4086     return true;
4087 
4088   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4089   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4090   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4091   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4092   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4093       Result == 8/*ROUND_NO_EXC*/ ||
4094       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4095       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4096     return false;
4097 
4098   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4099          << Arg->getSourceRange();
4100 }
4101 
4102 // Check if the gather/scatter scale is legal.
4103 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4104                                              CallExpr *TheCall) {
4105   unsigned ArgNum = 0;
4106   switch (BuiltinID) {
4107   default:
4108     return false;
4109   case X86::BI__builtin_ia32_gatherpfdpd:
4110   case X86::BI__builtin_ia32_gatherpfdps:
4111   case X86::BI__builtin_ia32_gatherpfqpd:
4112   case X86::BI__builtin_ia32_gatherpfqps:
4113   case X86::BI__builtin_ia32_scatterpfdpd:
4114   case X86::BI__builtin_ia32_scatterpfdps:
4115   case X86::BI__builtin_ia32_scatterpfqpd:
4116   case X86::BI__builtin_ia32_scatterpfqps:
4117     ArgNum = 3;
4118     break;
4119   case X86::BI__builtin_ia32_gatherd_pd:
4120   case X86::BI__builtin_ia32_gatherd_pd256:
4121   case X86::BI__builtin_ia32_gatherq_pd:
4122   case X86::BI__builtin_ia32_gatherq_pd256:
4123   case X86::BI__builtin_ia32_gatherd_ps:
4124   case X86::BI__builtin_ia32_gatherd_ps256:
4125   case X86::BI__builtin_ia32_gatherq_ps:
4126   case X86::BI__builtin_ia32_gatherq_ps256:
4127   case X86::BI__builtin_ia32_gatherd_q:
4128   case X86::BI__builtin_ia32_gatherd_q256:
4129   case X86::BI__builtin_ia32_gatherq_q:
4130   case X86::BI__builtin_ia32_gatherq_q256:
4131   case X86::BI__builtin_ia32_gatherd_d:
4132   case X86::BI__builtin_ia32_gatherd_d256:
4133   case X86::BI__builtin_ia32_gatherq_d:
4134   case X86::BI__builtin_ia32_gatherq_d256:
4135   case X86::BI__builtin_ia32_gather3div2df:
4136   case X86::BI__builtin_ia32_gather3div2di:
4137   case X86::BI__builtin_ia32_gather3div4df:
4138   case X86::BI__builtin_ia32_gather3div4di:
4139   case X86::BI__builtin_ia32_gather3div4sf:
4140   case X86::BI__builtin_ia32_gather3div4si:
4141   case X86::BI__builtin_ia32_gather3div8sf:
4142   case X86::BI__builtin_ia32_gather3div8si:
4143   case X86::BI__builtin_ia32_gather3siv2df:
4144   case X86::BI__builtin_ia32_gather3siv2di:
4145   case X86::BI__builtin_ia32_gather3siv4df:
4146   case X86::BI__builtin_ia32_gather3siv4di:
4147   case X86::BI__builtin_ia32_gather3siv4sf:
4148   case X86::BI__builtin_ia32_gather3siv4si:
4149   case X86::BI__builtin_ia32_gather3siv8sf:
4150   case X86::BI__builtin_ia32_gather3siv8si:
4151   case X86::BI__builtin_ia32_gathersiv8df:
4152   case X86::BI__builtin_ia32_gathersiv16sf:
4153   case X86::BI__builtin_ia32_gatherdiv8df:
4154   case X86::BI__builtin_ia32_gatherdiv16sf:
4155   case X86::BI__builtin_ia32_gathersiv8di:
4156   case X86::BI__builtin_ia32_gathersiv16si:
4157   case X86::BI__builtin_ia32_gatherdiv8di:
4158   case X86::BI__builtin_ia32_gatherdiv16si:
4159   case X86::BI__builtin_ia32_scatterdiv2df:
4160   case X86::BI__builtin_ia32_scatterdiv2di:
4161   case X86::BI__builtin_ia32_scatterdiv4df:
4162   case X86::BI__builtin_ia32_scatterdiv4di:
4163   case X86::BI__builtin_ia32_scatterdiv4sf:
4164   case X86::BI__builtin_ia32_scatterdiv4si:
4165   case X86::BI__builtin_ia32_scatterdiv8sf:
4166   case X86::BI__builtin_ia32_scatterdiv8si:
4167   case X86::BI__builtin_ia32_scattersiv2df:
4168   case X86::BI__builtin_ia32_scattersiv2di:
4169   case X86::BI__builtin_ia32_scattersiv4df:
4170   case X86::BI__builtin_ia32_scattersiv4di:
4171   case X86::BI__builtin_ia32_scattersiv4sf:
4172   case X86::BI__builtin_ia32_scattersiv4si:
4173   case X86::BI__builtin_ia32_scattersiv8sf:
4174   case X86::BI__builtin_ia32_scattersiv8si:
4175   case X86::BI__builtin_ia32_scattersiv8df:
4176   case X86::BI__builtin_ia32_scattersiv16sf:
4177   case X86::BI__builtin_ia32_scatterdiv8df:
4178   case X86::BI__builtin_ia32_scatterdiv16sf:
4179   case X86::BI__builtin_ia32_scattersiv8di:
4180   case X86::BI__builtin_ia32_scattersiv16si:
4181   case X86::BI__builtin_ia32_scatterdiv8di:
4182   case X86::BI__builtin_ia32_scatterdiv16si:
4183     ArgNum = 4;
4184     break;
4185   }
4186 
4187   llvm::APSInt Result;
4188 
4189   // We can't check the value of a dependent argument.
4190   Expr *Arg = TheCall->getArg(ArgNum);
4191   if (Arg->isTypeDependent() || Arg->isValueDependent())
4192     return false;
4193 
4194   // Check constant-ness first.
4195   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4196     return true;
4197 
4198   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4199     return false;
4200 
4201   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4202          << Arg->getSourceRange();
4203 }
4204 
4205 enum { TileRegLow = 0, TileRegHigh = 7 };
4206 
4207 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4208                                              ArrayRef<int> ArgNums) {
4209   for (int ArgNum : ArgNums) {
4210     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4211       return true;
4212   }
4213   return false;
4214 }
4215 
4216 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4217                                         ArrayRef<int> ArgNums) {
4218   // Because the max number of tile register is TileRegHigh + 1, so here we use
4219   // each bit to represent the usage of them in bitset.
4220   std::bitset<TileRegHigh + 1> ArgValues;
4221   for (int ArgNum : ArgNums) {
4222     Expr *Arg = TheCall->getArg(ArgNum);
4223     if (Arg->isTypeDependent() || Arg->isValueDependent())
4224       continue;
4225 
4226     llvm::APSInt Result;
4227     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4228       return true;
4229     int ArgExtValue = Result.getExtValue();
4230     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4231            "Incorrect tile register num.");
4232     if (ArgValues.test(ArgExtValue))
4233       return Diag(TheCall->getBeginLoc(),
4234                   diag::err_x86_builtin_tile_arg_duplicate)
4235              << TheCall->getArg(ArgNum)->getSourceRange();
4236     ArgValues.set(ArgExtValue);
4237   }
4238   return false;
4239 }
4240 
4241 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4242                                                 ArrayRef<int> ArgNums) {
4243   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4244          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4245 }
4246 
4247 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4248   switch (BuiltinID) {
4249   default:
4250     return false;
4251   case X86::BI__builtin_ia32_tileloadd64:
4252   case X86::BI__builtin_ia32_tileloaddt164:
4253   case X86::BI__builtin_ia32_tilestored64:
4254   case X86::BI__builtin_ia32_tilezero:
4255     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4256   case X86::BI__builtin_ia32_tdpbssd:
4257   case X86::BI__builtin_ia32_tdpbsud:
4258   case X86::BI__builtin_ia32_tdpbusd:
4259   case X86::BI__builtin_ia32_tdpbuud:
4260   case X86::BI__builtin_ia32_tdpbf16ps:
4261     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4262   }
4263 }
4264 static bool isX86_32Builtin(unsigned BuiltinID) {
4265   // These builtins only work on x86-32 targets.
4266   switch (BuiltinID) {
4267   case X86::BI__builtin_ia32_readeflags_u32:
4268   case X86::BI__builtin_ia32_writeeflags_u32:
4269     return true;
4270   }
4271 
4272   return false;
4273 }
4274 
4275 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4276                                        CallExpr *TheCall) {
4277   if (BuiltinID == X86::BI__builtin_cpu_supports)
4278     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4279 
4280   if (BuiltinID == X86::BI__builtin_cpu_is)
4281     return SemaBuiltinCpuIs(*this, TI, TheCall);
4282 
4283   // Check for 32-bit only builtins on a 64-bit target.
4284   const llvm::Triple &TT = TI.getTriple();
4285   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4286     return Diag(TheCall->getCallee()->getBeginLoc(),
4287                 diag::err_32_bit_builtin_64_bit_tgt);
4288 
4289   // If the intrinsic has rounding or SAE make sure its valid.
4290   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4291     return true;
4292 
4293   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4294   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4295     return true;
4296 
4297   // If the intrinsic has a tile arguments, make sure they are valid.
4298   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4299     return true;
4300 
4301   // For intrinsics which take an immediate value as part of the instruction,
4302   // range check them here.
4303   int i = 0, l = 0, u = 0;
4304   switch (BuiltinID) {
4305   default:
4306     return false;
4307   case X86::BI__builtin_ia32_vec_ext_v2si:
4308   case X86::BI__builtin_ia32_vec_ext_v2di:
4309   case X86::BI__builtin_ia32_vextractf128_pd256:
4310   case X86::BI__builtin_ia32_vextractf128_ps256:
4311   case X86::BI__builtin_ia32_vextractf128_si256:
4312   case X86::BI__builtin_ia32_extract128i256:
4313   case X86::BI__builtin_ia32_extractf64x4_mask:
4314   case X86::BI__builtin_ia32_extracti64x4_mask:
4315   case X86::BI__builtin_ia32_extractf32x8_mask:
4316   case X86::BI__builtin_ia32_extracti32x8_mask:
4317   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4318   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4319   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4320   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4321     i = 1; l = 0; u = 1;
4322     break;
4323   case X86::BI__builtin_ia32_vec_set_v2di:
4324   case X86::BI__builtin_ia32_vinsertf128_pd256:
4325   case X86::BI__builtin_ia32_vinsertf128_ps256:
4326   case X86::BI__builtin_ia32_vinsertf128_si256:
4327   case X86::BI__builtin_ia32_insert128i256:
4328   case X86::BI__builtin_ia32_insertf32x8:
4329   case X86::BI__builtin_ia32_inserti32x8:
4330   case X86::BI__builtin_ia32_insertf64x4:
4331   case X86::BI__builtin_ia32_inserti64x4:
4332   case X86::BI__builtin_ia32_insertf64x2_256:
4333   case X86::BI__builtin_ia32_inserti64x2_256:
4334   case X86::BI__builtin_ia32_insertf32x4_256:
4335   case X86::BI__builtin_ia32_inserti32x4_256:
4336     i = 2; l = 0; u = 1;
4337     break;
4338   case X86::BI__builtin_ia32_vpermilpd:
4339   case X86::BI__builtin_ia32_vec_ext_v4hi:
4340   case X86::BI__builtin_ia32_vec_ext_v4si:
4341   case X86::BI__builtin_ia32_vec_ext_v4sf:
4342   case X86::BI__builtin_ia32_vec_ext_v4di:
4343   case X86::BI__builtin_ia32_extractf32x4_mask:
4344   case X86::BI__builtin_ia32_extracti32x4_mask:
4345   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4346   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4347     i = 1; l = 0; u = 3;
4348     break;
4349   case X86::BI_mm_prefetch:
4350   case X86::BI__builtin_ia32_vec_ext_v8hi:
4351   case X86::BI__builtin_ia32_vec_ext_v8si:
4352     i = 1; l = 0; u = 7;
4353     break;
4354   case X86::BI__builtin_ia32_sha1rnds4:
4355   case X86::BI__builtin_ia32_blendpd:
4356   case X86::BI__builtin_ia32_shufpd:
4357   case X86::BI__builtin_ia32_vec_set_v4hi:
4358   case X86::BI__builtin_ia32_vec_set_v4si:
4359   case X86::BI__builtin_ia32_vec_set_v4di:
4360   case X86::BI__builtin_ia32_shuf_f32x4_256:
4361   case X86::BI__builtin_ia32_shuf_f64x2_256:
4362   case X86::BI__builtin_ia32_shuf_i32x4_256:
4363   case X86::BI__builtin_ia32_shuf_i64x2_256:
4364   case X86::BI__builtin_ia32_insertf64x2_512:
4365   case X86::BI__builtin_ia32_inserti64x2_512:
4366   case X86::BI__builtin_ia32_insertf32x4:
4367   case X86::BI__builtin_ia32_inserti32x4:
4368     i = 2; l = 0; u = 3;
4369     break;
4370   case X86::BI__builtin_ia32_vpermil2pd:
4371   case X86::BI__builtin_ia32_vpermil2pd256:
4372   case X86::BI__builtin_ia32_vpermil2ps:
4373   case X86::BI__builtin_ia32_vpermil2ps256:
4374     i = 3; l = 0; u = 3;
4375     break;
4376   case X86::BI__builtin_ia32_cmpb128_mask:
4377   case X86::BI__builtin_ia32_cmpw128_mask:
4378   case X86::BI__builtin_ia32_cmpd128_mask:
4379   case X86::BI__builtin_ia32_cmpq128_mask:
4380   case X86::BI__builtin_ia32_cmpb256_mask:
4381   case X86::BI__builtin_ia32_cmpw256_mask:
4382   case X86::BI__builtin_ia32_cmpd256_mask:
4383   case X86::BI__builtin_ia32_cmpq256_mask:
4384   case X86::BI__builtin_ia32_cmpb512_mask:
4385   case X86::BI__builtin_ia32_cmpw512_mask:
4386   case X86::BI__builtin_ia32_cmpd512_mask:
4387   case X86::BI__builtin_ia32_cmpq512_mask:
4388   case X86::BI__builtin_ia32_ucmpb128_mask:
4389   case X86::BI__builtin_ia32_ucmpw128_mask:
4390   case X86::BI__builtin_ia32_ucmpd128_mask:
4391   case X86::BI__builtin_ia32_ucmpq128_mask:
4392   case X86::BI__builtin_ia32_ucmpb256_mask:
4393   case X86::BI__builtin_ia32_ucmpw256_mask:
4394   case X86::BI__builtin_ia32_ucmpd256_mask:
4395   case X86::BI__builtin_ia32_ucmpq256_mask:
4396   case X86::BI__builtin_ia32_ucmpb512_mask:
4397   case X86::BI__builtin_ia32_ucmpw512_mask:
4398   case X86::BI__builtin_ia32_ucmpd512_mask:
4399   case X86::BI__builtin_ia32_ucmpq512_mask:
4400   case X86::BI__builtin_ia32_vpcomub:
4401   case X86::BI__builtin_ia32_vpcomuw:
4402   case X86::BI__builtin_ia32_vpcomud:
4403   case X86::BI__builtin_ia32_vpcomuq:
4404   case X86::BI__builtin_ia32_vpcomb:
4405   case X86::BI__builtin_ia32_vpcomw:
4406   case X86::BI__builtin_ia32_vpcomd:
4407   case X86::BI__builtin_ia32_vpcomq:
4408   case X86::BI__builtin_ia32_vec_set_v8hi:
4409   case X86::BI__builtin_ia32_vec_set_v8si:
4410     i = 2; l = 0; u = 7;
4411     break;
4412   case X86::BI__builtin_ia32_vpermilpd256:
4413   case X86::BI__builtin_ia32_roundps:
4414   case X86::BI__builtin_ia32_roundpd:
4415   case X86::BI__builtin_ia32_roundps256:
4416   case X86::BI__builtin_ia32_roundpd256:
4417   case X86::BI__builtin_ia32_getmantpd128_mask:
4418   case X86::BI__builtin_ia32_getmantpd256_mask:
4419   case X86::BI__builtin_ia32_getmantps128_mask:
4420   case X86::BI__builtin_ia32_getmantps256_mask:
4421   case X86::BI__builtin_ia32_getmantpd512_mask:
4422   case X86::BI__builtin_ia32_getmantps512_mask:
4423   case X86::BI__builtin_ia32_getmantph128_mask:
4424   case X86::BI__builtin_ia32_getmantph256_mask:
4425   case X86::BI__builtin_ia32_getmantph512_mask:
4426   case X86::BI__builtin_ia32_vec_ext_v16qi:
4427   case X86::BI__builtin_ia32_vec_ext_v16hi:
4428     i = 1; l = 0; u = 15;
4429     break;
4430   case X86::BI__builtin_ia32_pblendd128:
4431   case X86::BI__builtin_ia32_blendps:
4432   case X86::BI__builtin_ia32_blendpd256:
4433   case X86::BI__builtin_ia32_shufpd256:
4434   case X86::BI__builtin_ia32_roundss:
4435   case X86::BI__builtin_ia32_roundsd:
4436   case X86::BI__builtin_ia32_rangepd128_mask:
4437   case X86::BI__builtin_ia32_rangepd256_mask:
4438   case X86::BI__builtin_ia32_rangepd512_mask:
4439   case X86::BI__builtin_ia32_rangeps128_mask:
4440   case X86::BI__builtin_ia32_rangeps256_mask:
4441   case X86::BI__builtin_ia32_rangeps512_mask:
4442   case X86::BI__builtin_ia32_getmantsd_round_mask:
4443   case X86::BI__builtin_ia32_getmantss_round_mask:
4444   case X86::BI__builtin_ia32_getmantsh_round_mask:
4445   case X86::BI__builtin_ia32_vec_set_v16qi:
4446   case X86::BI__builtin_ia32_vec_set_v16hi:
4447     i = 2; l = 0; u = 15;
4448     break;
4449   case X86::BI__builtin_ia32_vec_ext_v32qi:
4450     i = 1; l = 0; u = 31;
4451     break;
4452   case X86::BI__builtin_ia32_cmpps:
4453   case X86::BI__builtin_ia32_cmpss:
4454   case X86::BI__builtin_ia32_cmppd:
4455   case X86::BI__builtin_ia32_cmpsd:
4456   case X86::BI__builtin_ia32_cmpps256:
4457   case X86::BI__builtin_ia32_cmppd256:
4458   case X86::BI__builtin_ia32_cmpps128_mask:
4459   case X86::BI__builtin_ia32_cmppd128_mask:
4460   case X86::BI__builtin_ia32_cmpps256_mask:
4461   case X86::BI__builtin_ia32_cmppd256_mask:
4462   case X86::BI__builtin_ia32_cmpps512_mask:
4463   case X86::BI__builtin_ia32_cmppd512_mask:
4464   case X86::BI__builtin_ia32_cmpsd_mask:
4465   case X86::BI__builtin_ia32_cmpss_mask:
4466   case X86::BI__builtin_ia32_vec_set_v32qi:
4467     i = 2; l = 0; u = 31;
4468     break;
4469   case X86::BI__builtin_ia32_permdf256:
4470   case X86::BI__builtin_ia32_permdi256:
4471   case X86::BI__builtin_ia32_permdf512:
4472   case X86::BI__builtin_ia32_permdi512:
4473   case X86::BI__builtin_ia32_vpermilps:
4474   case X86::BI__builtin_ia32_vpermilps256:
4475   case X86::BI__builtin_ia32_vpermilpd512:
4476   case X86::BI__builtin_ia32_vpermilps512:
4477   case X86::BI__builtin_ia32_pshufd:
4478   case X86::BI__builtin_ia32_pshufd256:
4479   case X86::BI__builtin_ia32_pshufd512:
4480   case X86::BI__builtin_ia32_pshufhw:
4481   case X86::BI__builtin_ia32_pshufhw256:
4482   case X86::BI__builtin_ia32_pshufhw512:
4483   case X86::BI__builtin_ia32_pshuflw:
4484   case X86::BI__builtin_ia32_pshuflw256:
4485   case X86::BI__builtin_ia32_pshuflw512:
4486   case X86::BI__builtin_ia32_vcvtps2ph:
4487   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4488   case X86::BI__builtin_ia32_vcvtps2ph256:
4489   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4490   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4491   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4492   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4493   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4494   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4495   case X86::BI__builtin_ia32_rndscaleps_mask:
4496   case X86::BI__builtin_ia32_rndscalepd_mask:
4497   case X86::BI__builtin_ia32_rndscaleph_mask:
4498   case X86::BI__builtin_ia32_reducepd128_mask:
4499   case X86::BI__builtin_ia32_reducepd256_mask:
4500   case X86::BI__builtin_ia32_reducepd512_mask:
4501   case X86::BI__builtin_ia32_reduceps128_mask:
4502   case X86::BI__builtin_ia32_reduceps256_mask:
4503   case X86::BI__builtin_ia32_reduceps512_mask:
4504   case X86::BI__builtin_ia32_reduceph128_mask:
4505   case X86::BI__builtin_ia32_reduceph256_mask:
4506   case X86::BI__builtin_ia32_reduceph512_mask:
4507   case X86::BI__builtin_ia32_prold512:
4508   case X86::BI__builtin_ia32_prolq512:
4509   case X86::BI__builtin_ia32_prold128:
4510   case X86::BI__builtin_ia32_prold256:
4511   case X86::BI__builtin_ia32_prolq128:
4512   case X86::BI__builtin_ia32_prolq256:
4513   case X86::BI__builtin_ia32_prord512:
4514   case X86::BI__builtin_ia32_prorq512:
4515   case X86::BI__builtin_ia32_prord128:
4516   case X86::BI__builtin_ia32_prord256:
4517   case X86::BI__builtin_ia32_prorq128:
4518   case X86::BI__builtin_ia32_prorq256:
4519   case X86::BI__builtin_ia32_fpclasspd128_mask:
4520   case X86::BI__builtin_ia32_fpclasspd256_mask:
4521   case X86::BI__builtin_ia32_fpclassps128_mask:
4522   case X86::BI__builtin_ia32_fpclassps256_mask:
4523   case X86::BI__builtin_ia32_fpclassps512_mask:
4524   case X86::BI__builtin_ia32_fpclasspd512_mask:
4525   case X86::BI__builtin_ia32_fpclassph128_mask:
4526   case X86::BI__builtin_ia32_fpclassph256_mask:
4527   case X86::BI__builtin_ia32_fpclassph512_mask:
4528   case X86::BI__builtin_ia32_fpclasssd_mask:
4529   case X86::BI__builtin_ia32_fpclassss_mask:
4530   case X86::BI__builtin_ia32_fpclasssh_mask:
4531   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4532   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4533   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4534   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4535   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4536   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4537   case X86::BI__builtin_ia32_kshiftliqi:
4538   case X86::BI__builtin_ia32_kshiftlihi:
4539   case X86::BI__builtin_ia32_kshiftlisi:
4540   case X86::BI__builtin_ia32_kshiftlidi:
4541   case X86::BI__builtin_ia32_kshiftriqi:
4542   case X86::BI__builtin_ia32_kshiftrihi:
4543   case X86::BI__builtin_ia32_kshiftrisi:
4544   case X86::BI__builtin_ia32_kshiftridi:
4545     i = 1; l = 0; u = 255;
4546     break;
4547   case X86::BI__builtin_ia32_vperm2f128_pd256:
4548   case X86::BI__builtin_ia32_vperm2f128_ps256:
4549   case X86::BI__builtin_ia32_vperm2f128_si256:
4550   case X86::BI__builtin_ia32_permti256:
4551   case X86::BI__builtin_ia32_pblendw128:
4552   case X86::BI__builtin_ia32_pblendw256:
4553   case X86::BI__builtin_ia32_blendps256:
4554   case X86::BI__builtin_ia32_pblendd256:
4555   case X86::BI__builtin_ia32_palignr128:
4556   case X86::BI__builtin_ia32_palignr256:
4557   case X86::BI__builtin_ia32_palignr512:
4558   case X86::BI__builtin_ia32_alignq512:
4559   case X86::BI__builtin_ia32_alignd512:
4560   case X86::BI__builtin_ia32_alignd128:
4561   case X86::BI__builtin_ia32_alignd256:
4562   case X86::BI__builtin_ia32_alignq128:
4563   case X86::BI__builtin_ia32_alignq256:
4564   case X86::BI__builtin_ia32_vcomisd:
4565   case X86::BI__builtin_ia32_vcomiss:
4566   case X86::BI__builtin_ia32_shuf_f32x4:
4567   case X86::BI__builtin_ia32_shuf_f64x2:
4568   case X86::BI__builtin_ia32_shuf_i32x4:
4569   case X86::BI__builtin_ia32_shuf_i64x2:
4570   case X86::BI__builtin_ia32_shufpd512:
4571   case X86::BI__builtin_ia32_shufps:
4572   case X86::BI__builtin_ia32_shufps256:
4573   case X86::BI__builtin_ia32_shufps512:
4574   case X86::BI__builtin_ia32_dbpsadbw128:
4575   case X86::BI__builtin_ia32_dbpsadbw256:
4576   case X86::BI__builtin_ia32_dbpsadbw512:
4577   case X86::BI__builtin_ia32_vpshldd128:
4578   case X86::BI__builtin_ia32_vpshldd256:
4579   case X86::BI__builtin_ia32_vpshldd512:
4580   case X86::BI__builtin_ia32_vpshldq128:
4581   case X86::BI__builtin_ia32_vpshldq256:
4582   case X86::BI__builtin_ia32_vpshldq512:
4583   case X86::BI__builtin_ia32_vpshldw128:
4584   case X86::BI__builtin_ia32_vpshldw256:
4585   case X86::BI__builtin_ia32_vpshldw512:
4586   case X86::BI__builtin_ia32_vpshrdd128:
4587   case X86::BI__builtin_ia32_vpshrdd256:
4588   case X86::BI__builtin_ia32_vpshrdd512:
4589   case X86::BI__builtin_ia32_vpshrdq128:
4590   case X86::BI__builtin_ia32_vpshrdq256:
4591   case X86::BI__builtin_ia32_vpshrdq512:
4592   case X86::BI__builtin_ia32_vpshrdw128:
4593   case X86::BI__builtin_ia32_vpshrdw256:
4594   case X86::BI__builtin_ia32_vpshrdw512:
4595     i = 2; l = 0; u = 255;
4596     break;
4597   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4598   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4599   case X86::BI__builtin_ia32_fixupimmps512_mask:
4600   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4601   case X86::BI__builtin_ia32_fixupimmsd_mask:
4602   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4603   case X86::BI__builtin_ia32_fixupimmss_mask:
4604   case X86::BI__builtin_ia32_fixupimmss_maskz:
4605   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4606   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4607   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4608   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4609   case X86::BI__builtin_ia32_fixupimmps128_mask:
4610   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4611   case X86::BI__builtin_ia32_fixupimmps256_mask:
4612   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4613   case X86::BI__builtin_ia32_pternlogd512_mask:
4614   case X86::BI__builtin_ia32_pternlogd512_maskz:
4615   case X86::BI__builtin_ia32_pternlogq512_mask:
4616   case X86::BI__builtin_ia32_pternlogq512_maskz:
4617   case X86::BI__builtin_ia32_pternlogd128_mask:
4618   case X86::BI__builtin_ia32_pternlogd128_maskz:
4619   case X86::BI__builtin_ia32_pternlogd256_mask:
4620   case X86::BI__builtin_ia32_pternlogd256_maskz:
4621   case X86::BI__builtin_ia32_pternlogq128_mask:
4622   case X86::BI__builtin_ia32_pternlogq128_maskz:
4623   case X86::BI__builtin_ia32_pternlogq256_mask:
4624   case X86::BI__builtin_ia32_pternlogq256_maskz:
4625     i = 3; l = 0; u = 255;
4626     break;
4627   case X86::BI__builtin_ia32_gatherpfdpd:
4628   case X86::BI__builtin_ia32_gatherpfdps:
4629   case X86::BI__builtin_ia32_gatherpfqpd:
4630   case X86::BI__builtin_ia32_gatherpfqps:
4631   case X86::BI__builtin_ia32_scatterpfdpd:
4632   case X86::BI__builtin_ia32_scatterpfdps:
4633   case X86::BI__builtin_ia32_scatterpfqpd:
4634   case X86::BI__builtin_ia32_scatterpfqps:
4635     i = 4; l = 2; u = 3;
4636     break;
4637   case X86::BI__builtin_ia32_reducesd_mask:
4638   case X86::BI__builtin_ia32_reducess_mask:
4639   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4640   case X86::BI__builtin_ia32_rndscaless_round_mask:
4641   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4642   case X86::BI__builtin_ia32_reducesh_mask:
4643     i = 4; l = 0; u = 255;
4644     break;
4645   }
4646 
4647   // Note that we don't force a hard error on the range check here, allowing
4648   // template-generated or macro-generated dead code to potentially have out-of-
4649   // range values. These need to code generate, but don't need to necessarily
4650   // make any sense. We use a warning that defaults to an error.
4651   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4652 }
4653 
4654 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4655 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4656 /// Returns true when the format fits the function and the FormatStringInfo has
4657 /// been populated.
4658 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4659                                FormatStringInfo *FSI) {
4660   FSI->HasVAListArg = Format->getFirstArg() == 0;
4661   FSI->FormatIdx = Format->getFormatIdx() - 1;
4662   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4663 
4664   // The way the format attribute works in GCC, the implicit this argument
4665   // of member functions is counted. However, it doesn't appear in our own
4666   // lists, so decrement format_idx in that case.
4667   if (IsCXXMember) {
4668     if(FSI->FormatIdx == 0)
4669       return false;
4670     --FSI->FormatIdx;
4671     if (FSI->FirstDataArg != 0)
4672       --FSI->FirstDataArg;
4673   }
4674   return true;
4675 }
4676 
4677 /// Checks if a the given expression evaluates to null.
4678 ///
4679 /// Returns true if the value evaluates to null.
4680 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4681   // If the expression has non-null type, it doesn't evaluate to null.
4682   if (auto nullability
4683         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4684     if (*nullability == NullabilityKind::NonNull)
4685       return false;
4686   }
4687 
4688   // As a special case, transparent unions initialized with zero are
4689   // considered null for the purposes of the nonnull attribute.
4690   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4691     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4692       if (const CompoundLiteralExpr *CLE =
4693           dyn_cast<CompoundLiteralExpr>(Expr))
4694         if (const InitListExpr *ILE =
4695             dyn_cast<InitListExpr>(CLE->getInitializer()))
4696           Expr = ILE->getInit(0);
4697   }
4698 
4699   bool Result;
4700   return (!Expr->isValueDependent() &&
4701           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4702           !Result);
4703 }
4704 
4705 static void CheckNonNullArgument(Sema &S,
4706                                  const Expr *ArgExpr,
4707                                  SourceLocation CallSiteLoc) {
4708   if (CheckNonNullExpr(S, ArgExpr))
4709     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4710                           S.PDiag(diag::warn_null_arg)
4711                               << ArgExpr->getSourceRange());
4712 }
4713 
4714 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4715   FormatStringInfo FSI;
4716   if ((GetFormatStringType(Format) == FST_NSString) &&
4717       getFormatStringInfo(Format, false, &FSI)) {
4718     Idx = FSI.FormatIdx;
4719     return true;
4720   }
4721   return false;
4722 }
4723 
4724 /// Diagnose use of %s directive in an NSString which is being passed
4725 /// as formatting string to formatting method.
4726 static void
4727 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4728                                         const NamedDecl *FDecl,
4729                                         Expr **Args,
4730                                         unsigned NumArgs) {
4731   unsigned Idx = 0;
4732   bool Format = false;
4733   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4734   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4735     Idx = 2;
4736     Format = true;
4737   }
4738   else
4739     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4740       if (S.GetFormatNSStringIdx(I, Idx)) {
4741         Format = true;
4742         break;
4743       }
4744     }
4745   if (!Format || NumArgs <= Idx)
4746     return;
4747   const Expr *FormatExpr = Args[Idx];
4748   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4749     FormatExpr = CSCE->getSubExpr();
4750   const StringLiteral *FormatString;
4751   if (const ObjCStringLiteral *OSL =
4752       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4753     FormatString = OSL->getString();
4754   else
4755     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4756   if (!FormatString)
4757     return;
4758   if (S.FormatStringHasSArg(FormatString)) {
4759     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4760       << "%s" << 1 << 1;
4761     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4762       << FDecl->getDeclName();
4763   }
4764 }
4765 
4766 /// Determine whether the given type has a non-null nullability annotation.
4767 static bool isNonNullType(ASTContext &ctx, QualType type) {
4768   if (auto nullability = type->getNullability(ctx))
4769     return *nullability == NullabilityKind::NonNull;
4770 
4771   return false;
4772 }
4773 
4774 static void CheckNonNullArguments(Sema &S,
4775                                   const NamedDecl *FDecl,
4776                                   const FunctionProtoType *Proto,
4777                                   ArrayRef<const Expr *> Args,
4778                                   SourceLocation CallSiteLoc) {
4779   assert((FDecl || Proto) && "Need a function declaration or prototype");
4780 
4781   // Already checked by by constant evaluator.
4782   if (S.isConstantEvaluated())
4783     return;
4784   // Check the attributes attached to the method/function itself.
4785   llvm::SmallBitVector NonNullArgs;
4786   if (FDecl) {
4787     // Handle the nonnull attribute on the function/method declaration itself.
4788     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4789       if (!NonNull->args_size()) {
4790         // Easy case: all pointer arguments are nonnull.
4791         for (const auto *Arg : Args)
4792           if (S.isValidPointerAttrType(Arg->getType()))
4793             CheckNonNullArgument(S, Arg, CallSiteLoc);
4794         return;
4795       }
4796 
4797       for (const ParamIdx &Idx : NonNull->args()) {
4798         unsigned IdxAST = Idx.getASTIndex();
4799         if (IdxAST >= Args.size())
4800           continue;
4801         if (NonNullArgs.empty())
4802           NonNullArgs.resize(Args.size());
4803         NonNullArgs.set(IdxAST);
4804       }
4805     }
4806   }
4807 
4808   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4809     // Handle the nonnull attribute on the parameters of the
4810     // function/method.
4811     ArrayRef<ParmVarDecl*> parms;
4812     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4813       parms = FD->parameters();
4814     else
4815       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4816 
4817     unsigned ParamIndex = 0;
4818     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4819          I != E; ++I, ++ParamIndex) {
4820       const ParmVarDecl *PVD = *I;
4821       if (PVD->hasAttr<NonNullAttr>() ||
4822           isNonNullType(S.Context, PVD->getType())) {
4823         if (NonNullArgs.empty())
4824           NonNullArgs.resize(Args.size());
4825 
4826         NonNullArgs.set(ParamIndex);
4827       }
4828     }
4829   } else {
4830     // If we have a non-function, non-method declaration but no
4831     // function prototype, try to dig out the function prototype.
4832     if (!Proto) {
4833       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4834         QualType type = VD->getType().getNonReferenceType();
4835         if (auto pointerType = type->getAs<PointerType>())
4836           type = pointerType->getPointeeType();
4837         else if (auto blockType = type->getAs<BlockPointerType>())
4838           type = blockType->getPointeeType();
4839         // FIXME: data member pointers?
4840 
4841         // Dig out the function prototype, if there is one.
4842         Proto = type->getAs<FunctionProtoType>();
4843       }
4844     }
4845 
4846     // Fill in non-null argument information from the nullability
4847     // information on the parameter types (if we have them).
4848     if (Proto) {
4849       unsigned Index = 0;
4850       for (auto paramType : Proto->getParamTypes()) {
4851         if (isNonNullType(S.Context, paramType)) {
4852           if (NonNullArgs.empty())
4853             NonNullArgs.resize(Args.size());
4854 
4855           NonNullArgs.set(Index);
4856         }
4857 
4858         ++Index;
4859       }
4860     }
4861   }
4862 
4863   // Check for non-null arguments.
4864   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4865        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4866     if (NonNullArgs[ArgIndex])
4867       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4868   }
4869 }
4870 
4871 /// Warn if a pointer or reference argument passed to a function points to an
4872 /// object that is less aligned than the parameter. This can happen when
4873 /// creating a typedef with a lower alignment than the original type and then
4874 /// calling functions defined in terms of the original type.
4875 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4876                              StringRef ParamName, QualType ArgTy,
4877                              QualType ParamTy) {
4878 
4879   // If a function accepts a pointer or reference type
4880   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4881     return;
4882 
4883   // If the parameter is a pointer type, get the pointee type for the
4884   // argument too. If the parameter is a reference type, don't try to get
4885   // the pointee type for the argument.
4886   if (ParamTy->isPointerType())
4887     ArgTy = ArgTy->getPointeeType();
4888 
4889   // Remove reference or pointer
4890   ParamTy = ParamTy->getPointeeType();
4891 
4892   // Find expected alignment, and the actual alignment of the passed object.
4893   // getTypeAlignInChars requires complete types
4894   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4895       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4896       ArgTy->isUndeducedType())
4897     return;
4898 
4899   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4900   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4901 
4902   // If the argument is less aligned than the parameter, there is a
4903   // potential alignment issue.
4904   if (ArgAlign < ParamAlign)
4905     Diag(Loc, diag::warn_param_mismatched_alignment)
4906         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4907         << ParamName << (FDecl != nullptr) << FDecl;
4908 }
4909 
4910 /// Handles the checks for format strings, non-POD arguments to vararg
4911 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4912 /// attributes.
4913 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4914                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4915                      bool IsMemberFunction, SourceLocation Loc,
4916                      SourceRange Range, VariadicCallType CallType) {
4917   // FIXME: We should check as much as we can in the template definition.
4918   if (CurContext->isDependentContext())
4919     return;
4920 
4921   // Printf and scanf checking.
4922   llvm::SmallBitVector CheckedVarArgs;
4923   if (FDecl) {
4924     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4925       // Only create vector if there are format attributes.
4926       CheckedVarArgs.resize(Args.size());
4927 
4928       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4929                            CheckedVarArgs);
4930     }
4931   }
4932 
4933   // Refuse POD arguments that weren't caught by the format string
4934   // checks above.
4935   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4936   if (CallType != VariadicDoesNotApply &&
4937       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4938     unsigned NumParams = Proto ? Proto->getNumParams()
4939                        : FDecl && isa<FunctionDecl>(FDecl)
4940                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4941                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4942                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4943                        : 0;
4944 
4945     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4946       // Args[ArgIdx] can be null in malformed code.
4947       if (const Expr *Arg = Args[ArgIdx]) {
4948         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4949           checkVariadicArgument(Arg, CallType);
4950       }
4951     }
4952   }
4953 
4954   if (FDecl || Proto) {
4955     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4956 
4957     // Type safety checking.
4958     if (FDecl) {
4959       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4960         CheckArgumentWithTypeTag(I, Args, Loc);
4961     }
4962   }
4963 
4964   // Check that passed arguments match the alignment of original arguments.
4965   // Try to get the missing prototype from the declaration.
4966   if (!Proto && FDecl) {
4967     const auto *FT = FDecl->getFunctionType();
4968     if (isa_and_nonnull<FunctionProtoType>(FT))
4969       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4970   }
4971   if (Proto) {
4972     // For variadic functions, we may have more args than parameters.
4973     // For some K&R functions, we may have less args than parameters.
4974     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4975     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4976       // Args[ArgIdx] can be null in malformed code.
4977       if (const Expr *Arg = Args[ArgIdx]) {
4978         if (Arg->containsErrors())
4979           continue;
4980 
4981         QualType ParamTy = Proto->getParamType(ArgIdx);
4982         QualType ArgTy = Arg->getType();
4983         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4984                           ArgTy, ParamTy);
4985       }
4986     }
4987   }
4988 
4989   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4990     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4991     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4992     if (!Arg->isValueDependent()) {
4993       Expr::EvalResult Align;
4994       if (Arg->EvaluateAsInt(Align, Context)) {
4995         const llvm::APSInt &I = Align.Val.getInt();
4996         if (!I.isPowerOf2())
4997           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4998               << Arg->getSourceRange();
4999 
5000         if (I > Sema::MaximumAlignment)
5001           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
5002               << Arg->getSourceRange() << Sema::MaximumAlignment;
5003       }
5004     }
5005   }
5006 
5007   if (FD)
5008     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
5009 }
5010 
5011 /// CheckConstructorCall - Check a constructor call for correctness and safety
5012 /// properties not enforced by the C type system.
5013 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
5014                                 ArrayRef<const Expr *> Args,
5015                                 const FunctionProtoType *Proto,
5016                                 SourceLocation Loc) {
5017   VariadicCallType CallType =
5018       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
5019 
5020   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
5021   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
5022                     Context.getPointerType(Ctor->getThisObjectType()));
5023 
5024   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
5025             Loc, SourceRange(), CallType);
5026 }
5027 
5028 /// CheckFunctionCall - Check a direct function call for various correctness
5029 /// and safety properties not strictly enforced by the C type system.
5030 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5031                              const FunctionProtoType *Proto) {
5032   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5033                               isa<CXXMethodDecl>(FDecl);
5034   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5035                           IsMemberOperatorCall;
5036   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5037                                                   TheCall->getCallee());
5038   Expr** Args = TheCall->getArgs();
5039   unsigned NumArgs = TheCall->getNumArgs();
5040 
5041   Expr *ImplicitThis = nullptr;
5042   if (IsMemberOperatorCall) {
5043     // If this is a call to a member operator, hide the first argument
5044     // from checkCall.
5045     // FIXME: Our choice of AST representation here is less than ideal.
5046     ImplicitThis = Args[0];
5047     ++Args;
5048     --NumArgs;
5049   } else if (IsMemberFunction)
5050     ImplicitThis =
5051         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5052 
5053   if (ImplicitThis) {
5054     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5055     // used.
5056     QualType ThisType = ImplicitThis->getType();
5057     if (!ThisType->isPointerType()) {
5058       assert(!ThisType->isReferenceType());
5059       ThisType = Context.getPointerType(ThisType);
5060     }
5061 
5062     QualType ThisTypeFromDecl =
5063         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5064 
5065     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5066                       ThisTypeFromDecl);
5067   }
5068 
5069   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5070             IsMemberFunction, TheCall->getRParenLoc(),
5071             TheCall->getCallee()->getSourceRange(), CallType);
5072 
5073   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5074   // None of the checks below are needed for functions that don't have
5075   // simple names (e.g., C++ conversion functions).
5076   if (!FnInfo)
5077     return false;
5078 
5079   CheckTCBEnforcement(TheCall, FDecl);
5080 
5081   CheckAbsoluteValueFunction(TheCall, FDecl);
5082   CheckMaxUnsignedZero(TheCall, FDecl);
5083 
5084   if (getLangOpts().ObjC)
5085     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5086 
5087   unsigned CMId = FDecl->getMemoryFunctionKind();
5088 
5089   // Handle memory setting and copying functions.
5090   switch (CMId) {
5091   case 0:
5092     return false;
5093   case Builtin::BIstrlcpy: // fallthrough
5094   case Builtin::BIstrlcat:
5095     CheckStrlcpycatArguments(TheCall, FnInfo);
5096     break;
5097   case Builtin::BIstrncat:
5098     CheckStrncatArguments(TheCall, FnInfo);
5099     break;
5100   case Builtin::BIfree:
5101     CheckFreeArguments(TheCall);
5102     break;
5103   default:
5104     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5105   }
5106 
5107   return false;
5108 }
5109 
5110 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5111                                ArrayRef<const Expr *> Args) {
5112   VariadicCallType CallType =
5113       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5114 
5115   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5116             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5117             CallType);
5118 
5119   return false;
5120 }
5121 
5122 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5123                             const FunctionProtoType *Proto) {
5124   QualType Ty;
5125   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5126     Ty = V->getType().getNonReferenceType();
5127   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5128     Ty = F->getType().getNonReferenceType();
5129   else
5130     return false;
5131 
5132   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5133       !Ty->isFunctionProtoType())
5134     return false;
5135 
5136   VariadicCallType CallType;
5137   if (!Proto || !Proto->isVariadic()) {
5138     CallType = VariadicDoesNotApply;
5139   } else if (Ty->isBlockPointerType()) {
5140     CallType = VariadicBlock;
5141   } else { // Ty->isFunctionPointerType()
5142     CallType = VariadicFunction;
5143   }
5144 
5145   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5146             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5147             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5148             TheCall->getCallee()->getSourceRange(), CallType);
5149 
5150   return false;
5151 }
5152 
5153 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5154 /// such as function pointers returned from functions.
5155 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5156   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5157                                                   TheCall->getCallee());
5158   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5159             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5160             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5161             TheCall->getCallee()->getSourceRange(), CallType);
5162 
5163   return false;
5164 }
5165 
5166 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5167   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5168     return false;
5169 
5170   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5171   switch (Op) {
5172   case AtomicExpr::AO__c11_atomic_init:
5173   case AtomicExpr::AO__opencl_atomic_init:
5174     llvm_unreachable("There is no ordering argument for an init");
5175 
5176   case AtomicExpr::AO__c11_atomic_load:
5177   case AtomicExpr::AO__opencl_atomic_load:
5178   case AtomicExpr::AO__atomic_load_n:
5179   case AtomicExpr::AO__atomic_load:
5180     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5181            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5182 
5183   case AtomicExpr::AO__c11_atomic_store:
5184   case AtomicExpr::AO__opencl_atomic_store:
5185   case AtomicExpr::AO__atomic_store:
5186   case AtomicExpr::AO__atomic_store_n:
5187     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5188            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5189            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5190 
5191   default:
5192     return true;
5193   }
5194 }
5195 
5196 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5197                                          AtomicExpr::AtomicOp Op) {
5198   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5199   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5200   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5201   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5202                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5203                          Op);
5204 }
5205 
5206 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5207                                  SourceLocation RParenLoc, MultiExprArg Args,
5208                                  AtomicExpr::AtomicOp Op,
5209                                  AtomicArgumentOrder ArgOrder) {
5210   // All the non-OpenCL operations take one of the following forms.
5211   // The OpenCL operations take the __c11 forms with one extra argument for
5212   // synchronization scope.
5213   enum {
5214     // C    __c11_atomic_init(A *, C)
5215     Init,
5216 
5217     // C    __c11_atomic_load(A *, int)
5218     Load,
5219 
5220     // void __atomic_load(A *, CP, int)
5221     LoadCopy,
5222 
5223     // void __atomic_store(A *, CP, int)
5224     Copy,
5225 
5226     // C    __c11_atomic_add(A *, M, int)
5227     Arithmetic,
5228 
5229     // C    __atomic_exchange_n(A *, CP, int)
5230     Xchg,
5231 
5232     // void __atomic_exchange(A *, C *, CP, int)
5233     GNUXchg,
5234 
5235     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5236     C11CmpXchg,
5237 
5238     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5239     GNUCmpXchg
5240   } Form = Init;
5241 
5242   const unsigned NumForm = GNUCmpXchg + 1;
5243   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5244   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5245   // where:
5246   //   C is an appropriate type,
5247   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5248   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5249   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5250   //   the int parameters are for orderings.
5251 
5252   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5253       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5254       "need to update code for modified forms");
5255   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5256                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5257                         AtomicExpr::AO__atomic_load,
5258                 "need to update code for modified C11 atomics");
5259   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5260                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5261   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5262                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5263                IsOpenCL;
5264   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5265              Op == AtomicExpr::AO__atomic_store_n ||
5266              Op == AtomicExpr::AO__atomic_exchange_n ||
5267              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5268   bool IsAddSub = false;
5269 
5270   switch (Op) {
5271   case AtomicExpr::AO__c11_atomic_init:
5272   case AtomicExpr::AO__opencl_atomic_init:
5273     Form = Init;
5274     break;
5275 
5276   case AtomicExpr::AO__c11_atomic_load:
5277   case AtomicExpr::AO__opencl_atomic_load:
5278   case AtomicExpr::AO__atomic_load_n:
5279     Form = Load;
5280     break;
5281 
5282   case AtomicExpr::AO__atomic_load:
5283     Form = LoadCopy;
5284     break;
5285 
5286   case AtomicExpr::AO__c11_atomic_store:
5287   case AtomicExpr::AO__opencl_atomic_store:
5288   case AtomicExpr::AO__atomic_store:
5289   case AtomicExpr::AO__atomic_store_n:
5290     Form = Copy;
5291     break;
5292 
5293   case AtomicExpr::AO__c11_atomic_fetch_add:
5294   case AtomicExpr::AO__c11_atomic_fetch_sub:
5295   case AtomicExpr::AO__opencl_atomic_fetch_add:
5296   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5297   case AtomicExpr::AO__atomic_fetch_add:
5298   case AtomicExpr::AO__atomic_fetch_sub:
5299   case AtomicExpr::AO__atomic_add_fetch:
5300   case AtomicExpr::AO__atomic_sub_fetch:
5301     IsAddSub = true;
5302     Form = Arithmetic;
5303     break;
5304   case AtomicExpr::AO__c11_atomic_fetch_and:
5305   case AtomicExpr::AO__c11_atomic_fetch_or:
5306   case AtomicExpr::AO__c11_atomic_fetch_xor:
5307   case AtomicExpr::AO__c11_atomic_fetch_nand:
5308   case AtomicExpr::AO__opencl_atomic_fetch_and:
5309   case AtomicExpr::AO__opencl_atomic_fetch_or:
5310   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5311   case AtomicExpr::AO__atomic_fetch_and:
5312   case AtomicExpr::AO__atomic_fetch_or:
5313   case AtomicExpr::AO__atomic_fetch_xor:
5314   case AtomicExpr::AO__atomic_fetch_nand:
5315   case AtomicExpr::AO__atomic_and_fetch:
5316   case AtomicExpr::AO__atomic_or_fetch:
5317   case AtomicExpr::AO__atomic_xor_fetch:
5318   case AtomicExpr::AO__atomic_nand_fetch:
5319     Form = Arithmetic;
5320     break;
5321   case AtomicExpr::AO__c11_atomic_fetch_min:
5322   case AtomicExpr::AO__c11_atomic_fetch_max:
5323   case AtomicExpr::AO__opencl_atomic_fetch_min:
5324   case AtomicExpr::AO__opencl_atomic_fetch_max:
5325   case AtomicExpr::AO__atomic_min_fetch:
5326   case AtomicExpr::AO__atomic_max_fetch:
5327   case AtomicExpr::AO__atomic_fetch_min:
5328   case AtomicExpr::AO__atomic_fetch_max:
5329     Form = Arithmetic;
5330     break;
5331 
5332   case AtomicExpr::AO__c11_atomic_exchange:
5333   case AtomicExpr::AO__opencl_atomic_exchange:
5334   case AtomicExpr::AO__atomic_exchange_n:
5335     Form = Xchg;
5336     break;
5337 
5338   case AtomicExpr::AO__atomic_exchange:
5339     Form = GNUXchg;
5340     break;
5341 
5342   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5343   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5344   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5345   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5346     Form = C11CmpXchg;
5347     break;
5348 
5349   case AtomicExpr::AO__atomic_compare_exchange:
5350   case AtomicExpr::AO__atomic_compare_exchange_n:
5351     Form = GNUCmpXchg;
5352     break;
5353   }
5354 
5355   unsigned AdjustedNumArgs = NumArgs[Form];
5356   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5357     ++AdjustedNumArgs;
5358   // Check we have the right number of arguments.
5359   if (Args.size() < AdjustedNumArgs) {
5360     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5361         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5362         << ExprRange;
5363     return ExprError();
5364   } else if (Args.size() > AdjustedNumArgs) {
5365     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5366          diag::err_typecheck_call_too_many_args)
5367         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5368         << ExprRange;
5369     return ExprError();
5370   }
5371 
5372   // Inspect the first argument of the atomic operation.
5373   Expr *Ptr = Args[0];
5374   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5375   if (ConvertedPtr.isInvalid())
5376     return ExprError();
5377 
5378   Ptr = ConvertedPtr.get();
5379   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5380   if (!pointerType) {
5381     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5382         << Ptr->getType() << Ptr->getSourceRange();
5383     return ExprError();
5384   }
5385 
5386   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5387   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5388   QualType ValType = AtomTy; // 'C'
5389   if (IsC11) {
5390     if (!AtomTy->isAtomicType()) {
5391       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5392           << Ptr->getType() << Ptr->getSourceRange();
5393       return ExprError();
5394     }
5395     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5396         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5397       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5398           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5399           << Ptr->getSourceRange();
5400       return ExprError();
5401     }
5402     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5403   } else if (Form != Load && Form != LoadCopy) {
5404     if (ValType.isConstQualified()) {
5405       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5406           << Ptr->getType() << Ptr->getSourceRange();
5407       return ExprError();
5408     }
5409   }
5410 
5411   // For an arithmetic operation, the implied arithmetic must be well-formed.
5412   if (Form == Arithmetic) {
5413     // gcc does not enforce these rules for GNU atomics, but we do so for
5414     // sanity.
5415     auto IsAllowedValueType = [&](QualType ValType) {
5416       if (ValType->isIntegerType())
5417         return true;
5418       if (ValType->isPointerType())
5419         return true;
5420       if (!ValType->isFloatingType())
5421         return false;
5422       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5423       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5424           &Context.getTargetInfo().getLongDoubleFormat() ==
5425               &llvm::APFloat::x87DoubleExtended())
5426         return false;
5427       return true;
5428     };
5429     if (IsAddSub && !IsAllowedValueType(ValType)) {
5430       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5431           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5432       return ExprError();
5433     }
5434     if (!IsAddSub && !ValType->isIntegerType()) {
5435       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5436           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5437       return ExprError();
5438     }
5439     if (IsC11 && ValType->isPointerType() &&
5440         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5441                             diag::err_incomplete_type)) {
5442       return ExprError();
5443     }
5444   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5445     // For __atomic_*_n operations, the value type must be a scalar integral or
5446     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5447     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5448         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5449     return ExprError();
5450   }
5451 
5452   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5453       !AtomTy->isScalarType()) {
5454     // For GNU atomics, require a trivially-copyable type. This is not part of
5455     // the GNU atomics specification, but we enforce it for sanity.
5456     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5457         << Ptr->getType() << Ptr->getSourceRange();
5458     return ExprError();
5459   }
5460 
5461   switch (ValType.getObjCLifetime()) {
5462   case Qualifiers::OCL_None:
5463   case Qualifiers::OCL_ExplicitNone:
5464     // okay
5465     break;
5466 
5467   case Qualifiers::OCL_Weak:
5468   case Qualifiers::OCL_Strong:
5469   case Qualifiers::OCL_Autoreleasing:
5470     // FIXME: Can this happen? By this point, ValType should be known
5471     // to be trivially copyable.
5472     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5473         << ValType << Ptr->getSourceRange();
5474     return ExprError();
5475   }
5476 
5477   // All atomic operations have an overload which takes a pointer to a volatile
5478   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5479   // into the result or the other operands. Similarly atomic_load takes a
5480   // pointer to a const 'A'.
5481   ValType.removeLocalVolatile();
5482   ValType.removeLocalConst();
5483   QualType ResultType = ValType;
5484   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5485       Form == Init)
5486     ResultType = Context.VoidTy;
5487   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5488     ResultType = Context.BoolTy;
5489 
5490   // The type of a parameter passed 'by value'. In the GNU atomics, such
5491   // arguments are actually passed as pointers.
5492   QualType ByValType = ValType; // 'CP'
5493   bool IsPassedByAddress = false;
5494   if (!IsC11 && !IsN) {
5495     ByValType = Ptr->getType();
5496     IsPassedByAddress = true;
5497   }
5498 
5499   SmallVector<Expr *, 5> APIOrderedArgs;
5500   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5501     APIOrderedArgs.push_back(Args[0]);
5502     switch (Form) {
5503     case Init:
5504     case Load:
5505       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5506       break;
5507     case LoadCopy:
5508     case Copy:
5509     case Arithmetic:
5510     case Xchg:
5511       APIOrderedArgs.push_back(Args[2]); // Val1
5512       APIOrderedArgs.push_back(Args[1]); // Order
5513       break;
5514     case GNUXchg:
5515       APIOrderedArgs.push_back(Args[2]); // Val1
5516       APIOrderedArgs.push_back(Args[3]); // Val2
5517       APIOrderedArgs.push_back(Args[1]); // Order
5518       break;
5519     case C11CmpXchg:
5520       APIOrderedArgs.push_back(Args[2]); // Val1
5521       APIOrderedArgs.push_back(Args[4]); // Val2
5522       APIOrderedArgs.push_back(Args[1]); // Order
5523       APIOrderedArgs.push_back(Args[3]); // OrderFail
5524       break;
5525     case GNUCmpXchg:
5526       APIOrderedArgs.push_back(Args[2]); // Val1
5527       APIOrderedArgs.push_back(Args[4]); // Val2
5528       APIOrderedArgs.push_back(Args[5]); // Weak
5529       APIOrderedArgs.push_back(Args[1]); // Order
5530       APIOrderedArgs.push_back(Args[3]); // OrderFail
5531       break;
5532     }
5533   } else
5534     APIOrderedArgs.append(Args.begin(), Args.end());
5535 
5536   // The first argument's non-CV pointer type is used to deduce the type of
5537   // subsequent arguments, except for:
5538   //  - weak flag (always converted to bool)
5539   //  - memory order (always converted to int)
5540   //  - scope  (always converted to int)
5541   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5542     QualType Ty;
5543     if (i < NumVals[Form] + 1) {
5544       switch (i) {
5545       case 0:
5546         // The first argument is always a pointer. It has a fixed type.
5547         // It is always dereferenced, a nullptr is undefined.
5548         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5549         // Nothing else to do: we already know all we want about this pointer.
5550         continue;
5551       case 1:
5552         // The second argument is the non-atomic operand. For arithmetic, this
5553         // is always passed by value, and for a compare_exchange it is always
5554         // passed by address. For the rest, GNU uses by-address and C11 uses
5555         // by-value.
5556         assert(Form != Load);
5557         if (Form == Arithmetic && ValType->isPointerType())
5558           Ty = Context.getPointerDiffType();
5559         else if (Form == Init || Form == Arithmetic)
5560           Ty = ValType;
5561         else if (Form == Copy || Form == Xchg) {
5562           if (IsPassedByAddress) {
5563             // The value pointer is always dereferenced, a nullptr is undefined.
5564             CheckNonNullArgument(*this, APIOrderedArgs[i],
5565                                  ExprRange.getBegin());
5566           }
5567           Ty = ByValType;
5568         } else {
5569           Expr *ValArg = APIOrderedArgs[i];
5570           // The value pointer is always dereferenced, a nullptr is undefined.
5571           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5572           LangAS AS = LangAS::Default;
5573           // Keep address space of non-atomic pointer type.
5574           if (const PointerType *PtrTy =
5575                   ValArg->getType()->getAs<PointerType>()) {
5576             AS = PtrTy->getPointeeType().getAddressSpace();
5577           }
5578           Ty = Context.getPointerType(
5579               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5580         }
5581         break;
5582       case 2:
5583         // The third argument to compare_exchange / GNU exchange is the desired
5584         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5585         if (IsPassedByAddress)
5586           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5587         Ty = ByValType;
5588         break;
5589       case 3:
5590         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5591         Ty = Context.BoolTy;
5592         break;
5593       }
5594     } else {
5595       // The order(s) and scope are always converted to int.
5596       Ty = Context.IntTy;
5597     }
5598 
5599     InitializedEntity Entity =
5600         InitializedEntity::InitializeParameter(Context, Ty, false);
5601     ExprResult Arg = APIOrderedArgs[i];
5602     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5603     if (Arg.isInvalid())
5604       return true;
5605     APIOrderedArgs[i] = Arg.get();
5606   }
5607 
5608   // Permute the arguments into a 'consistent' order.
5609   SmallVector<Expr*, 5> SubExprs;
5610   SubExprs.push_back(Ptr);
5611   switch (Form) {
5612   case Init:
5613     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5614     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5615     break;
5616   case Load:
5617     SubExprs.push_back(APIOrderedArgs[1]); // Order
5618     break;
5619   case LoadCopy:
5620   case Copy:
5621   case Arithmetic:
5622   case Xchg:
5623     SubExprs.push_back(APIOrderedArgs[2]); // Order
5624     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5625     break;
5626   case GNUXchg:
5627     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5628     SubExprs.push_back(APIOrderedArgs[3]); // Order
5629     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5630     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5631     break;
5632   case C11CmpXchg:
5633     SubExprs.push_back(APIOrderedArgs[3]); // Order
5634     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5635     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5636     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5637     break;
5638   case GNUCmpXchg:
5639     SubExprs.push_back(APIOrderedArgs[4]); // Order
5640     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5641     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5642     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5643     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5644     break;
5645   }
5646 
5647   if (SubExprs.size() >= 2 && Form != Init) {
5648     if (Optional<llvm::APSInt> Result =
5649             SubExprs[1]->getIntegerConstantExpr(Context))
5650       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5651         Diag(SubExprs[1]->getBeginLoc(),
5652              diag::warn_atomic_op_has_invalid_memory_order)
5653             << SubExprs[1]->getSourceRange();
5654   }
5655 
5656   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5657     auto *Scope = Args[Args.size() - 1];
5658     if (Optional<llvm::APSInt> Result =
5659             Scope->getIntegerConstantExpr(Context)) {
5660       if (!ScopeModel->isValid(Result->getZExtValue()))
5661         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5662             << Scope->getSourceRange();
5663     }
5664     SubExprs.push_back(Scope);
5665   }
5666 
5667   AtomicExpr *AE = new (Context)
5668       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5669 
5670   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5671        Op == AtomicExpr::AO__c11_atomic_store ||
5672        Op == AtomicExpr::AO__opencl_atomic_load ||
5673        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5674       Context.AtomicUsesUnsupportedLibcall(AE))
5675     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5676         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5677              Op == AtomicExpr::AO__opencl_atomic_load)
5678                 ? 0
5679                 : 1);
5680 
5681   if (ValType->isExtIntType()) {
5682     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5683     return ExprError();
5684   }
5685 
5686   return AE;
5687 }
5688 
5689 /// checkBuiltinArgument - Given a call to a builtin function, perform
5690 /// normal type-checking on the given argument, updating the call in
5691 /// place.  This is useful when a builtin function requires custom
5692 /// type-checking for some of its arguments but not necessarily all of
5693 /// them.
5694 ///
5695 /// Returns true on error.
5696 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5697   FunctionDecl *Fn = E->getDirectCallee();
5698   assert(Fn && "builtin call without direct callee!");
5699 
5700   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5701   InitializedEntity Entity =
5702     InitializedEntity::InitializeParameter(S.Context, Param);
5703 
5704   ExprResult Arg = E->getArg(0);
5705   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5706   if (Arg.isInvalid())
5707     return true;
5708 
5709   E->setArg(ArgIndex, Arg.get());
5710   return false;
5711 }
5712 
5713 /// We have a call to a function like __sync_fetch_and_add, which is an
5714 /// overloaded function based on the pointer type of its first argument.
5715 /// The main BuildCallExpr routines have already promoted the types of
5716 /// arguments because all of these calls are prototyped as void(...).
5717 ///
5718 /// This function goes through and does final semantic checking for these
5719 /// builtins, as well as generating any warnings.
5720 ExprResult
5721 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5722   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5723   Expr *Callee = TheCall->getCallee();
5724   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5725   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5726 
5727   // Ensure that we have at least one argument to do type inference from.
5728   if (TheCall->getNumArgs() < 1) {
5729     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5730         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5731     return ExprError();
5732   }
5733 
5734   // Inspect the first argument of the atomic builtin.  This should always be
5735   // a pointer type, whose element is an integral scalar or pointer type.
5736   // Because it is a pointer type, we don't have to worry about any implicit
5737   // casts here.
5738   // FIXME: We don't allow floating point scalars as input.
5739   Expr *FirstArg = TheCall->getArg(0);
5740   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5741   if (FirstArgResult.isInvalid())
5742     return ExprError();
5743   FirstArg = FirstArgResult.get();
5744   TheCall->setArg(0, FirstArg);
5745 
5746   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5747   if (!pointerType) {
5748     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5749         << FirstArg->getType() << FirstArg->getSourceRange();
5750     return ExprError();
5751   }
5752 
5753   QualType ValType = pointerType->getPointeeType();
5754   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5755       !ValType->isBlockPointerType()) {
5756     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5757         << FirstArg->getType() << FirstArg->getSourceRange();
5758     return ExprError();
5759   }
5760 
5761   if (ValType.isConstQualified()) {
5762     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5763         << FirstArg->getType() << FirstArg->getSourceRange();
5764     return ExprError();
5765   }
5766 
5767   switch (ValType.getObjCLifetime()) {
5768   case Qualifiers::OCL_None:
5769   case Qualifiers::OCL_ExplicitNone:
5770     // okay
5771     break;
5772 
5773   case Qualifiers::OCL_Weak:
5774   case Qualifiers::OCL_Strong:
5775   case Qualifiers::OCL_Autoreleasing:
5776     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5777         << ValType << FirstArg->getSourceRange();
5778     return ExprError();
5779   }
5780 
5781   // Strip any qualifiers off ValType.
5782   ValType = ValType.getUnqualifiedType();
5783 
5784   // The majority of builtins return a value, but a few have special return
5785   // types, so allow them to override appropriately below.
5786   QualType ResultType = ValType;
5787 
5788   // We need to figure out which concrete builtin this maps onto.  For example,
5789   // __sync_fetch_and_add with a 2 byte object turns into
5790   // __sync_fetch_and_add_2.
5791 #define BUILTIN_ROW(x) \
5792   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5793     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5794 
5795   static const unsigned BuiltinIndices[][5] = {
5796     BUILTIN_ROW(__sync_fetch_and_add),
5797     BUILTIN_ROW(__sync_fetch_and_sub),
5798     BUILTIN_ROW(__sync_fetch_and_or),
5799     BUILTIN_ROW(__sync_fetch_and_and),
5800     BUILTIN_ROW(__sync_fetch_and_xor),
5801     BUILTIN_ROW(__sync_fetch_and_nand),
5802 
5803     BUILTIN_ROW(__sync_add_and_fetch),
5804     BUILTIN_ROW(__sync_sub_and_fetch),
5805     BUILTIN_ROW(__sync_and_and_fetch),
5806     BUILTIN_ROW(__sync_or_and_fetch),
5807     BUILTIN_ROW(__sync_xor_and_fetch),
5808     BUILTIN_ROW(__sync_nand_and_fetch),
5809 
5810     BUILTIN_ROW(__sync_val_compare_and_swap),
5811     BUILTIN_ROW(__sync_bool_compare_and_swap),
5812     BUILTIN_ROW(__sync_lock_test_and_set),
5813     BUILTIN_ROW(__sync_lock_release),
5814     BUILTIN_ROW(__sync_swap)
5815   };
5816 #undef BUILTIN_ROW
5817 
5818   // Determine the index of the size.
5819   unsigned SizeIndex;
5820   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5821   case 1: SizeIndex = 0; break;
5822   case 2: SizeIndex = 1; break;
5823   case 4: SizeIndex = 2; break;
5824   case 8: SizeIndex = 3; break;
5825   case 16: SizeIndex = 4; break;
5826   default:
5827     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5828         << FirstArg->getType() << FirstArg->getSourceRange();
5829     return ExprError();
5830   }
5831 
5832   // Each of these builtins has one pointer argument, followed by some number of
5833   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5834   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5835   // as the number of fixed args.
5836   unsigned BuiltinID = FDecl->getBuiltinID();
5837   unsigned BuiltinIndex, NumFixed = 1;
5838   bool WarnAboutSemanticsChange = false;
5839   switch (BuiltinID) {
5840   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5841   case Builtin::BI__sync_fetch_and_add:
5842   case Builtin::BI__sync_fetch_and_add_1:
5843   case Builtin::BI__sync_fetch_and_add_2:
5844   case Builtin::BI__sync_fetch_and_add_4:
5845   case Builtin::BI__sync_fetch_and_add_8:
5846   case Builtin::BI__sync_fetch_and_add_16:
5847     BuiltinIndex = 0;
5848     break;
5849 
5850   case Builtin::BI__sync_fetch_and_sub:
5851   case Builtin::BI__sync_fetch_and_sub_1:
5852   case Builtin::BI__sync_fetch_and_sub_2:
5853   case Builtin::BI__sync_fetch_and_sub_4:
5854   case Builtin::BI__sync_fetch_and_sub_8:
5855   case Builtin::BI__sync_fetch_and_sub_16:
5856     BuiltinIndex = 1;
5857     break;
5858 
5859   case Builtin::BI__sync_fetch_and_or:
5860   case Builtin::BI__sync_fetch_and_or_1:
5861   case Builtin::BI__sync_fetch_and_or_2:
5862   case Builtin::BI__sync_fetch_and_or_4:
5863   case Builtin::BI__sync_fetch_and_or_8:
5864   case Builtin::BI__sync_fetch_and_or_16:
5865     BuiltinIndex = 2;
5866     break;
5867 
5868   case Builtin::BI__sync_fetch_and_and:
5869   case Builtin::BI__sync_fetch_and_and_1:
5870   case Builtin::BI__sync_fetch_and_and_2:
5871   case Builtin::BI__sync_fetch_and_and_4:
5872   case Builtin::BI__sync_fetch_and_and_8:
5873   case Builtin::BI__sync_fetch_and_and_16:
5874     BuiltinIndex = 3;
5875     break;
5876 
5877   case Builtin::BI__sync_fetch_and_xor:
5878   case Builtin::BI__sync_fetch_and_xor_1:
5879   case Builtin::BI__sync_fetch_and_xor_2:
5880   case Builtin::BI__sync_fetch_and_xor_4:
5881   case Builtin::BI__sync_fetch_and_xor_8:
5882   case Builtin::BI__sync_fetch_and_xor_16:
5883     BuiltinIndex = 4;
5884     break;
5885 
5886   case Builtin::BI__sync_fetch_and_nand:
5887   case Builtin::BI__sync_fetch_and_nand_1:
5888   case Builtin::BI__sync_fetch_and_nand_2:
5889   case Builtin::BI__sync_fetch_and_nand_4:
5890   case Builtin::BI__sync_fetch_and_nand_8:
5891   case Builtin::BI__sync_fetch_and_nand_16:
5892     BuiltinIndex = 5;
5893     WarnAboutSemanticsChange = true;
5894     break;
5895 
5896   case Builtin::BI__sync_add_and_fetch:
5897   case Builtin::BI__sync_add_and_fetch_1:
5898   case Builtin::BI__sync_add_and_fetch_2:
5899   case Builtin::BI__sync_add_and_fetch_4:
5900   case Builtin::BI__sync_add_and_fetch_8:
5901   case Builtin::BI__sync_add_and_fetch_16:
5902     BuiltinIndex = 6;
5903     break;
5904 
5905   case Builtin::BI__sync_sub_and_fetch:
5906   case Builtin::BI__sync_sub_and_fetch_1:
5907   case Builtin::BI__sync_sub_and_fetch_2:
5908   case Builtin::BI__sync_sub_and_fetch_4:
5909   case Builtin::BI__sync_sub_and_fetch_8:
5910   case Builtin::BI__sync_sub_and_fetch_16:
5911     BuiltinIndex = 7;
5912     break;
5913 
5914   case Builtin::BI__sync_and_and_fetch:
5915   case Builtin::BI__sync_and_and_fetch_1:
5916   case Builtin::BI__sync_and_and_fetch_2:
5917   case Builtin::BI__sync_and_and_fetch_4:
5918   case Builtin::BI__sync_and_and_fetch_8:
5919   case Builtin::BI__sync_and_and_fetch_16:
5920     BuiltinIndex = 8;
5921     break;
5922 
5923   case Builtin::BI__sync_or_and_fetch:
5924   case Builtin::BI__sync_or_and_fetch_1:
5925   case Builtin::BI__sync_or_and_fetch_2:
5926   case Builtin::BI__sync_or_and_fetch_4:
5927   case Builtin::BI__sync_or_and_fetch_8:
5928   case Builtin::BI__sync_or_and_fetch_16:
5929     BuiltinIndex = 9;
5930     break;
5931 
5932   case Builtin::BI__sync_xor_and_fetch:
5933   case Builtin::BI__sync_xor_and_fetch_1:
5934   case Builtin::BI__sync_xor_and_fetch_2:
5935   case Builtin::BI__sync_xor_and_fetch_4:
5936   case Builtin::BI__sync_xor_and_fetch_8:
5937   case Builtin::BI__sync_xor_and_fetch_16:
5938     BuiltinIndex = 10;
5939     break;
5940 
5941   case Builtin::BI__sync_nand_and_fetch:
5942   case Builtin::BI__sync_nand_and_fetch_1:
5943   case Builtin::BI__sync_nand_and_fetch_2:
5944   case Builtin::BI__sync_nand_and_fetch_4:
5945   case Builtin::BI__sync_nand_and_fetch_8:
5946   case Builtin::BI__sync_nand_and_fetch_16:
5947     BuiltinIndex = 11;
5948     WarnAboutSemanticsChange = true;
5949     break;
5950 
5951   case Builtin::BI__sync_val_compare_and_swap:
5952   case Builtin::BI__sync_val_compare_and_swap_1:
5953   case Builtin::BI__sync_val_compare_and_swap_2:
5954   case Builtin::BI__sync_val_compare_and_swap_4:
5955   case Builtin::BI__sync_val_compare_and_swap_8:
5956   case Builtin::BI__sync_val_compare_and_swap_16:
5957     BuiltinIndex = 12;
5958     NumFixed = 2;
5959     break;
5960 
5961   case Builtin::BI__sync_bool_compare_and_swap:
5962   case Builtin::BI__sync_bool_compare_and_swap_1:
5963   case Builtin::BI__sync_bool_compare_and_swap_2:
5964   case Builtin::BI__sync_bool_compare_and_swap_4:
5965   case Builtin::BI__sync_bool_compare_and_swap_8:
5966   case Builtin::BI__sync_bool_compare_and_swap_16:
5967     BuiltinIndex = 13;
5968     NumFixed = 2;
5969     ResultType = Context.BoolTy;
5970     break;
5971 
5972   case Builtin::BI__sync_lock_test_and_set:
5973   case Builtin::BI__sync_lock_test_and_set_1:
5974   case Builtin::BI__sync_lock_test_and_set_2:
5975   case Builtin::BI__sync_lock_test_and_set_4:
5976   case Builtin::BI__sync_lock_test_and_set_8:
5977   case Builtin::BI__sync_lock_test_and_set_16:
5978     BuiltinIndex = 14;
5979     break;
5980 
5981   case Builtin::BI__sync_lock_release:
5982   case Builtin::BI__sync_lock_release_1:
5983   case Builtin::BI__sync_lock_release_2:
5984   case Builtin::BI__sync_lock_release_4:
5985   case Builtin::BI__sync_lock_release_8:
5986   case Builtin::BI__sync_lock_release_16:
5987     BuiltinIndex = 15;
5988     NumFixed = 0;
5989     ResultType = Context.VoidTy;
5990     break;
5991 
5992   case Builtin::BI__sync_swap:
5993   case Builtin::BI__sync_swap_1:
5994   case Builtin::BI__sync_swap_2:
5995   case Builtin::BI__sync_swap_4:
5996   case Builtin::BI__sync_swap_8:
5997   case Builtin::BI__sync_swap_16:
5998     BuiltinIndex = 16;
5999     break;
6000   }
6001 
6002   // Now that we know how many fixed arguments we expect, first check that we
6003   // have at least that many.
6004   if (TheCall->getNumArgs() < 1+NumFixed) {
6005     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
6006         << 0 << 1 + NumFixed << TheCall->getNumArgs()
6007         << Callee->getSourceRange();
6008     return ExprError();
6009   }
6010 
6011   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
6012       << Callee->getSourceRange();
6013 
6014   if (WarnAboutSemanticsChange) {
6015     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
6016         << Callee->getSourceRange();
6017   }
6018 
6019   // Get the decl for the concrete builtin from this, we can tell what the
6020   // concrete integer type we should convert to is.
6021   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
6022   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
6023   FunctionDecl *NewBuiltinDecl;
6024   if (NewBuiltinID == BuiltinID)
6025     NewBuiltinDecl = FDecl;
6026   else {
6027     // Perform builtin lookup to avoid redeclaring it.
6028     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6029     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6030     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6031     assert(Res.getFoundDecl());
6032     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6033     if (!NewBuiltinDecl)
6034       return ExprError();
6035   }
6036 
6037   // The first argument --- the pointer --- has a fixed type; we
6038   // deduce the types of the rest of the arguments accordingly.  Walk
6039   // the remaining arguments, converting them to the deduced value type.
6040   for (unsigned i = 0; i != NumFixed; ++i) {
6041     ExprResult Arg = TheCall->getArg(i+1);
6042 
6043     // GCC does an implicit conversion to the pointer or integer ValType.  This
6044     // can fail in some cases (1i -> int**), check for this error case now.
6045     // Initialize the argument.
6046     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6047                                                    ValType, /*consume*/ false);
6048     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6049     if (Arg.isInvalid())
6050       return ExprError();
6051 
6052     // Okay, we have something that *can* be converted to the right type.  Check
6053     // to see if there is a potentially weird extension going on here.  This can
6054     // happen when you do an atomic operation on something like an char* and
6055     // pass in 42.  The 42 gets converted to char.  This is even more strange
6056     // for things like 45.123 -> char, etc.
6057     // FIXME: Do this check.
6058     TheCall->setArg(i+1, Arg.get());
6059   }
6060 
6061   // Create a new DeclRefExpr to refer to the new decl.
6062   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6063       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6064       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6065       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6066 
6067   // Set the callee in the CallExpr.
6068   // FIXME: This loses syntactic information.
6069   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6070   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6071                                               CK_BuiltinFnToFnPtr);
6072   TheCall->setCallee(PromotedCall.get());
6073 
6074   // Change the result type of the call to match the original value type. This
6075   // is arbitrary, but the codegen for these builtins ins design to handle it
6076   // gracefully.
6077   TheCall->setType(ResultType);
6078 
6079   // Prohibit use of _ExtInt with atomic builtins.
6080   // The arguments would have already been converted to the first argument's
6081   // type, so only need to check the first argument.
6082   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6083   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6084     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6085     return ExprError();
6086   }
6087 
6088   return TheCallResult;
6089 }
6090 
6091 /// SemaBuiltinNontemporalOverloaded - We have a call to
6092 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6093 /// overloaded function based on the pointer type of its last argument.
6094 ///
6095 /// This function goes through and does final semantic checking for these
6096 /// builtins.
6097 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6098   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6099   DeclRefExpr *DRE =
6100       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6101   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6102   unsigned BuiltinID = FDecl->getBuiltinID();
6103   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6104           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6105          "Unexpected nontemporal load/store builtin!");
6106   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6107   unsigned numArgs = isStore ? 2 : 1;
6108 
6109   // Ensure that we have the proper number of arguments.
6110   if (checkArgCount(*this, TheCall, numArgs))
6111     return ExprError();
6112 
6113   // Inspect the last argument of the nontemporal builtin.  This should always
6114   // be a pointer type, from which we imply the type of the memory access.
6115   // Because it is a pointer type, we don't have to worry about any implicit
6116   // casts here.
6117   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6118   ExprResult PointerArgResult =
6119       DefaultFunctionArrayLvalueConversion(PointerArg);
6120 
6121   if (PointerArgResult.isInvalid())
6122     return ExprError();
6123   PointerArg = PointerArgResult.get();
6124   TheCall->setArg(numArgs - 1, PointerArg);
6125 
6126   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6127   if (!pointerType) {
6128     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6129         << PointerArg->getType() << PointerArg->getSourceRange();
6130     return ExprError();
6131   }
6132 
6133   QualType ValType = pointerType->getPointeeType();
6134 
6135   // Strip any qualifiers off ValType.
6136   ValType = ValType.getUnqualifiedType();
6137   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6138       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6139       !ValType->isVectorType()) {
6140     Diag(DRE->getBeginLoc(),
6141          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6142         << PointerArg->getType() << PointerArg->getSourceRange();
6143     return ExprError();
6144   }
6145 
6146   if (!isStore) {
6147     TheCall->setType(ValType);
6148     return TheCallResult;
6149   }
6150 
6151   ExprResult ValArg = TheCall->getArg(0);
6152   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6153       Context, ValType, /*consume*/ false);
6154   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6155   if (ValArg.isInvalid())
6156     return ExprError();
6157 
6158   TheCall->setArg(0, ValArg.get());
6159   TheCall->setType(Context.VoidTy);
6160   return TheCallResult;
6161 }
6162 
6163 /// CheckObjCString - Checks that the argument to the builtin
6164 /// CFString constructor is correct
6165 /// Note: It might also make sense to do the UTF-16 conversion here (would
6166 /// simplify the backend).
6167 bool Sema::CheckObjCString(Expr *Arg) {
6168   Arg = Arg->IgnoreParenCasts();
6169   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6170 
6171   if (!Literal || !Literal->isAscii()) {
6172     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6173         << Arg->getSourceRange();
6174     return true;
6175   }
6176 
6177   if (Literal->containsNonAsciiOrNull()) {
6178     StringRef String = Literal->getString();
6179     unsigned NumBytes = String.size();
6180     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6181     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6182     llvm::UTF16 *ToPtr = &ToBuf[0];
6183 
6184     llvm::ConversionResult Result =
6185         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6186                                  ToPtr + NumBytes, llvm::strictConversion);
6187     // Check for conversion failure.
6188     if (Result != llvm::conversionOK)
6189       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6190           << Arg->getSourceRange();
6191   }
6192   return false;
6193 }
6194 
6195 /// CheckObjCString - Checks that the format string argument to the os_log()
6196 /// and os_trace() functions is correct, and converts it to const char *.
6197 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6198   Arg = Arg->IgnoreParenCasts();
6199   auto *Literal = dyn_cast<StringLiteral>(Arg);
6200   if (!Literal) {
6201     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6202       Literal = ObjcLiteral->getString();
6203     }
6204   }
6205 
6206   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6207     return ExprError(
6208         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6209         << Arg->getSourceRange());
6210   }
6211 
6212   ExprResult Result(Literal);
6213   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6214   InitializedEntity Entity =
6215       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6216   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6217   return Result;
6218 }
6219 
6220 /// Check that the user is calling the appropriate va_start builtin for the
6221 /// target and calling convention.
6222 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6223   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6224   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6225   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6226                     TT.getArch() == llvm::Triple::aarch64_32);
6227   bool IsWindows = TT.isOSWindows();
6228   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6229   if (IsX64 || IsAArch64) {
6230     CallingConv CC = CC_C;
6231     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6232       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6233     if (IsMSVAStart) {
6234       // Don't allow this in System V ABI functions.
6235       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6236         return S.Diag(Fn->getBeginLoc(),
6237                       diag::err_ms_va_start_used_in_sysv_function);
6238     } else {
6239       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6240       // On x64 Windows, don't allow this in System V ABI functions.
6241       // (Yes, that means there's no corresponding way to support variadic
6242       // System V ABI functions on Windows.)
6243       if ((IsWindows && CC == CC_X86_64SysV) ||
6244           (!IsWindows && CC == CC_Win64))
6245         return S.Diag(Fn->getBeginLoc(),
6246                       diag::err_va_start_used_in_wrong_abi_function)
6247                << !IsWindows;
6248     }
6249     return false;
6250   }
6251 
6252   if (IsMSVAStart)
6253     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6254   return false;
6255 }
6256 
6257 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6258                                              ParmVarDecl **LastParam = nullptr) {
6259   // Determine whether the current function, block, or obj-c method is variadic
6260   // and get its parameter list.
6261   bool IsVariadic = false;
6262   ArrayRef<ParmVarDecl *> Params;
6263   DeclContext *Caller = S.CurContext;
6264   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6265     IsVariadic = Block->isVariadic();
6266     Params = Block->parameters();
6267   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6268     IsVariadic = FD->isVariadic();
6269     Params = FD->parameters();
6270   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6271     IsVariadic = MD->isVariadic();
6272     // FIXME: This isn't correct for methods (results in bogus warning).
6273     Params = MD->parameters();
6274   } else if (isa<CapturedDecl>(Caller)) {
6275     // We don't support va_start in a CapturedDecl.
6276     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6277     return true;
6278   } else {
6279     // This must be some other declcontext that parses exprs.
6280     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6281     return true;
6282   }
6283 
6284   if (!IsVariadic) {
6285     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6286     return true;
6287   }
6288 
6289   if (LastParam)
6290     *LastParam = Params.empty() ? nullptr : Params.back();
6291 
6292   return false;
6293 }
6294 
6295 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6296 /// for validity.  Emit an error and return true on failure; return false
6297 /// on success.
6298 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6299   Expr *Fn = TheCall->getCallee();
6300 
6301   if (checkVAStartABI(*this, BuiltinID, Fn))
6302     return true;
6303 
6304   if (checkArgCount(*this, TheCall, 2))
6305     return true;
6306 
6307   // Type-check the first argument normally.
6308   if (checkBuiltinArgument(*this, TheCall, 0))
6309     return true;
6310 
6311   // Check that the current function is variadic, and get its last parameter.
6312   ParmVarDecl *LastParam;
6313   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6314     return true;
6315 
6316   // Verify that the second argument to the builtin is the last argument of the
6317   // current function or method.
6318   bool SecondArgIsLastNamedArgument = false;
6319   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6320 
6321   // These are valid if SecondArgIsLastNamedArgument is false after the next
6322   // block.
6323   QualType Type;
6324   SourceLocation ParamLoc;
6325   bool IsCRegister = false;
6326 
6327   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6328     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6329       SecondArgIsLastNamedArgument = PV == LastParam;
6330 
6331       Type = PV->getType();
6332       ParamLoc = PV->getLocation();
6333       IsCRegister =
6334           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6335     }
6336   }
6337 
6338   if (!SecondArgIsLastNamedArgument)
6339     Diag(TheCall->getArg(1)->getBeginLoc(),
6340          diag::warn_second_arg_of_va_start_not_last_named_param);
6341   else if (IsCRegister || Type->isReferenceType() ||
6342            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6343              // Promotable integers are UB, but enumerations need a bit of
6344              // extra checking to see what their promotable type actually is.
6345              if (!Type->isPromotableIntegerType())
6346                return false;
6347              if (!Type->isEnumeralType())
6348                return true;
6349              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6350              return !(ED &&
6351                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6352            }()) {
6353     unsigned Reason = 0;
6354     if (Type->isReferenceType())  Reason = 1;
6355     else if (IsCRegister)         Reason = 2;
6356     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6357     Diag(ParamLoc, diag::note_parameter_type) << Type;
6358   }
6359 
6360   TheCall->setType(Context.VoidTy);
6361   return false;
6362 }
6363 
6364 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6365   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6366     const LangOptions &LO = getLangOpts();
6367 
6368     if (LO.CPlusPlus)
6369       return Arg->getType()
6370                  .getCanonicalType()
6371                  .getTypePtr()
6372                  ->getPointeeType()
6373                  .withoutLocalFastQualifiers() == Context.CharTy;
6374 
6375     // In C, allow aliasing through `char *`, this is required for AArch64 at
6376     // least.
6377     return true;
6378   };
6379 
6380   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6381   //                 const char *named_addr);
6382 
6383   Expr *Func = Call->getCallee();
6384 
6385   if (Call->getNumArgs() < 3)
6386     return Diag(Call->getEndLoc(),
6387                 diag::err_typecheck_call_too_few_args_at_least)
6388            << 0 /*function call*/ << 3 << Call->getNumArgs();
6389 
6390   // Type-check the first argument normally.
6391   if (checkBuiltinArgument(*this, Call, 0))
6392     return true;
6393 
6394   // Check that the current function is variadic.
6395   if (checkVAStartIsInVariadicFunction(*this, Func))
6396     return true;
6397 
6398   // __va_start on Windows does not validate the parameter qualifiers
6399 
6400   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6401   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6402 
6403   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6404   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6405 
6406   const QualType &ConstCharPtrTy =
6407       Context.getPointerType(Context.CharTy.withConst());
6408   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6409     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6410         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6411         << 0                                      /* qualifier difference */
6412         << 3                                      /* parameter mismatch */
6413         << 2 << Arg1->getType() << ConstCharPtrTy;
6414 
6415   const QualType SizeTy = Context.getSizeType();
6416   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6417     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6418         << Arg2->getType() << SizeTy << 1 /* different class */
6419         << 0                              /* qualifier difference */
6420         << 3                              /* parameter mismatch */
6421         << 3 << Arg2->getType() << SizeTy;
6422 
6423   return false;
6424 }
6425 
6426 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6427 /// friends.  This is declared to take (...), so we have to check everything.
6428 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6429   if (checkArgCount(*this, TheCall, 2))
6430     return true;
6431 
6432   ExprResult OrigArg0 = TheCall->getArg(0);
6433   ExprResult OrigArg1 = TheCall->getArg(1);
6434 
6435   // Do standard promotions between the two arguments, returning their common
6436   // type.
6437   QualType Res = UsualArithmeticConversions(
6438       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6439   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6440     return true;
6441 
6442   // Make sure any conversions are pushed back into the call; this is
6443   // type safe since unordered compare builtins are declared as "_Bool
6444   // foo(...)".
6445   TheCall->setArg(0, OrigArg0.get());
6446   TheCall->setArg(1, OrigArg1.get());
6447 
6448   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6449     return false;
6450 
6451   // If the common type isn't a real floating type, then the arguments were
6452   // invalid for this operation.
6453   if (Res.isNull() || !Res->isRealFloatingType())
6454     return Diag(OrigArg0.get()->getBeginLoc(),
6455                 diag::err_typecheck_call_invalid_ordered_compare)
6456            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6457            << SourceRange(OrigArg0.get()->getBeginLoc(),
6458                           OrigArg1.get()->getEndLoc());
6459 
6460   return false;
6461 }
6462 
6463 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6464 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6465 /// to check everything. We expect the last argument to be a floating point
6466 /// value.
6467 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6468   if (checkArgCount(*this, TheCall, NumArgs))
6469     return true;
6470 
6471   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6472   // on all preceding parameters just being int.  Try all of those.
6473   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6474     Expr *Arg = TheCall->getArg(i);
6475 
6476     if (Arg->isTypeDependent())
6477       return false;
6478 
6479     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6480 
6481     if (Res.isInvalid())
6482       return true;
6483     TheCall->setArg(i, Res.get());
6484   }
6485 
6486   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6487 
6488   if (OrigArg->isTypeDependent())
6489     return false;
6490 
6491   // Usual Unary Conversions will convert half to float, which we want for
6492   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6493   // type how it is, but do normal L->Rvalue conversions.
6494   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6495     OrigArg = UsualUnaryConversions(OrigArg).get();
6496   else
6497     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6498   TheCall->setArg(NumArgs - 1, OrigArg);
6499 
6500   // This operation requires a non-_Complex floating-point number.
6501   if (!OrigArg->getType()->isRealFloatingType())
6502     return Diag(OrigArg->getBeginLoc(),
6503                 diag::err_typecheck_call_invalid_unary_fp)
6504            << OrigArg->getType() << OrigArg->getSourceRange();
6505 
6506   return false;
6507 }
6508 
6509 /// Perform semantic analysis for a call to __builtin_complex.
6510 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6511   if (checkArgCount(*this, TheCall, 2))
6512     return true;
6513 
6514   bool Dependent = false;
6515   for (unsigned I = 0; I != 2; ++I) {
6516     Expr *Arg = TheCall->getArg(I);
6517     QualType T = Arg->getType();
6518     if (T->isDependentType()) {
6519       Dependent = true;
6520       continue;
6521     }
6522 
6523     // Despite supporting _Complex int, GCC requires a real floating point type
6524     // for the operands of __builtin_complex.
6525     if (!T->isRealFloatingType()) {
6526       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6527              << Arg->getType() << Arg->getSourceRange();
6528     }
6529 
6530     ExprResult Converted = DefaultLvalueConversion(Arg);
6531     if (Converted.isInvalid())
6532       return true;
6533     TheCall->setArg(I, Converted.get());
6534   }
6535 
6536   if (Dependent) {
6537     TheCall->setType(Context.DependentTy);
6538     return false;
6539   }
6540 
6541   Expr *Real = TheCall->getArg(0);
6542   Expr *Imag = TheCall->getArg(1);
6543   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6544     return Diag(Real->getBeginLoc(),
6545                 diag::err_typecheck_call_different_arg_types)
6546            << Real->getType() << Imag->getType()
6547            << Real->getSourceRange() << Imag->getSourceRange();
6548   }
6549 
6550   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6551   // don't allow this builtin to form those types either.
6552   // FIXME: Should we allow these types?
6553   if (Real->getType()->isFloat16Type())
6554     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6555            << "_Float16";
6556   if (Real->getType()->isHalfType())
6557     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6558            << "half";
6559 
6560   TheCall->setType(Context.getComplexType(Real->getType()));
6561   return false;
6562 }
6563 
6564 // Customized Sema Checking for VSX builtins that have the following signature:
6565 // vector [...] builtinName(vector [...], vector [...], const int);
6566 // Which takes the same type of vectors (any legal vector type) for the first
6567 // two arguments and takes compile time constant for the third argument.
6568 // Example builtins are :
6569 // vector double vec_xxpermdi(vector double, vector double, int);
6570 // vector short vec_xxsldwi(vector short, vector short, int);
6571 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6572   unsigned ExpectedNumArgs = 3;
6573   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6574     return true;
6575 
6576   // Check the third argument is a compile time constant
6577   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6578     return Diag(TheCall->getBeginLoc(),
6579                 diag::err_vsx_builtin_nonconstant_argument)
6580            << 3 /* argument index */ << TheCall->getDirectCallee()
6581            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6582                           TheCall->getArg(2)->getEndLoc());
6583 
6584   QualType Arg1Ty = TheCall->getArg(0)->getType();
6585   QualType Arg2Ty = TheCall->getArg(1)->getType();
6586 
6587   // Check the type of argument 1 and argument 2 are vectors.
6588   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6589   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6590       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6591     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6592            << TheCall->getDirectCallee()
6593            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6594                           TheCall->getArg(1)->getEndLoc());
6595   }
6596 
6597   // Check the first two arguments are the same type.
6598   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6599     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6600            << TheCall->getDirectCallee()
6601            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6602                           TheCall->getArg(1)->getEndLoc());
6603   }
6604 
6605   // When default clang type checking is turned off and the customized type
6606   // checking is used, the returning type of the function must be explicitly
6607   // set. Otherwise it is _Bool by default.
6608   TheCall->setType(Arg1Ty);
6609 
6610   return false;
6611 }
6612 
6613 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6614 // This is declared to take (...), so we have to check everything.
6615 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6616   if (TheCall->getNumArgs() < 2)
6617     return ExprError(Diag(TheCall->getEndLoc(),
6618                           diag::err_typecheck_call_too_few_args_at_least)
6619                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6620                      << TheCall->getSourceRange());
6621 
6622   // Determine which of the following types of shufflevector we're checking:
6623   // 1) unary, vector mask: (lhs, mask)
6624   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6625   QualType resType = TheCall->getArg(0)->getType();
6626   unsigned numElements = 0;
6627 
6628   if (!TheCall->getArg(0)->isTypeDependent() &&
6629       !TheCall->getArg(1)->isTypeDependent()) {
6630     QualType LHSType = TheCall->getArg(0)->getType();
6631     QualType RHSType = TheCall->getArg(1)->getType();
6632 
6633     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6634       return ExprError(
6635           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6636           << TheCall->getDirectCallee()
6637           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6638                          TheCall->getArg(1)->getEndLoc()));
6639 
6640     numElements = LHSType->castAs<VectorType>()->getNumElements();
6641     unsigned numResElements = TheCall->getNumArgs() - 2;
6642 
6643     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6644     // with mask.  If so, verify that RHS is an integer vector type with the
6645     // same number of elts as lhs.
6646     if (TheCall->getNumArgs() == 2) {
6647       if (!RHSType->hasIntegerRepresentation() ||
6648           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6649         return ExprError(Diag(TheCall->getBeginLoc(),
6650                               diag::err_vec_builtin_incompatible_vector)
6651                          << TheCall->getDirectCallee()
6652                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6653                                         TheCall->getArg(1)->getEndLoc()));
6654     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6655       return ExprError(Diag(TheCall->getBeginLoc(),
6656                             diag::err_vec_builtin_incompatible_vector)
6657                        << TheCall->getDirectCallee()
6658                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6659                                       TheCall->getArg(1)->getEndLoc()));
6660     } else if (numElements != numResElements) {
6661       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6662       resType = Context.getVectorType(eltType, numResElements,
6663                                       VectorType::GenericVector);
6664     }
6665   }
6666 
6667   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6668     if (TheCall->getArg(i)->isTypeDependent() ||
6669         TheCall->getArg(i)->isValueDependent())
6670       continue;
6671 
6672     Optional<llvm::APSInt> Result;
6673     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6674       return ExprError(Diag(TheCall->getBeginLoc(),
6675                             diag::err_shufflevector_nonconstant_argument)
6676                        << TheCall->getArg(i)->getSourceRange());
6677 
6678     // Allow -1 which will be translated to undef in the IR.
6679     if (Result->isSigned() && Result->isAllOnes())
6680       continue;
6681 
6682     if (Result->getActiveBits() > 64 ||
6683         Result->getZExtValue() >= numElements * 2)
6684       return ExprError(Diag(TheCall->getBeginLoc(),
6685                             diag::err_shufflevector_argument_too_large)
6686                        << TheCall->getArg(i)->getSourceRange());
6687   }
6688 
6689   SmallVector<Expr*, 32> exprs;
6690 
6691   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6692     exprs.push_back(TheCall->getArg(i));
6693     TheCall->setArg(i, nullptr);
6694   }
6695 
6696   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6697                                          TheCall->getCallee()->getBeginLoc(),
6698                                          TheCall->getRParenLoc());
6699 }
6700 
6701 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6702 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6703                                        SourceLocation BuiltinLoc,
6704                                        SourceLocation RParenLoc) {
6705   ExprValueKind VK = VK_PRValue;
6706   ExprObjectKind OK = OK_Ordinary;
6707   QualType DstTy = TInfo->getType();
6708   QualType SrcTy = E->getType();
6709 
6710   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6711     return ExprError(Diag(BuiltinLoc,
6712                           diag::err_convertvector_non_vector)
6713                      << E->getSourceRange());
6714   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6715     return ExprError(Diag(BuiltinLoc,
6716                           diag::err_convertvector_non_vector_type));
6717 
6718   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6719     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6720     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6721     if (SrcElts != DstElts)
6722       return ExprError(Diag(BuiltinLoc,
6723                             diag::err_convertvector_incompatible_vector)
6724                        << E->getSourceRange());
6725   }
6726 
6727   return new (Context)
6728       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6729 }
6730 
6731 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6732 // This is declared to take (const void*, ...) and can take two
6733 // optional constant int args.
6734 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6735   unsigned NumArgs = TheCall->getNumArgs();
6736 
6737   if (NumArgs > 3)
6738     return Diag(TheCall->getEndLoc(),
6739                 diag::err_typecheck_call_too_many_args_at_most)
6740            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6741 
6742   // Argument 0 is checked for us and the remaining arguments must be
6743   // constant integers.
6744   for (unsigned i = 1; i != NumArgs; ++i)
6745     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6746       return true;
6747 
6748   return false;
6749 }
6750 
6751 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6752 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6753   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6754     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6755            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6756   if (checkArgCount(*this, TheCall, 1))
6757     return true;
6758   Expr *Arg = TheCall->getArg(0);
6759   if (Arg->isInstantiationDependent())
6760     return false;
6761 
6762   QualType ArgTy = Arg->getType();
6763   if (!ArgTy->hasFloatingRepresentation())
6764     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6765            << ArgTy;
6766   if (Arg->isLValue()) {
6767     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6768     TheCall->setArg(0, FirstArg.get());
6769   }
6770   TheCall->setType(TheCall->getArg(0)->getType());
6771   return false;
6772 }
6773 
6774 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6775 // __assume does not evaluate its arguments, and should warn if its argument
6776 // has side effects.
6777 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6778   Expr *Arg = TheCall->getArg(0);
6779   if (Arg->isInstantiationDependent()) return false;
6780 
6781   if (Arg->HasSideEffects(Context))
6782     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6783         << Arg->getSourceRange()
6784         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6785 
6786   return false;
6787 }
6788 
6789 /// Handle __builtin_alloca_with_align. This is declared
6790 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6791 /// than 8.
6792 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6793   // The alignment must be a constant integer.
6794   Expr *Arg = TheCall->getArg(1);
6795 
6796   // We can't check the value of a dependent argument.
6797   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6798     if (const auto *UE =
6799             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6800       if (UE->getKind() == UETT_AlignOf ||
6801           UE->getKind() == UETT_PreferredAlignOf)
6802         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6803             << Arg->getSourceRange();
6804 
6805     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6806 
6807     if (!Result.isPowerOf2())
6808       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6809              << Arg->getSourceRange();
6810 
6811     if (Result < Context.getCharWidth())
6812       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6813              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6814 
6815     if (Result > std::numeric_limits<int32_t>::max())
6816       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6817              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6818   }
6819 
6820   return false;
6821 }
6822 
6823 /// Handle __builtin_assume_aligned. This is declared
6824 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6825 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6826   unsigned NumArgs = TheCall->getNumArgs();
6827 
6828   if (NumArgs > 3)
6829     return Diag(TheCall->getEndLoc(),
6830                 diag::err_typecheck_call_too_many_args_at_most)
6831            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6832 
6833   // The alignment must be a constant integer.
6834   Expr *Arg = TheCall->getArg(1);
6835 
6836   // We can't check the value of a dependent argument.
6837   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6838     llvm::APSInt Result;
6839     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6840       return true;
6841 
6842     if (!Result.isPowerOf2())
6843       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6844              << Arg->getSourceRange();
6845 
6846     if (Result > Sema::MaximumAlignment)
6847       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6848           << Arg->getSourceRange() << Sema::MaximumAlignment;
6849   }
6850 
6851   if (NumArgs > 2) {
6852     ExprResult Arg(TheCall->getArg(2));
6853     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6854       Context.getSizeType(), false);
6855     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6856     if (Arg.isInvalid()) return true;
6857     TheCall->setArg(2, Arg.get());
6858   }
6859 
6860   return false;
6861 }
6862 
6863 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6864   unsigned BuiltinID =
6865       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6866   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6867 
6868   unsigned NumArgs = TheCall->getNumArgs();
6869   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6870   if (NumArgs < NumRequiredArgs) {
6871     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6872            << 0 /* function call */ << NumRequiredArgs << NumArgs
6873            << TheCall->getSourceRange();
6874   }
6875   if (NumArgs >= NumRequiredArgs + 0x100) {
6876     return Diag(TheCall->getEndLoc(),
6877                 diag::err_typecheck_call_too_many_args_at_most)
6878            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6879            << TheCall->getSourceRange();
6880   }
6881   unsigned i = 0;
6882 
6883   // For formatting call, check buffer arg.
6884   if (!IsSizeCall) {
6885     ExprResult Arg(TheCall->getArg(i));
6886     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6887         Context, Context.VoidPtrTy, false);
6888     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6889     if (Arg.isInvalid())
6890       return true;
6891     TheCall->setArg(i, Arg.get());
6892     i++;
6893   }
6894 
6895   // Check string literal arg.
6896   unsigned FormatIdx = i;
6897   {
6898     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6899     if (Arg.isInvalid())
6900       return true;
6901     TheCall->setArg(i, Arg.get());
6902     i++;
6903   }
6904 
6905   // Make sure variadic args are scalar.
6906   unsigned FirstDataArg = i;
6907   while (i < NumArgs) {
6908     ExprResult Arg = DefaultVariadicArgumentPromotion(
6909         TheCall->getArg(i), VariadicFunction, nullptr);
6910     if (Arg.isInvalid())
6911       return true;
6912     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6913     if (ArgSize.getQuantity() >= 0x100) {
6914       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6915              << i << (int)ArgSize.getQuantity() << 0xff
6916              << TheCall->getSourceRange();
6917     }
6918     TheCall->setArg(i, Arg.get());
6919     i++;
6920   }
6921 
6922   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6923   // call to avoid duplicate diagnostics.
6924   if (!IsSizeCall) {
6925     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6926     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6927     bool Success = CheckFormatArguments(
6928         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6929         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6930         CheckedVarArgs);
6931     if (!Success)
6932       return true;
6933   }
6934 
6935   if (IsSizeCall) {
6936     TheCall->setType(Context.getSizeType());
6937   } else {
6938     TheCall->setType(Context.VoidPtrTy);
6939   }
6940   return false;
6941 }
6942 
6943 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6944 /// TheCall is a constant expression.
6945 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6946                                   llvm::APSInt &Result) {
6947   Expr *Arg = TheCall->getArg(ArgNum);
6948   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6949   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6950 
6951   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6952 
6953   Optional<llvm::APSInt> R;
6954   if (!(R = Arg->getIntegerConstantExpr(Context)))
6955     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6956            << FDecl->getDeclName() << Arg->getSourceRange();
6957   Result = *R;
6958   return false;
6959 }
6960 
6961 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6962 /// TheCall is a constant expression in the range [Low, High].
6963 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6964                                        int Low, int High, bool RangeIsError) {
6965   if (isConstantEvaluated())
6966     return false;
6967   llvm::APSInt Result;
6968 
6969   // We can't check the value of a dependent argument.
6970   Expr *Arg = TheCall->getArg(ArgNum);
6971   if (Arg->isTypeDependent() || Arg->isValueDependent())
6972     return false;
6973 
6974   // Check constant-ness first.
6975   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6976     return true;
6977 
6978   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6979     if (RangeIsError)
6980       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6981              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6982     else
6983       // Defer the warning until we know if the code will be emitted so that
6984       // dead code can ignore this.
6985       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6986                           PDiag(diag::warn_argument_invalid_range)
6987                               << toString(Result, 10) << Low << High
6988                               << Arg->getSourceRange());
6989   }
6990 
6991   return false;
6992 }
6993 
6994 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6995 /// TheCall is a constant expression is a multiple of Num..
6996 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6997                                           unsigned Num) {
6998   llvm::APSInt Result;
6999 
7000   // We can't check the value of a dependent argument.
7001   Expr *Arg = TheCall->getArg(ArgNum);
7002   if (Arg->isTypeDependent() || Arg->isValueDependent())
7003     return false;
7004 
7005   // Check constant-ness first.
7006   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7007     return true;
7008 
7009   if (Result.getSExtValue() % Num != 0)
7010     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
7011            << Num << Arg->getSourceRange();
7012 
7013   return false;
7014 }
7015 
7016 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
7017 /// constant expression representing a power of 2.
7018 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
7019   llvm::APSInt Result;
7020 
7021   // We can't check the value of a dependent argument.
7022   Expr *Arg = TheCall->getArg(ArgNum);
7023   if (Arg->isTypeDependent() || Arg->isValueDependent())
7024     return false;
7025 
7026   // Check constant-ness first.
7027   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7028     return true;
7029 
7030   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7031   // and only if x is a power of 2.
7032   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7033     return false;
7034 
7035   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7036          << Arg->getSourceRange();
7037 }
7038 
7039 static bool IsShiftedByte(llvm::APSInt Value) {
7040   if (Value.isNegative())
7041     return false;
7042 
7043   // Check if it's a shifted byte, by shifting it down
7044   while (true) {
7045     // If the value fits in the bottom byte, the check passes.
7046     if (Value < 0x100)
7047       return true;
7048 
7049     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7050     // fails.
7051     if ((Value & 0xFF) != 0)
7052       return false;
7053 
7054     // If the bottom 8 bits are all 0, but something above that is nonzero,
7055     // then shifting the value right by 8 bits won't affect whether it's a
7056     // shifted byte or not. So do that, and go round again.
7057     Value >>= 8;
7058   }
7059 }
7060 
7061 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7062 /// a constant expression representing an arbitrary byte value shifted left by
7063 /// a multiple of 8 bits.
7064 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7065                                              unsigned ArgBits) {
7066   llvm::APSInt Result;
7067 
7068   // We can't check the value of a dependent argument.
7069   Expr *Arg = TheCall->getArg(ArgNum);
7070   if (Arg->isTypeDependent() || Arg->isValueDependent())
7071     return false;
7072 
7073   // Check constant-ness first.
7074   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7075     return true;
7076 
7077   // Truncate to the given size.
7078   Result = Result.getLoBits(ArgBits);
7079   Result.setIsUnsigned(true);
7080 
7081   if (IsShiftedByte(Result))
7082     return false;
7083 
7084   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7085          << Arg->getSourceRange();
7086 }
7087 
7088 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7089 /// TheCall is a constant expression representing either a shifted byte value,
7090 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7091 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7092 /// Arm MVE intrinsics.
7093 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7094                                                    int ArgNum,
7095                                                    unsigned ArgBits) {
7096   llvm::APSInt Result;
7097 
7098   // We can't check the value of a dependent argument.
7099   Expr *Arg = TheCall->getArg(ArgNum);
7100   if (Arg->isTypeDependent() || Arg->isValueDependent())
7101     return false;
7102 
7103   // Check constant-ness first.
7104   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7105     return true;
7106 
7107   // Truncate to the given size.
7108   Result = Result.getLoBits(ArgBits);
7109   Result.setIsUnsigned(true);
7110 
7111   // Check to see if it's in either of the required forms.
7112   if (IsShiftedByte(Result) ||
7113       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7114     return false;
7115 
7116   return Diag(TheCall->getBeginLoc(),
7117               diag::err_argument_not_shifted_byte_or_xxff)
7118          << Arg->getSourceRange();
7119 }
7120 
7121 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7122 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7123   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7124     if (checkArgCount(*this, TheCall, 2))
7125       return true;
7126     Expr *Arg0 = TheCall->getArg(0);
7127     Expr *Arg1 = TheCall->getArg(1);
7128 
7129     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7130     if (FirstArg.isInvalid())
7131       return true;
7132     QualType FirstArgType = FirstArg.get()->getType();
7133     if (!FirstArgType->isAnyPointerType())
7134       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7135                << "first" << FirstArgType << Arg0->getSourceRange();
7136     TheCall->setArg(0, FirstArg.get());
7137 
7138     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7139     if (SecArg.isInvalid())
7140       return true;
7141     QualType SecArgType = SecArg.get()->getType();
7142     if (!SecArgType->isIntegerType())
7143       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7144                << "second" << SecArgType << Arg1->getSourceRange();
7145 
7146     // Derive the return type from the pointer argument.
7147     TheCall->setType(FirstArgType);
7148     return false;
7149   }
7150 
7151   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7152     if (checkArgCount(*this, TheCall, 2))
7153       return true;
7154 
7155     Expr *Arg0 = TheCall->getArg(0);
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     // Derive the return type from the pointer argument.
7166     TheCall->setType(FirstArgType);
7167 
7168     // Second arg must be an constant in range [0,15]
7169     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7170   }
7171 
7172   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7173     if (checkArgCount(*this, TheCall, 2))
7174       return true;
7175     Expr *Arg0 = TheCall->getArg(0);
7176     Expr *Arg1 = TheCall->getArg(1);
7177 
7178     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7179     if (FirstArg.isInvalid())
7180       return true;
7181     QualType FirstArgType = FirstArg.get()->getType();
7182     if (!FirstArgType->isAnyPointerType())
7183       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7184                << "first" << FirstArgType << Arg0->getSourceRange();
7185 
7186     QualType SecArgType = Arg1->getType();
7187     if (!SecArgType->isIntegerType())
7188       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7189                << "second" << SecArgType << Arg1->getSourceRange();
7190     TheCall->setType(Context.IntTy);
7191     return false;
7192   }
7193 
7194   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7195       BuiltinID == AArch64::BI__builtin_arm_stg) {
7196     if (checkArgCount(*this, TheCall, 1))
7197       return true;
7198     Expr *Arg0 = TheCall->getArg(0);
7199     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7200     if (FirstArg.isInvalid())
7201       return true;
7202 
7203     QualType FirstArgType = FirstArg.get()->getType();
7204     if (!FirstArgType->isAnyPointerType())
7205       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7206                << "first" << FirstArgType << Arg0->getSourceRange();
7207     TheCall->setArg(0, FirstArg.get());
7208 
7209     // Derive the return type from the pointer argument.
7210     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7211       TheCall->setType(FirstArgType);
7212     return false;
7213   }
7214 
7215   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7216     Expr *ArgA = TheCall->getArg(0);
7217     Expr *ArgB = TheCall->getArg(1);
7218 
7219     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7220     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7221 
7222     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7223       return true;
7224 
7225     QualType ArgTypeA = ArgExprA.get()->getType();
7226     QualType ArgTypeB = ArgExprB.get()->getType();
7227 
7228     auto isNull = [&] (Expr *E) -> bool {
7229       return E->isNullPointerConstant(
7230                         Context, Expr::NPC_ValueDependentIsNotNull); };
7231 
7232     // argument should be either a pointer or null
7233     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7234       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7235         << "first" << ArgTypeA << ArgA->getSourceRange();
7236 
7237     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7238       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7239         << "second" << ArgTypeB << ArgB->getSourceRange();
7240 
7241     // Ensure Pointee types are compatible
7242     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7243         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7244       QualType pointeeA = ArgTypeA->getPointeeType();
7245       QualType pointeeB = ArgTypeB->getPointeeType();
7246       if (!Context.typesAreCompatible(
7247              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7248              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7249         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7250           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7251           << ArgB->getSourceRange();
7252       }
7253     }
7254 
7255     // at least one argument should be pointer type
7256     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7257       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7258         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7259 
7260     if (isNull(ArgA)) // adopt type of the other pointer
7261       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7262 
7263     if (isNull(ArgB))
7264       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7265 
7266     TheCall->setArg(0, ArgExprA.get());
7267     TheCall->setArg(1, ArgExprB.get());
7268     TheCall->setType(Context.LongLongTy);
7269     return false;
7270   }
7271   assert(false && "Unhandled ARM MTE intrinsic");
7272   return true;
7273 }
7274 
7275 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7276 /// TheCall is an ARM/AArch64 special register string literal.
7277 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7278                                     int ArgNum, unsigned ExpectedFieldNum,
7279                                     bool AllowName) {
7280   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7281                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7282                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7283                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7284                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7285                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7286   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7287                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7288                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7289                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7290                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7291                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7292   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7293 
7294   // We can't check the value of a dependent argument.
7295   Expr *Arg = TheCall->getArg(ArgNum);
7296   if (Arg->isTypeDependent() || Arg->isValueDependent())
7297     return false;
7298 
7299   // Check if the argument is a string literal.
7300   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7301     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7302            << Arg->getSourceRange();
7303 
7304   // Check the type of special register given.
7305   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7306   SmallVector<StringRef, 6> Fields;
7307   Reg.split(Fields, ":");
7308 
7309   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7310     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7311            << Arg->getSourceRange();
7312 
7313   // If the string is the name of a register then we cannot check that it is
7314   // valid here but if the string is of one the forms described in ACLE then we
7315   // can check that the supplied fields are integers and within the valid
7316   // ranges.
7317   if (Fields.size() > 1) {
7318     bool FiveFields = Fields.size() == 5;
7319 
7320     bool ValidString = true;
7321     if (IsARMBuiltin) {
7322       ValidString &= Fields[0].startswith_insensitive("cp") ||
7323                      Fields[0].startswith_insensitive("p");
7324       if (ValidString)
7325         Fields[0] = Fields[0].drop_front(
7326             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7327 
7328       ValidString &= Fields[2].startswith_insensitive("c");
7329       if (ValidString)
7330         Fields[2] = Fields[2].drop_front(1);
7331 
7332       if (FiveFields) {
7333         ValidString &= Fields[3].startswith_insensitive("c");
7334         if (ValidString)
7335           Fields[3] = Fields[3].drop_front(1);
7336       }
7337     }
7338 
7339     SmallVector<int, 5> Ranges;
7340     if (FiveFields)
7341       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7342     else
7343       Ranges.append({15, 7, 15});
7344 
7345     for (unsigned i=0; i<Fields.size(); ++i) {
7346       int IntField;
7347       ValidString &= !Fields[i].getAsInteger(10, IntField);
7348       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7349     }
7350 
7351     if (!ValidString)
7352       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7353              << Arg->getSourceRange();
7354   } else if (IsAArch64Builtin && Fields.size() == 1) {
7355     // If the register name is one of those that appear in the condition below
7356     // and the special register builtin being used is one of the write builtins,
7357     // then we require that the argument provided for writing to the register
7358     // is an integer constant expression. This is because it will be lowered to
7359     // an MSR (immediate) instruction, so we need to know the immediate at
7360     // compile time.
7361     if (TheCall->getNumArgs() != 2)
7362       return false;
7363 
7364     std::string RegLower = Reg.lower();
7365     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7366         RegLower != "pan" && RegLower != "uao")
7367       return false;
7368 
7369     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7370   }
7371 
7372   return false;
7373 }
7374 
7375 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7376 /// Emit an error and return true on failure; return false on success.
7377 /// TypeStr is a string containing the type descriptor of the value returned by
7378 /// the builtin and the descriptors of the expected type of the arguments.
7379 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7380                                  const char *TypeStr) {
7381 
7382   assert((TypeStr[0] != '\0') &&
7383          "Invalid types in PPC MMA builtin declaration");
7384 
7385   switch (BuiltinID) {
7386   default:
7387     // This function is called in CheckPPCBuiltinFunctionCall where the
7388     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7389     // we are isolating the pair vector memop builtins that can be used with mma
7390     // off so the default case is every builtin that requires mma and paired
7391     // vector memops.
7392     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7393                          diag::err_ppc_builtin_only_on_arch, "10") ||
7394         SemaFeatureCheck(*this, TheCall, "mma",
7395                          diag::err_ppc_builtin_only_on_arch, "10"))
7396       return true;
7397     break;
7398   case PPC::BI__builtin_vsx_lxvp:
7399   case PPC::BI__builtin_vsx_stxvp:
7400   case PPC::BI__builtin_vsx_assemble_pair:
7401   case PPC::BI__builtin_vsx_disassemble_pair:
7402     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7403                          diag::err_ppc_builtin_only_on_arch, "10"))
7404       return true;
7405     break;
7406   }
7407 
7408   unsigned Mask = 0;
7409   unsigned ArgNum = 0;
7410 
7411   // The first type in TypeStr is the type of the value returned by the
7412   // builtin. So we first read that type and change the type of TheCall.
7413   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7414   TheCall->setType(type);
7415 
7416   while (*TypeStr != '\0') {
7417     Mask = 0;
7418     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7419     if (ArgNum >= TheCall->getNumArgs()) {
7420       ArgNum++;
7421       break;
7422     }
7423 
7424     Expr *Arg = TheCall->getArg(ArgNum);
7425     QualType PassedType = Arg->getType();
7426     QualType StrippedRVType = PassedType.getCanonicalType();
7427 
7428     // Strip Restrict/Volatile qualifiers.
7429     if (StrippedRVType.isRestrictQualified() ||
7430         StrippedRVType.isVolatileQualified())
7431       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7432 
7433     // The only case where the argument type and expected type are allowed to
7434     // mismatch is if the argument type is a non-void pointer and expected type
7435     // is a void pointer.
7436     if (StrippedRVType != ExpectedType)
7437       if (!(ExpectedType->isVoidPointerType() &&
7438             StrippedRVType->isPointerType()))
7439         return Diag(Arg->getBeginLoc(),
7440                     diag::err_typecheck_convert_incompatible)
7441                << PassedType << ExpectedType << 1 << 0 << 0;
7442 
7443     // If the value of the Mask is not 0, we have a constraint in the size of
7444     // the integer argument so here we ensure the argument is a constant that
7445     // is in the valid range.
7446     if (Mask != 0 &&
7447         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7448       return true;
7449 
7450     ArgNum++;
7451   }
7452 
7453   // In case we exited early from the previous loop, there are other types to
7454   // read from TypeStr. So we need to read them all to ensure we have the right
7455   // number of arguments in TheCall and if it is not the case, to display a
7456   // better error message.
7457   while (*TypeStr != '\0') {
7458     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7459     ArgNum++;
7460   }
7461   if (checkArgCount(*this, TheCall, ArgNum))
7462     return true;
7463 
7464   return false;
7465 }
7466 
7467 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7468 /// This checks that the target supports __builtin_longjmp and
7469 /// that val is a constant 1.
7470 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7471   if (!Context.getTargetInfo().hasSjLjLowering())
7472     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7473            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7474 
7475   Expr *Arg = TheCall->getArg(1);
7476   llvm::APSInt Result;
7477 
7478   // TODO: This is less than ideal. Overload this to take a value.
7479   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7480     return true;
7481 
7482   if (Result != 1)
7483     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7484            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7485 
7486   return false;
7487 }
7488 
7489 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7490 /// This checks that the target supports __builtin_setjmp.
7491 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7492   if (!Context.getTargetInfo().hasSjLjLowering())
7493     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7494            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7495   return false;
7496 }
7497 
7498 namespace {
7499 
7500 class UncoveredArgHandler {
7501   enum { Unknown = -1, AllCovered = -2 };
7502 
7503   signed FirstUncoveredArg = Unknown;
7504   SmallVector<const Expr *, 4> DiagnosticExprs;
7505 
7506 public:
7507   UncoveredArgHandler() = default;
7508 
7509   bool hasUncoveredArg() const {
7510     return (FirstUncoveredArg >= 0);
7511   }
7512 
7513   unsigned getUncoveredArg() const {
7514     assert(hasUncoveredArg() && "no uncovered argument");
7515     return FirstUncoveredArg;
7516   }
7517 
7518   void setAllCovered() {
7519     // A string has been found with all arguments covered, so clear out
7520     // the diagnostics.
7521     DiagnosticExprs.clear();
7522     FirstUncoveredArg = AllCovered;
7523   }
7524 
7525   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7526     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7527 
7528     // Don't update if a previous string covers all arguments.
7529     if (FirstUncoveredArg == AllCovered)
7530       return;
7531 
7532     // UncoveredArgHandler tracks the highest uncovered argument index
7533     // and with it all the strings that match this index.
7534     if (NewFirstUncoveredArg == FirstUncoveredArg)
7535       DiagnosticExprs.push_back(StrExpr);
7536     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7537       DiagnosticExprs.clear();
7538       DiagnosticExprs.push_back(StrExpr);
7539       FirstUncoveredArg = NewFirstUncoveredArg;
7540     }
7541   }
7542 
7543   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7544 };
7545 
7546 enum StringLiteralCheckType {
7547   SLCT_NotALiteral,
7548   SLCT_UncheckedLiteral,
7549   SLCT_CheckedLiteral
7550 };
7551 
7552 } // namespace
7553 
7554 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7555                                      BinaryOperatorKind BinOpKind,
7556                                      bool AddendIsRight) {
7557   unsigned BitWidth = Offset.getBitWidth();
7558   unsigned AddendBitWidth = Addend.getBitWidth();
7559   // There might be negative interim results.
7560   if (Addend.isUnsigned()) {
7561     Addend = Addend.zext(++AddendBitWidth);
7562     Addend.setIsSigned(true);
7563   }
7564   // Adjust the bit width of the APSInts.
7565   if (AddendBitWidth > BitWidth) {
7566     Offset = Offset.sext(AddendBitWidth);
7567     BitWidth = AddendBitWidth;
7568   } else if (BitWidth > AddendBitWidth) {
7569     Addend = Addend.sext(BitWidth);
7570   }
7571 
7572   bool Ov = false;
7573   llvm::APSInt ResOffset = Offset;
7574   if (BinOpKind == BO_Add)
7575     ResOffset = Offset.sadd_ov(Addend, Ov);
7576   else {
7577     assert(AddendIsRight && BinOpKind == BO_Sub &&
7578            "operator must be add or sub with addend on the right");
7579     ResOffset = Offset.ssub_ov(Addend, Ov);
7580   }
7581 
7582   // We add an offset to a pointer here so we should support an offset as big as
7583   // possible.
7584   if (Ov) {
7585     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7586            "index (intermediate) result too big");
7587     Offset = Offset.sext(2 * BitWidth);
7588     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7589     return;
7590   }
7591 
7592   Offset = ResOffset;
7593 }
7594 
7595 namespace {
7596 
7597 // This is a wrapper class around StringLiteral to support offsetted string
7598 // literals as format strings. It takes the offset into account when returning
7599 // the string and its length or the source locations to display notes correctly.
7600 class FormatStringLiteral {
7601   const StringLiteral *FExpr;
7602   int64_t Offset;
7603 
7604  public:
7605   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7606       : FExpr(fexpr), Offset(Offset) {}
7607 
7608   StringRef getString() const {
7609     return FExpr->getString().drop_front(Offset);
7610   }
7611 
7612   unsigned getByteLength() const {
7613     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7614   }
7615 
7616   unsigned getLength() const { return FExpr->getLength() - Offset; }
7617   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7618 
7619   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7620 
7621   QualType getType() const { return FExpr->getType(); }
7622 
7623   bool isAscii() const { return FExpr->isAscii(); }
7624   bool isWide() const { return FExpr->isWide(); }
7625   bool isUTF8() const { return FExpr->isUTF8(); }
7626   bool isUTF16() const { return FExpr->isUTF16(); }
7627   bool isUTF32() const { return FExpr->isUTF32(); }
7628   bool isPascal() const { return FExpr->isPascal(); }
7629 
7630   SourceLocation getLocationOfByte(
7631       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7632       const TargetInfo &Target, unsigned *StartToken = nullptr,
7633       unsigned *StartTokenByteOffset = nullptr) const {
7634     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7635                                     StartToken, StartTokenByteOffset);
7636   }
7637 
7638   SourceLocation getBeginLoc() const LLVM_READONLY {
7639     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7640   }
7641 
7642   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7643 };
7644 
7645 }  // namespace
7646 
7647 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7648                               const Expr *OrigFormatExpr,
7649                               ArrayRef<const Expr *> Args,
7650                               bool HasVAListArg, unsigned format_idx,
7651                               unsigned firstDataArg,
7652                               Sema::FormatStringType Type,
7653                               bool inFunctionCall,
7654                               Sema::VariadicCallType CallType,
7655                               llvm::SmallBitVector &CheckedVarArgs,
7656                               UncoveredArgHandler &UncoveredArg,
7657                               bool IgnoreStringsWithoutSpecifiers);
7658 
7659 // Determine if an expression is a string literal or constant string.
7660 // If this function returns false on the arguments to a function expecting a
7661 // format string, we will usually need to emit a warning.
7662 // True string literals are then checked by CheckFormatString.
7663 static StringLiteralCheckType
7664 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7665                       bool HasVAListArg, unsigned format_idx,
7666                       unsigned firstDataArg, Sema::FormatStringType Type,
7667                       Sema::VariadicCallType CallType, bool InFunctionCall,
7668                       llvm::SmallBitVector &CheckedVarArgs,
7669                       UncoveredArgHandler &UncoveredArg,
7670                       llvm::APSInt Offset,
7671                       bool IgnoreStringsWithoutSpecifiers = false) {
7672   if (S.isConstantEvaluated())
7673     return SLCT_NotALiteral;
7674  tryAgain:
7675   assert(Offset.isSigned() && "invalid offset");
7676 
7677   if (E->isTypeDependent() || E->isValueDependent())
7678     return SLCT_NotALiteral;
7679 
7680   E = E->IgnoreParenCasts();
7681 
7682   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7683     // Technically -Wformat-nonliteral does not warn about this case.
7684     // The behavior of printf and friends in this case is implementation
7685     // dependent.  Ideally if the format string cannot be null then
7686     // it should have a 'nonnull' attribute in the function prototype.
7687     return SLCT_UncheckedLiteral;
7688 
7689   switch (E->getStmtClass()) {
7690   case Stmt::BinaryConditionalOperatorClass:
7691   case Stmt::ConditionalOperatorClass: {
7692     // The expression is a literal if both sub-expressions were, and it was
7693     // completely checked only if both sub-expressions were checked.
7694     const AbstractConditionalOperator *C =
7695         cast<AbstractConditionalOperator>(E);
7696 
7697     // Determine whether it is necessary to check both sub-expressions, for
7698     // example, because the condition expression is a constant that can be
7699     // evaluated at compile time.
7700     bool CheckLeft = true, CheckRight = true;
7701 
7702     bool Cond;
7703     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7704                                                  S.isConstantEvaluated())) {
7705       if (Cond)
7706         CheckRight = false;
7707       else
7708         CheckLeft = false;
7709     }
7710 
7711     // We need to maintain the offsets for the right and the left hand side
7712     // separately to check if every possible indexed expression is a valid
7713     // string literal. They might have different offsets for different string
7714     // literals in the end.
7715     StringLiteralCheckType Left;
7716     if (!CheckLeft)
7717       Left = SLCT_UncheckedLiteral;
7718     else {
7719       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7720                                    HasVAListArg, format_idx, firstDataArg,
7721                                    Type, CallType, InFunctionCall,
7722                                    CheckedVarArgs, UncoveredArg, Offset,
7723                                    IgnoreStringsWithoutSpecifiers);
7724       if (Left == SLCT_NotALiteral || !CheckRight) {
7725         return Left;
7726       }
7727     }
7728 
7729     StringLiteralCheckType Right = checkFormatStringExpr(
7730         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7731         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7732         IgnoreStringsWithoutSpecifiers);
7733 
7734     return (CheckLeft && Left < Right) ? Left : Right;
7735   }
7736 
7737   case Stmt::ImplicitCastExprClass:
7738     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7739     goto tryAgain;
7740 
7741   case Stmt::OpaqueValueExprClass:
7742     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7743       E = src;
7744       goto tryAgain;
7745     }
7746     return SLCT_NotALiteral;
7747 
7748   case Stmt::PredefinedExprClass:
7749     // While __func__, etc., are technically not string literals, they
7750     // cannot contain format specifiers and thus are not a security
7751     // liability.
7752     return SLCT_UncheckedLiteral;
7753 
7754   case Stmt::DeclRefExprClass: {
7755     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7756 
7757     // As an exception, do not flag errors for variables binding to
7758     // const string literals.
7759     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7760       bool isConstant = false;
7761       QualType T = DR->getType();
7762 
7763       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7764         isConstant = AT->getElementType().isConstant(S.Context);
7765       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7766         isConstant = T.isConstant(S.Context) &&
7767                      PT->getPointeeType().isConstant(S.Context);
7768       } else if (T->isObjCObjectPointerType()) {
7769         // In ObjC, there is usually no "const ObjectPointer" type,
7770         // so don't check if the pointee type is constant.
7771         isConstant = T.isConstant(S.Context);
7772       }
7773 
7774       if (isConstant) {
7775         if (const Expr *Init = VD->getAnyInitializer()) {
7776           // Look through initializers like const char c[] = { "foo" }
7777           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7778             if (InitList->isStringLiteralInit())
7779               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7780           }
7781           return checkFormatStringExpr(S, Init, Args,
7782                                        HasVAListArg, format_idx,
7783                                        firstDataArg, Type, CallType,
7784                                        /*InFunctionCall*/ false, CheckedVarArgs,
7785                                        UncoveredArg, Offset);
7786         }
7787       }
7788 
7789       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7790       // special check to see if the format string is a function parameter
7791       // of the function calling the printf function.  If the function
7792       // has an attribute indicating it is a printf-like function, then we
7793       // should suppress warnings concerning non-literals being used in a call
7794       // to a vprintf function.  For example:
7795       //
7796       // void
7797       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7798       //      va_list ap;
7799       //      va_start(ap, fmt);
7800       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7801       //      ...
7802       // }
7803       if (HasVAListArg) {
7804         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7805           if (const Decl *D = dyn_cast<Decl>(PV->getDeclContext())) {
7806             int PVIndex = PV->getFunctionScopeIndex() + 1;
7807             for (const auto *PVFormat : D->specific_attrs<FormatAttr>()) {
7808               // adjust for implicit parameter
7809               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
7810                 if (MD->isInstance())
7811                   ++PVIndex;
7812               // We also check if the formats are compatible.
7813               // We can't pass a 'scanf' string to a 'printf' function.
7814               if (PVIndex == PVFormat->getFormatIdx() &&
7815                   Type == S.GetFormatStringType(PVFormat))
7816                 return SLCT_UncheckedLiteral;
7817             }
7818           }
7819         }
7820       }
7821     }
7822 
7823     return SLCT_NotALiteral;
7824   }
7825 
7826   case Stmt::CallExprClass:
7827   case Stmt::CXXMemberCallExprClass: {
7828     const CallExpr *CE = cast<CallExpr>(E);
7829     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7830       bool IsFirst = true;
7831       StringLiteralCheckType CommonResult;
7832       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7833         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7834         StringLiteralCheckType Result = checkFormatStringExpr(
7835             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7836             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7837             IgnoreStringsWithoutSpecifiers);
7838         if (IsFirst) {
7839           CommonResult = Result;
7840           IsFirst = false;
7841         }
7842       }
7843       if (!IsFirst)
7844         return CommonResult;
7845 
7846       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7847         unsigned BuiltinID = FD->getBuiltinID();
7848         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7849             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7850           const Expr *Arg = CE->getArg(0);
7851           return checkFormatStringExpr(S, Arg, Args,
7852                                        HasVAListArg, format_idx,
7853                                        firstDataArg, Type, CallType,
7854                                        InFunctionCall, CheckedVarArgs,
7855                                        UncoveredArg, Offset,
7856                                        IgnoreStringsWithoutSpecifiers);
7857         }
7858       }
7859     }
7860 
7861     return SLCT_NotALiteral;
7862   }
7863   case Stmt::ObjCMessageExprClass: {
7864     const auto *ME = cast<ObjCMessageExpr>(E);
7865     if (const auto *MD = ME->getMethodDecl()) {
7866       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7867         // As a special case heuristic, if we're using the method -[NSBundle
7868         // localizedStringForKey:value:table:], ignore any key strings that lack
7869         // format specifiers. The idea is that if the key doesn't have any
7870         // format specifiers then its probably just a key to map to the
7871         // localized strings. If it does have format specifiers though, then its
7872         // likely that the text of the key is the format string in the
7873         // programmer's language, and should be checked.
7874         const ObjCInterfaceDecl *IFace;
7875         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7876             IFace->getIdentifier()->isStr("NSBundle") &&
7877             MD->getSelector().isKeywordSelector(
7878                 {"localizedStringForKey", "value", "table"})) {
7879           IgnoreStringsWithoutSpecifiers = true;
7880         }
7881 
7882         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7883         return checkFormatStringExpr(
7884             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7885             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7886             IgnoreStringsWithoutSpecifiers);
7887       }
7888     }
7889 
7890     return SLCT_NotALiteral;
7891   }
7892   case Stmt::ObjCStringLiteralClass:
7893   case Stmt::StringLiteralClass: {
7894     const StringLiteral *StrE = nullptr;
7895 
7896     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7897       StrE = ObjCFExpr->getString();
7898     else
7899       StrE = cast<StringLiteral>(E);
7900 
7901     if (StrE) {
7902       if (Offset.isNegative() || Offset > StrE->getLength()) {
7903         // TODO: It would be better to have an explicit warning for out of
7904         // bounds literals.
7905         return SLCT_NotALiteral;
7906       }
7907       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7908       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7909                         firstDataArg, Type, InFunctionCall, CallType,
7910                         CheckedVarArgs, UncoveredArg,
7911                         IgnoreStringsWithoutSpecifiers);
7912       return SLCT_CheckedLiteral;
7913     }
7914 
7915     return SLCT_NotALiteral;
7916   }
7917   case Stmt::BinaryOperatorClass: {
7918     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7919 
7920     // A string literal + an int offset is still a string literal.
7921     if (BinOp->isAdditiveOp()) {
7922       Expr::EvalResult LResult, RResult;
7923 
7924       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7925           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7926       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7927           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7928 
7929       if (LIsInt != RIsInt) {
7930         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7931 
7932         if (LIsInt) {
7933           if (BinOpKind == BO_Add) {
7934             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7935             E = BinOp->getRHS();
7936             goto tryAgain;
7937           }
7938         } else {
7939           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7940           E = BinOp->getLHS();
7941           goto tryAgain;
7942         }
7943       }
7944     }
7945 
7946     return SLCT_NotALiteral;
7947   }
7948   case Stmt::UnaryOperatorClass: {
7949     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7950     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7951     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7952       Expr::EvalResult IndexResult;
7953       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7954                                        Expr::SE_NoSideEffects,
7955                                        S.isConstantEvaluated())) {
7956         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7957                    /*RHS is int*/ true);
7958         E = ASE->getBase();
7959         goto tryAgain;
7960       }
7961     }
7962 
7963     return SLCT_NotALiteral;
7964   }
7965 
7966   default:
7967     return SLCT_NotALiteral;
7968   }
7969 }
7970 
7971 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7972   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7973       .Case("scanf", FST_Scanf)
7974       .Cases("printf", "printf0", FST_Printf)
7975       .Cases("NSString", "CFString", FST_NSString)
7976       .Case("strftime", FST_Strftime)
7977       .Case("strfmon", FST_Strfmon)
7978       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7979       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7980       .Case("os_trace", FST_OSLog)
7981       .Case("os_log", FST_OSLog)
7982       .Default(FST_Unknown);
7983 }
7984 
7985 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7986 /// functions) for correct use of format strings.
7987 /// Returns true if a format string has been fully checked.
7988 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7989                                 ArrayRef<const Expr *> Args,
7990                                 bool IsCXXMember,
7991                                 VariadicCallType CallType,
7992                                 SourceLocation Loc, SourceRange Range,
7993                                 llvm::SmallBitVector &CheckedVarArgs) {
7994   FormatStringInfo FSI;
7995   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7996     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7997                                 FSI.FirstDataArg, GetFormatStringType(Format),
7998                                 CallType, Loc, Range, CheckedVarArgs);
7999   return false;
8000 }
8001 
8002 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
8003                                 bool HasVAListArg, unsigned format_idx,
8004                                 unsigned firstDataArg, FormatStringType Type,
8005                                 VariadicCallType CallType,
8006                                 SourceLocation Loc, SourceRange Range,
8007                                 llvm::SmallBitVector &CheckedVarArgs) {
8008   // CHECK: printf/scanf-like function is called with no format string.
8009   if (format_idx >= Args.size()) {
8010     Diag(Loc, diag::warn_missing_format_string) << Range;
8011     return false;
8012   }
8013 
8014   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
8015 
8016   // CHECK: format string is not a string literal.
8017   //
8018   // Dynamically generated format strings are difficult to
8019   // automatically vet at compile time.  Requiring that format strings
8020   // are string literals: (1) permits the checking of format strings by
8021   // the compiler and thereby (2) can practically remove the source of
8022   // many format string exploits.
8023 
8024   // Format string can be either ObjC string (e.g. @"%d") or
8025   // C string (e.g. "%d")
8026   // ObjC string uses the same format specifiers as C string, so we can use
8027   // the same format string checking logic for both ObjC and C strings.
8028   UncoveredArgHandler UncoveredArg;
8029   StringLiteralCheckType CT =
8030       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8031                             format_idx, firstDataArg, Type, CallType,
8032                             /*IsFunctionCall*/ true, CheckedVarArgs,
8033                             UncoveredArg,
8034                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8035 
8036   // Generate a diagnostic where an uncovered argument is detected.
8037   if (UncoveredArg.hasUncoveredArg()) {
8038     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8039     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8040     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8041   }
8042 
8043   if (CT != SLCT_NotALiteral)
8044     // Literal format string found, check done!
8045     return CT == SLCT_CheckedLiteral;
8046 
8047   // Strftime is particular as it always uses a single 'time' argument,
8048   // so it is safe to pass a non-literal string.
8049   if (Type == FST_Strftime)
8050     return false;
8051 
8052   // Do not emit diag when the string param is a macro expansion and the
8053   // format is either NSString or CFString. This is a hack to prevent
8054   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8055   // which are usually used in place of NS and CF string literals.
8056   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8057   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8058     return false;
8059 
8060   // If there are no arguments specified, warn with -Wformat-security, otherwise
8061   // warn only with -Wformat-nonliteral.
8062   if (Args.size() == firstDataArg) {
8063     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8064       << OrigFormatExpr->getSourceRange();
8065     switch (Type) {
8066     default:
8067       break;
8068     case FST_Kprintf:
8069     case FST_FreeBSDKPrintf:
8070     case FST_Printf:
8071       Diag(FormatLoc, diag::note_format_security_fixit)
8072         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8073       break;
8074     case FST_NSString:
8075       Diag(FormatLoc, diag::note_format_security_fixit)
8076         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8077       break;
8078     }
8079   } else {
8080     Diag(FormatLoc, diag::warn_format_nonliteral)
8081       << OrigFormatExpr->getSourceRange();
8082   }
8083   return false;
8084 }
8085 
8086 namespace {
8087 
8088 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8089 protected:
8090   Sema &S;
8091   const FormatStringLiteral *FExpr;
8092   const Expr *OrigFormatExpr;
8093   const Sema::FormatStringType FSType;
8094   const unsigned FirstDataArg;
8095   const unsigned NumDataArgs;
8096   const char *Beg; // Start of format string.
8097   const bool HasVAListArg;
8098   ArrayRef<const Expr *> Args;
8099   unsigned FormatIdx;
8100   llvm::SmallBitVector CoveredArgs;
8101   bool usesPositionalArgs = false;
8102   bool atFirstArg = true;
8103   bool inFunctionCall;
8104   Sema::VariadicCallType CallType;
8105   llvm::SmallBitVector &CheckedVarArgs;
8106   UncoveredArgHandler &UncoveredArg;
8107 
8108 public:
8109   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8110                      const Expr *origFormatExpr,
8111                      const Sema::FormatStringType type, unsigned firstDataArg,
8112                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8113                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8114                      bool inFunctionCall, Sema::VariadicCallType callType,
8115                      llvm::SmallBitVector &CheckedVarArgs,
8116                      UncoveredArgHandler &UncoveredArg)
8117       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8118         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8119         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8120         inFunctionCall(inFunctionCall), CallType(callType),
8121         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8122     CoveredArgs.resize(numDataArgs);
8123     CoveredArgs.reset();
8124   }
8125 
8126   void DoneProcessing();
8127 
8128   void HandleIncompleteSpecifier(const char *startSpecifier,
8129                                  unsigned specifierLen) override;
8130 
8131   void HandleInvalidLengthModifier(
8132                            const analyze_format_string::FormatSpecifier &FS,
8133                            const analyze_format_string::ConversionSpecifier &CS,
8134                            const char *startSpecifier, unsigned specifierLen,
8135                            unsigned DiagID);
8136 
8137   void HandleNonStandardLengthModifier(
8138                     const analyze_format_string::FormatSpecifier &FS,
8139                     const char *startSpecifier, unsigned specifierLen);
8140 
8141   void HandleNonStandardConversionSpecifier(
8142                     const analyze_format_string::ConversionSpecifier &CS,
8143                     const char *startSpecifier, unsigned specifierLen);
8144 
8145   void HandlePosition(const char *startPos, unsigned posLen) override;
8146 
8147   void HandleInvalidPosition(const char *startSpecifier,
8148                              unsigned specifierLen,
8149                              analyze_format_string::PositionContext p) override;
8150 
8151   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8152 
8153   void HandleNullChar(const char *nullCharacter) override;
8154 
8155   template <typename Range>
8156   static void
8157   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8158                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8159                        bool IsStringLocation, Range StringRange,
8160                        ArrayRef<FixItHint> Fixit = None);
8161 
8162 protected:
8163   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8164                                         const char *startSpec,
8165                                         unsigned specifierLen,
8166                                         const char *csStart, unsigned csLen);
8167 
8168   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8169                                          const char *startSpec,
8170                                          unsigned specifierLen);
8171 
8172   SourceRange getFormatStringRange();
8173   CharSourceRange getSpecifierRange(const char *startSpecifier,
8174                                     unsigned specifierLen);
8175   SourceLocation getLocationOfByte(const char *x);
8176 
8177   const Expr *getDataArg(unsigned i) const;
8178 
8179   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8180                     const analyze_format_string::ConversionSpecifier &CS,
8181                     const char *startSpecifier, unsigned specifierLen,
8182                     unsigned argIndex);
8183 
8184   template <typename Range>
8185   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8186                             bool IsStringLocation, Range StringRange,
8187                             ArrayRef<FixItHint> Fixit = None);
8188 };
8189 
8190 } // namespace
8191 
8192 SourceRange CheckFormatHandler::getFormatStringRange() {
8193   return OrigFormatExpr->getSourceRange();
8194 }
8195 
8196 CharSourceRange CheckFormatHandler::
8197 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8198   SourceLocation Start = getLocationOfByte(startSpecifier);
8199   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8200 
8201   // Advance the end SourceLocation by one due to half-open ranges.
8202   End = End.getLocWithOffset(1);
8203 
8204   return CharSourceRange::getCharRange(Start, End);
8205 }
8206 
8207 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8208   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8209                                   S.getLangOpts(), S.Context.getTargetInfo());
8210 }
8211 
8212 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8213                                                    unsigned specifierLen){
8214   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8215                        getLocationOfByte(startSpecifier),
8216                        /*IsStringLocation*/true,
8217                        getSpecifierRange(startSpecifier, specifierLen));
8218 }
8219 
8220 void CheckFormatHandler::HandleInvalidLengthModifier(
8221     const analyze_format_string::FormatSpecifier &FS,
8222     const analyze_format_string::ConversionSpecifier &CS,
8223     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8224   using namespace analyze_format_string;
8225 
8226   const LengthModifier &LM = FS.getLengthModifier();
8227   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8228 
8229   // See if we know how to fix this length modifier.
8230   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8231   if (FixedLM) {
8232     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8233                          getLocationOfByte(LM.getStart()),
8234                          /*IsStringLocation*/true,
8235                          getSpecifierRange(startSpecifier, specifierLen));
8236 
8237     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8238       << FixedLM->toString()
8239       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8240 
8241   } else {
8242     FixItHint Hint;
8243     if (DiagID == diag::warn_format_nonsensical_length)
8244       Hint = FixItHint::CreateRemoval(LMRange);
8245 
8246     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8247                          getLocationOfByte(LM.getStart()),
8248                          /*IsStringLocation*/true,
8249                          getSpecifierRange(startSpecifier, specifierLen),
8250                          Hint);
8251   }
8252 }
8253 
8254 void CheckFormatHandler::HandleNonStandardLengthModifier(
8255     const analyze_format_string::FormatSpecifier &FS,
8256     const char *startSpecifier, unsigned specifierLen) {
8257   using namespace analyze_format_string;
8258 
8259   const LengthModifier &LM = FS.getLengthModifier();
8260   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8261 
8262   // See if we know how to fix this length modifier.
8263   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8264   if (FixedLM) {
8265     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8266                            << LM.toString() << 0,
8267                          getLocationOfByte(LM.getStart()),
8268                          /*IsStringLocation*/true,
8269                          getSpecifierRange(startSpecifier, specifierLen));
8270 
8271     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8272       << FixedLM->toString()
8273       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8274 
8275   } else {
8276     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8277                            << LM.toString() << 0,
8278                          getLocationOfByte(LM.getStart()),
8279                          /*IsStringLocation*/true,
8280                          getSpecifierRange(startSpecifier, specifierLen));
8281   }
8282 }
8283 
8284 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8285     const analyze_format_string::ConversionSpecifier &CS,
8286     const char *startSpecifier, unsigned specifierLen) {
8287   using namespace analyze_format_string;
8288 
8289   // See if we know how to fix this conversion specifier.
8290   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8291   if (FixedCS) {
8292     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8293                           << CS.toString() << /*conversion specifier*/1,
8294                          getLocationOfByte(CS.getStart()),
8295                          /*IsStringLocation*/true,
8296                          getSpecifierRange(startSpecifier, specifierLen));
8297 
8298     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8299     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8300       << FixedCS->toString()
8301       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8302   } else {
8303     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8304                           << CS.toString() << /*conversion specifier*/1,
8305                          getLocationOfByte(CS.getStart()),
8306                          /*IsStringLocation*/true,
8307                          getSpecifierRange(startSpecifier, specifierLen));
8308   }
8309 }
8310 
8311 void CheckFormatHandler::HandlePosition(const char *startPos,
8312                                         unsigned posLen) {
8313   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8314                                getLocationOfByte(startPos),
8315                                /*IsStringLocation*/true,
8316                                getSpecifierRange(startPos, posLen));
8317 }
8318 
8319 void
8320 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8321                                      analyze_format_string::PositionContext p) {
8322   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8323                          << (unsigned) p,
8324                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8325                        getSpecifierRange(startPos, posLen));
8326 }
8327 
8328 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8329                                             unsigned posLen) {
8330   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8331                                getLocationOfByte(startPos),
8332                                /*IsStringLocation*/true,
8333                                getSpecifierRange(startPos, posLen));
8334 }
8335 
8336 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8337   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8338     // The presence of a null character is likely an error.
8339     EmitFormatDiagnostic(
8340       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8341       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8342       getFormatStringRange());
8343   }
8344 }
8345 
8346 // Note that this may return NULL if there was an error parsing or building
8347 // one of the argument expressions.
8348 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8349   return Args[FirstDataArg + i];
8350 }
8351 
8352 void CheckFormatHandler::DoneProcessing() {
8353   // Does the number of data arguments exceed the number of
8354   // format conversions in the format string?
8355   if (!HasVAListArg) {
8356       // Find any arguments that weren't covered.
8357     CoveredArgs.flip();
8358     signed notCoveredArg = CoveredArgs.find_first();
8359     if (notCoveredArg >= 0) {
8360       assert((unsigned)notCoveredArg < NumDataArgs);
8361       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8362     } else {
8363       UncoveredArg.setAllCovered();
8364     }
8365   }
8366 }
8367 
8368 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8369                                    const Expr *ArgExpr) {
8370   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8371          "Invalid state");
8372 
8373   if (!ArgExpr)
8374     return;
8375 
8376   SourceLocation Loc = ArgExpr->getBeginLoc();
8377 
8378   if (S.getSourceManager().isInSystemMacro(Loc))
8379     return;
8380 
8381   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8382   for (auto E : DiagnosticExprs)
8383     PDiag << E->getSourceRange();
8384 
8385   CheckFormatHandler::EmitFormatDiagnostic(
8386                                   S, IsFunctionCall, DiagnosticExprs[0],
8387                                   PDiag, Loc, /*IsStringLocation*/false,
8388                                   DiagnosticExprs[0]->getSourceRange());
8389 }
8390 
8391 bool
8392 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8393                                                      SourceLocation Loc,
8394                                                      const char *startSpec,
8395                                                      unsigned specifierLen,
8396                                                      const char *csStart,
8397                                                      unsigned csLen) {
8398   bool keepGoing = true;
8399   if (argIndex < NumDataArgs) {
8400     // Consider the argument coverered, even though the specifier doesn't
8401     // make sense.
8402     CoveredArgs.set(argIndex);
8403   }
8404   else {
8405     // If argIndex exceeds the number of data arguments we
8406     // don't issue a warning because that is just a cascade of warnings (and
8407     // they may have intended '%%' anyway). We don't want to continue processing
8408     // the format string after this point, however, as we will like just get
8409     // gibberish when trying to match arguments.
8410     keepGoing = false;
8411   }
8412 
8413   StringRef Specifier(csStart, csLen);
8414 
8415   // If the specifier in non-printable, it could be the first byte of a UTF-8
8416   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8417   // hex value.
8418   std::string CodePointStr;
8419   if (!llvm::sys::locale::isPrint(*csStart)) {
8420     llvm::UTF32 CodePoint;
8421     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8422     const llvm::UTF8 *E =
8423         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8424     llvm::ConversionResult Result =
8425         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8426 
8427     if (Result != llvm::conversionOK) {
8428       unsigned char FirstChar = *csStart;
8429       CodePoint = (llvm::UTF32)FirstChar;
8430     }
8431 
8432     llvm::raw_string_ostream OS(CodePointStr);
8433     if (CodePoint < 256)
8434       OS << "\\x" << llvm::format("%02x", CodePoint);
8435     else if (CodePoint <= 0xFFFF)
8436       OS << "\\u" << llvm::format("%04x", CodePoint);
8437     else
8438       OS << "\\U" << llvm::format("%08x", CodePoint);
8439     OS.flush();
8440     Specifier = CodePointStr;
8441   }
8442 
8443   EmitFormatDiagnostic(
8444       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8445       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8446 
8447   return keepGoing;
8448 }
8449 
8450 void
8451 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8452                                                       const char *startSpec,
8453                                                       unsigned specifierLen) {
8454   EmitFormatDiagnostic(
8455     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8456     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8457 }
8458 
8459 bool
8460 CheckFormatHandler::CheckNumArgs(
8461   const analyze_format_string::FormatSpecifier &FS,
8462   const analyze_format_string::ConversionSpecifier &CS,
8463   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8464 
8465   if (argIndex >= NumDataArgs) {
8466     PartialDiagnostic PDiag = FS.usesPositionalArg()
8467       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8468            << (argIndex+1) << NumDataArgs)
8469       : S.PDiag(diag::warn_printf_insufficient_data_args);
8470     EmitFormatDiagnostic(
8471       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8472       getSpecifierRange(startSpecifier, specifierLen));
8473 
8474     // Since more arguments than conversion tokens are given, by extension
8475     // all arguments are covered, so mark this as so.
8476     UncoveredArg.setAllCovered();
8477     return false;
8478   }
8479   return true;
8480 }
8481 
8482 template<typename Range>
8483 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8484                                               SourceLocation Loc,
8485                                               bool IsStringLocation,
8486                                               Range StringRange,
8487                                               ArrayRef<FixItHint> FixIt) {
8488   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8489                        Loc, IsStringLocation, StringRange, FixIt);
8490 }
8491 
8492 /// If the format string is not within the function call, emit a note
8493 /// so that the function call and string are in diagnostic messages.
8494 ///
8495 /// \param InFunctionCall if true, the format string is within the function
8496 /// call and only one diagnostic message will be produced.  Otherwise, an
8497 /// extra note will be emitted pointing to location of the format string.
8498 ///
8499 /// \param ArgumentExpr the expression that is passed as the format string
8500 /// argument in the function call.  Used for getting locations when two
8501 /// diagnostics are emitted.
8502 ///
8503 /// \param PDiag the callee should already have provided any strings for the
8504 /// diagnostic message.  This function only adds locations and fixits
8505 /// to diagnostics.
8506 ///
8507 /// \param Loc primary location for diagnostic.  If two diagnostics are
8508 /// required, one will be at Loc and a new SourceLocation will be created for
8509 /// the other one.
8510 ///
8511 /// \param IsStringLocation if true, Loc points to the format string should be
8512 /// used for the note.  Otherwise, Loc points to the argument list and will
8513 /// be used with PDiag.
8514 ///
8515 /// \param StringRange some or all of the string to highlight.  This is
8516 /// templated so it can accept either a CharSourceRange or a SourceRange.
8517 ///
8518 /// \param FixIt optional fix it hint for the format string.
8519 template <typename Range>
8520 void CheckFormatHandler::EmitFormatDiagnostic(
8521     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8522     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8523     Range StringRange, ArrayRef<FixItHint> FixIt) {
8524   if (InFunctionCall) {
8525     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8526     D << StringRange;
8527     D << FixIt;
8528   } else {
8529     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8530       << ArgumentExpr->getSourceRange();
8531 
8532     const Sema::SemaDiagnosticBuilder &Note =
8533       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8534              diag::note_format_string_defined);
8535 
8536     Note << StringRange;
8537     Note << FixIt;
8538   }
8539 }
8540 
8541 //===--- CHECK: Printf format string checking ------------------------------===//
8542 
8543 namespace {
8544 
8545 class CheckPrintfHandler : public CheckFormatHandler {
8546 public:
8547   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8548                      const Expr *origFormatExpr,
8549                      const Sema::FormatStringType type, unsigned firstDataArg,
8550                      unsigned numDataArgs, bool isObjC, const char *beg,
8551                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8552                      unsigned formatIdx, bool inFunctionCall,
8553                      Sema::VariadicCallType CallType,
8554                      llvm::SmallBitVector &CheckedVarArgs,
8555                      UncoveredArgHandler &UncoveredArg)
8556       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8557                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8558                            inFunctionCall, CallType, CheckedVarArgs,
8559                            UncoveredArg) {}
8560 
8561   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8562 
8563   /// Returns true if '%@' specifiers are allowed in the format string.
8564   bool allowsObjCArg() const {
8565     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8566            FSType == Sema::FST_OSTrace;
8567   }
8568 
8569   bool HandleInvalidPrintfConversionSpecifier(
8570                                       const analyze_printf::PrintfSpecifier &FS,
8571                                       const char *startSpecifier,
8572                                       unsigned specifierLen) override;
8573 
8574   void handleInvalidMaskType(StringRef MaskType) override;
8575 
8576   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8577                              const char *startSpecifier,
8578                              unsigned specifierLen) override;
8579   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8580                        const char *StartSpecifier,
8581                        unsigned SpecifierLen,
8582                        const Expr *E);
8583 
8584   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8585                     const char *startSpecifier, unsigned specifierLen);
8586   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8587                            const analyze_printf::OptionalAmount &Amt,
8588                            unsigned type,
8589                            const char *startSpecifier, unsigned specifierLen);
8590   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8591                   const analyze_printf::OptionalFlag &flag,
8592                   const char *startSpecifier, unsigned specifierLen);
8593   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8594                          const analyze_printf::OptionalFlag &ignoredFlag,
8595                          const analyze_printf::OptionalFlag &flag,
8596                          const char *startSpecifier, unsigned specifierLen);
8597   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8598                            const Expr *E);
8599 
8600   void HandleEmptyObjCModifierFlag(const char *startFlag,
8601                                    unsigned flagLen) override;
8602 
8603   void HandleInvalidObjCModifierFlag(const char *startFlag,
8604                                             unsigned flagLen) override;
8605 
8606   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8607                                            const char *flagsEnd,
8608                                            const char *conversionPosition)
8609                                              override;
8610 };
8611 
8612 } // namespace
8613 
8614 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8615                                       const analyze_printf::PrintfSpecifier &FS,
8616                                       const char *startSpecifier,
8617                                       unsigned specifierLen) {
8618   const analyze_printf::PrintfConversionSpecifier &CS =
8619     FS.getConversionSpecifier();
8620 
8621   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8622                                           getLocationOfByte(CS.getStart()),
8623                                           startSpecifier, specifierLen,
8624                                           CS.getStart(), CS.getLength());
8625 }
8626 
8627 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8628   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8629 }
8630 
8631 bool CheckPrintfHandler::HandleAmount(
8632                                const analyze_format_string::OptionalAmount &Amt,
8633                                unsigned k, const char *startSpecifier,
8634                                unsigned specifierLen) {
8635   if (Amt.hasDataArgument()) {
8636     if (!HasVAListArg) {
8637       unsigned argIndex = Amt.getArgIndex();
8638       if (argIndex >= NumDataArgs) {
8639         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8640                                << k,
8641                              getLocationOfByte(Amt.getStart()),
8642                              /*IsStringLocation*/true,
8643                              getSpecifierRange(startSpecifier, specifierLen));
8644         // Don't do any more checking.  We will just emit
8645         // spurious errors.
8646         return false;
8647       }
8648 
8649       // Type check the data argument.  It should be an 'int'.
8650       // Although not in conformance with C99, we also allow the argument to be
8651       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8652       // doesn't emit a warning for that case.
8653       CoveredArgs.set(argIndex);
8654       const Expr *Arg = getDataArg(argIndex);
8655       if (!Arg)
8656         return false;
8657 
8658       QualType T = Arg->getType();
8659 
8660       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8661       assert(AT.isValid());
8662 
8663       if (!AT.matchesType(S.Context, T)) {
8664         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8665                                << k << AT.getRepresentativeTypeName(S.Context)
8666                                << T << Arg->getSourceRange(),
8667                              getLocationOfByte(Amt.getStart()),
8668                              /*IsStringLocation*/true,
8669                              getSpecifierRange(startSpecifier, specifierLen));
8670         // Don't do any more checking.  We will just emit
8671         // spurious errors.
8672         return false;
8673       }
8674     }
8675   }
8676   return true;
8677 }
8678 
8679 void CheckPrintfHandler::HandleInvalidAmount(
8680                                       const analyze_printf::PrintfSpecifier &FS,
8681                                       const analyze_printf::OptionalAmount &Amt,
8682                                       unsigned type,
8683                                       const char *startSpecifier,
8684                                       unsigned specifierLen) {
8685   const analyze_printf::PrintfConversionSpecifier &CS =
8686     FS.getConversionSpecifier();
8687 
8688   FixItHint fixit =
8689     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8690       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8691                                  Amt.getConstantLength()))
8692       : FixItHint();
8693 
8694   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8695                          << type << CS.toString(),
8696                        getLocationOfByte(Amt.getStart()),
8697                        /*IsStringLocation*/true,
8698                        getSpecifierRange(startSpecifier, specifierLen),
8699                        fixit);
8700 }
8701 
8702 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8703                                     const analyze_printf::OptionalFlag &flag,
8704                                     const char *startSpecifier,
8705                                     unsigned specifierLen) {
8706   // Warn about pointless flag with a fixit removal.
8707   const analyze_printf::PrintfConversionSpecifier &CS =
8708     FS.getConversionSpecifier();
8709   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8710                          << flag.toString() << CS.toString(),
8711                        getLocationOfByte(flag.getPosition()),
8712                        /*IsStringLocation*/true,
8713                        getSpecifierRange(startSpecifier, specifierLen),
8714                        FixItHint::CreateRemoval(
8715                          getSpecifierRange(flag.getPosition(), 1)));
8716 }
8717 
8718 void CheckPrintfHandler::HandleIgnoredFlag(
8719                                 const analyze_printf::PrintfSpecifier &FS,
8720                                 const analyze_printf::OptionalFlag &ignoredFlag,
8721                                 const analyze_printf::OptionalFlag &flag,
8722                                 const char *startSpecifier,
8723                                 unsigned specifierLen) {
8724   // Warn about ignored flag with a fixit removal.
8725   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8726                          << ignoredFlag.toString() << flag.toString(),
8727                        getLocationOfByte(ignoredFlag.getPosition()),
8728                        /*IsStringLocation*/true,
8729                        getSpecifierRange(startSpecifier, specifierLen),
8730                        FixItHint::CreateRemoval(
8731                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8732 }
8733 
8734 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8735                                                      unsigned flagLen) {
8736   // Warn about an empty flag.
8737   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8738                        getLocationOfByte(startFlag),
8739                        /*IsStringLocation*/true,
8740                        getSpecifierRange(startFlag, flagLen));
8741 }
8742 
8743 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8744                                                        unsigned flagLen) {
8745   // Warn about an invalid flag.
8746   auto Range = getSpecifierRange(startFlag, flagLen);
8747   StringRef flag(startFlag, flagLen);
8748   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8749                       getLocationOfByte(startFlag),
8750                       /*IsStringLocation*/true,
8751                       Range, FixItHint::CreateRemoval(Range));
8752 }
8753 
8754 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8755     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8756     // Warn about using '[...]' without a '@' conversion.
8757     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8758     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8759     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8760                          getLocationOfByte(conversionPosition),
8761                          /*IsStringLocation*/true,
8762                          Range, FixItHint::CreateRemoval(Range));
8763 }
8764 
8765 // Determines if the specified is a C++ class or struct containing
8766 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8767 // "c_str()").
8768 template<typename MemberKind>
8769 static llvm::SmallPtrSet<MemberKind*, 1>
8770 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8771   const RecordType *RT = Ty->getAs<RecordType>();
8772   llvm::SmallPtrSet<MemberKind*, 1> Results;
8773 
8774   if (!RT)
8775     return Results;
8776   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8777   if (!RD || !RD->getDefinition())
8778     return Results;
8779 
8780   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8781                  Sema::LookupMemberName);
8782   R.suppressDiagnostics();
8783 
8784   // We just need to include all members of the right kind turned up by the
8785   // filter, at this point.
8786   if (S.LookupQualifiedName(R, RT->getDecl()))
8787     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8788       NamedDecl *decl = (*I)->getUnderlyingDecl();
8789       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8790         Results.insert(FK);
8791     }
8792   return Results;
8793 }
8794 
8795 /// Check if we could call '.c_str()' on an object.
8796 ///
8797 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8798 /// allow the call, or if it would be ambiguous).
8799 bool Sema::hasCStrMethod(const Expr *E) {
8800   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8801 
8802   MethodSet Results =
8803       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8804   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8805        MI != ME; ++MI)
8806     if ((*MI)->getMinRequiredArguments() == 0)
8807       return true;
8808   return false;
8809 }
8810 
8811 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8812 // better diagnostic if so. AT is assumed to be valid.
8813 // Returns true when a c_str() conversion method is found.
8814 bool CheckPrintfHandler::checkForCStrMembers(
8815     const analyze_printf::ArgType &AT, const Expr *E) {
8816   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8817 
8818   MethodSet Results =
8819       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8820 
8821   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8822        MI != ME; ++MI) {
8823     const CXXMethodDecl *Method = *MI;
8824     if (Method->getMinRequiredArguments() == 0 &&
8825         AT.matchesType(S.Context, Method->getReturnType())) {
8826       // FIXME: Suggest parens if the expression needs them.
8827       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8828       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8829           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8830       return true;
8831     }
8832   }
8833 
8834   return false;
8835 }
8836 
8837 bool
8838 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8839                                             &FS,
8840                                           const char *startSpecifier,
8841                                           unsigned specifierLen) {
8842   using namespace analyze_format_string;
8843   using namespace analyze_printf;
8844 
8845   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8846 
8847   if (FS.consumesDataArgument()) {
8848     if (atFirstArg) {
8849         atFirstArg = false;
8850         usesPositionalArgs = FS.usesPositionalArg();
8851     }
8852     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8853       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8854                                         startSpecifier, specifierLen);
8855       return false;
8856     }
8857   }
8858 
8859   // First check if the field width, precision, and conversion specifier
8860   // have matching data arguments.
8861   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8862                     startSpecifier, specifierLen)) {
8863     return false;
8864   }
8865 
8866   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8867                     startSpecifier, specifierLen)) {
8868     return false;
8869   }
8870 
8871   if (!CS.consumesDataArgument()) {
8872     // FIXME: Technically specifying a precision or field width here
8873     // makes no sense.  Worth issuing a warning at some point.
8874     return true;
8875   }
8876 
8877   // Consume the argument.
8878   unsigned argIndex = FS.getArgIndex();
8879   if (argIndex < NumDataArgs) {
8880     // The check to see if the argIndex is valid will come later.
8881     // We set the bit here because we may exit early from this
8882     // function if we encounter some other error.
8883     CoveredArgs.set(argIndex);
8884   }
8885 
8886   // FreeBSD kernel extensions.
8887   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8888       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8889     // We need at least two arguments.
8890     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8891       return false;
8892 
8893     // Claim the second argument.
8894     CoveredArgs.set(argIndex + 1);
8895 
8896     // Type check the first argument (int for %b, pointer for %D)
8897     const Expr *Ex = getDataArg(argIndex);
8898     const analyze_printf::ArgType &AT =
8899       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8900         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8901     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8902       EmitFormatDiagnostic(
8903           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8904               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8905               << false << Ex->getSourceRange(),
8906           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8907           getSpecifierRange(startSpecifier, specifierLen));
8908 
8909     // Type check the second argument (char * for both %b and %D)
8910     Ex = getDataArg(argIndex + 1);
8911     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8912     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8913       EmitFormatDiagnostic(
8914           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8915               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8916               << false << Ex->getSourceRange(),
8917           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8918           getSpecifierRange(startSpecifier, specifierLen));
8919 
8920      return true;
8921   }
8922 
8923   // Check for using an Objective-C specific conversion specifier
8924   // in a non-ObjC literal.
8925   if (!allowsObjCArg() && CS.isObjCArg()) {
8926     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8927                                                   specifierLen);
8928   }
8929 
8930   // %P can only be used with os_log.
8931   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8932     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8933                                                   specifierLen);
8934   }
8935 
8936   // %n is not allowed with os_log.
8937   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8938     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8939                          getLocationOfByte(CS.getStart()),
8940                          /*IsStringLocation*/ false,
8941                          getSpecifierRange(startSpecifier, specifierLen));
8942 
8943     return true;
8944   }
8945 
8946   // Only scalars are allowed for os_trace.
8947   if (FSType == Sema::FST_OSTrace &&
8948       (CS.getKind() == ConversionSpecifier::PArg ||
8949        CS.getKind() == ConversionSpecifier::sArg ||
8950        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8951     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8952                                                   specifierLen);
8953   }
8954 
8955   // Check for use of public/private annotation outside of os_log().
8956   if (FSType != Sema::FST_OSLog) {
8957     if (FS.isPublic().isSet()) {
8958       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8959                                << "public",
8960                            getLocationOfByte(FS.isPublic().getPosition()),
8961                            /*IsStringLocation*/ false,
8962                            getSpecifierRange(startSpecifier, specifierLen));
8963     }
8964     if (FS.isPrivate().isSet()) {
8965       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8966                                << "private",
8967                            getLocationOfByte(FS.isPrivate().getPosition()),
8968                            /*IsStringLocation*/ false,
8969                            getSpecifierRange(startSpecifier, specifierLen));
8970     }
8971   }
8972 
8973   // Check for invalid use of field width
8974   if (!FS.hasValidFieldWidth()) {
8975     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8976         startSpecifier, specifierLen);
8977   }
8978 
8979   // Check for invalid use of precision
8980   if (!FS.hasValidPrecision()) {
8981     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8982         startSpecifier, specifierLen);
8983   }
8984 
8985   // Precision is mandatory for %P specifier.
8986   if (CS.getKind() == ConversionSpecifier::PArg &&
8987       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8988     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8989                          getLocationOfByte(startSpecifier),
8990                          /*IsStringLocation*/ false,
8991                          getSpecifierRange(startSpecifier, specifierLen));
8992   }
8993 
8994   // Check each flag does not conflict with any other component.
8995   if (!FS.hasValidThousandsGroupingPrefix())
8996     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8997   if (!FS.hasValidLeadingZeros())
8998     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8999   if (!FS.hasValidPlusPrefix())
9000     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
9001   if (!FS.hasValidSpacePrefix())
9002     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
9003   if (!FS.hasValidAlternativeForm())
9004     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
9005   if (!FS.hasValidLeftJustified())
9006     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
9007 
9008   // Check that flags are not ignored by another flag
9009   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
9010     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
9011         startSpecifier, specifierLen);
9012   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
9013     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
9014             startSpecifier, specifierLen);
9015 
9016   // Check the length modifier is valid with the given conversion specifier.
9017   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9018                                  S.getLangOpts()))
9019     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9020                                 diag::warn_format_nonsensical_length);
9021   else if (!FS.hasStandardLengthModifier())
9022     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9023   else if (!FS.hasStandardLengthConversionCombination())
9024     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9025                                 diag::warn_format_non_standard_conversion_spec);
9026 
9027   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9028     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9029 
9030   // The remaining checks depend on the data arguments.
9031   if (HasVAListArg)
9032     return true;
9033 
9034   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9035     return false;
9036 
9037   const Expr *Arg = getDataArg(argIndex);
9038   if (!Arg)
9039     return true;
9040 
9041   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9042 }
9043 
9044 static bool requiresParensToAddCast(const Expr *E) {
9045   // FIXME: We should have a general way to reason about operator
9046   // precedence and whether parens are actually needed here.
9047   // Take care of a few common cases where they aren't.
9048   const Expr *Inside = E->IgnoreImpCasts();
9049   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9050     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9051 
9052   switch (Inside->getStmtClass()) {
9053   case Stmt::ArraySubscriptExprClass:
9054   case Stmt::CallExprClass:
9055   case Stmt::CharacterLiteralClass:
9056   case Stmt::CXXBoolLiteralExprClass:
9057   case Stmt::DeclRefExprClass:
9058   case Stmt::FloatingLiteralClass:
9059   case Stmt::IntegerLiteralClass:
9060   case Stmt::MemberExprClass:
9061   case Stmt::ObjCArrayLiteralClass:
9062   case Stmt::ObjCBoolLiteralExprClass:
9063   case Stmt::ObjCBoxedExprClass:
9064   case Stmt::ObjCDictionaryLiteralClass:
9065   case Stmt::ObjCEncodeExprClass:
9066   case Stmt::ObjCIvarRefExprClass:
9067   case Stmt::ObjCMessageExprClass:
9068   case Stmt::ObjCPropertyRefExprClass:
9069   case Stmt::ObjCStringLiteralClass:
9070   case Stmt::ObjCSubscriptRefExprClass:
9071   case Stmt::ParenExprClass:
9072   case Stmt::StringLiteralClass:
9073   case Stmt::UnaryOperatorClass:
9074     return false;
9075   default:
9076     return true;
9077   }
9078 }
9079 
9080 static std::pair<QualType, StringRef>
9081 shouldNotPrintDirectly(const ASTContext &Context,
9082                        QualType IntendedTy,
9083                        const Expr *E) {
9084   // Use a 'while' to peel off layers of typedefs.
9085   QualType TyTy = IntendedTy;
9086   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9087     StringRef Name = UserTy->getDecl()->getName();
9088     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9089       .Case("CFIndex", Context.getNSIntegerType())
9090       .Case("NSInteger", Context.getNSIntegerType())
9091       .Case("NSUInteger", Context.getNSUIntegerType())
9092       .Case("SInt32", Context.IntTy)
9093       .Case("UInt32", Context.UnsignedIntTy)
9094       .Default(QualType());
9095 
9096     if (!CastTy.isNull())
9097       return std::make_pair(CastTy, Name);
9098 
9099     TyTy = UserTy->desugar();
9100   }
9101 
9102   // Strip parens if necessary.
9103   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9104     return shouldNotPrintDirectly(Context,
9105                                   PE->getSubExpr()->getType(),
9106                                   PE->getSubExpr());
9107 
9108   // If this is a conditional expression, then its result type is constructed
9109   // via usual arithmetic conversions and thus there might be no necessary
9110   // typedef sugar there.  Recurse to operands to check for NSInteger &
9111   // Co. usage condition.
9112   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9113     QualType TrueTy, FalseTy;
9114     StringRef TrueName, FalseName;
9115 
9116     std::tie(TrueTy, TrueName) =
9117       shouldNotPrintDirectly(Context,
9118                              CO->getTrueExpr()->getType(),
9119                              CO->getTrueExpr());
9120     std::tie(FalseTy, FalseName) =
9121       shouldNotPrintDirectly(Context,
9122                              CO->getFalseExpr()->getType(),
9123                              CO->getFalseExpr());
9124 
9125     if (TrueTy == FalseTy)
9126       return std::make_pair(TrueTy, TrueName);
9127     else if (TrueTy.isNull())
9128       return std::make_pair(FalseTy, FalseName);
9129     else if (FalseTy.isNull())
9130       return std::make_pair(TrueTy, TrueName);
9131   }
9132 
9133   return std::make_pair(QualType(), StringRef());
9134 }
9135 
9136 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9137 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9138 /// type do not count.
9139 static bool
9140 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9141   QualType From = ICE->getSubExpr()->getType();
9142   QualType To = ICE->getType();
9143   // It's an integer promotion if the destination type is the promoted
9144   // source type.
9145   if (ICE->getCastKind() == CK_IntegralCast &&
9146       From->isPromotableIntegerType() &&
9147       S.Context.getPromotedIntegerType(From) == To)
9148     return true;
9149   // Look through vector types, since we do default argument promotion for
9150   // those in OpenCL.
9151   if (const auto *VecTy = From->getAs<ExtVectorType>())
9152     From = VecTy->getElementType();
9153   if (const auto *VecTy = To->getAs<ExtVectorType>())
9154     To = VecTy->getElementType();
9155   // It's a floating promotion if the source type is a lower rank.
9156   return ICE->getCastKind() == CK_FloatingCast &&
9157          S.Context.getFloatingTypeOrder(From, To) < 0;
9158 }
9159 
9160 bool
9161 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9162                                     const char *StartSpecifier,
9163                                     unsigned SpecifierLen,
9164                                     const Expr *E) {
9165   using namespace analyze_format_string;
9166   using namespace analyze_printf;
9167 
9168   // Now type check the data expression that matches the
9169   // format specifier.
9170   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9171   if (!AT.isValid())
9172     return true;
9173 
9174   QualType ExprTy = E->getType();
9175   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9176     ExprTy = TET->getUnderlyingExpr()->getType();
9177   }
9178 
9179   // Diagnose attempts to print a boolean value as a character. Unlike other
9180   // -Wformat diagnostics, this is fine from a type perspective, but it still
9181   // doesn't make sense.
9182   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9183       E->isKnownToHaveBooleanValue()) {
9184     const CharSourceRange &CSR =
9185         getSpecifierRange(StartSpecifier, SpecifierLen);
9186     SmallString<4> FSString;
9187     llvm::raw_svector_ostream os(FSString);
9188     FS.toString(os);
9189     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9190                              << FSString,
9191                          E->getExprLoc(), false, CSR);
9192     return true;
9193   }
9194 
9195   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9196   if (Match == analyze_printf::ArgType::Match)
9197     return true;
9198 
9199   // Look through argument promotions for our error message's reported type.
9200   // This includes the integral and floating promotions, but excludes array
9201   // and function pointer decay (seeing that an argument intended to be a
9202   // string has type 'char [6]' is probably more confusing than 'char *') and
9203   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9204   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9205     if (isArithmeticArgumentPromotion(S, ICE)) {
9206       E = ICE->getSubExpr();
9207       ExprTy = E->getType();
9208 
9209       // Check if we didn't match because of an implicit cast from a 'char'
9210       // or 'short' to an 'int'.  This is done because printf is a varargs
9211       // function.
9212       if (ICE->getType() == S.Context.IntTy ||
9213           ICE->getType() == S.Context.UnsignedIntTy) {
9214         // All further checking is done on the subexpression
9215         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9216             AT.matchesType(S.Context, ExprTy);
9217         if (ImplicitMatch == analyze_printf::ArgType::Match)
9218           return true;
9219         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9220             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9221           Match = ImplicitMatch;
9222       }
9223     }
9224   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9225     // Special case for 'a', which has type 'int' in C.
9226     // Note, however, that we do /not/ want to treat multibyte constants like
9227     // 'MooV' as characters! This form is deprecated but still exists. In
9228     // addition, don't treat expressions as of type 'char' if one byte length
9229     // modifier is provided.
9230     if (ExprTy == S.Context.IntTy &&
9231         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9232       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9233         ExprTy = S.Context.CharTy;
9234   }
9235 
9236   // Look through enums to their underlying type.
9237   bool IsEnum = false;
9238   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9239     ExprTy = EnumTy->getDecl()->getIntegerType();
9240     IsEnum = true;
9241   }
9242 
9243   // %C in an Objective-C context prints a unichar, not a wchar_t.
9244   // If the argument is an integer of some kind, believe the %C and suggest
9245   // a cast instead of changing the conversion specifier.
9246   QualType IntendedTy = ExprTy;
9247   if (isObjCContext() &&
9248       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9249     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9250         !ExprTy->isCharType()) {
9251       // 'unichar' is defined as a typedef of unsigned short, but we should
9252       // prefer using the typedef if it is visible.
9253       IntendedTy = S.Context.UnsignedShortTy;
9254 
9255       // While we are here, check if the value is an IntegerLiteral that happens
9256       // to be within the valid range.
9257       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9258         const llvm::APInt &V = IL->getValue();
9259         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9260           return true;
9261       }
9262 
9263       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9264                           Sema::LookupOrdinaryName);
9265       if (S.LookupName(Result, S.getCurScope())) {
9266         NamedDecl *ND = Result.getFoundDecl();
9267         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9268           if (TD->getUnderlyingType() == IntendedTy)
9269             IntendedTy = S.Context.getTypedefType(TD);
9270       }
9271     }
9272   }
9273 
9274   // Special-case some of Darwin's platform-independence types by suggesting
9275   // casts to primitive types that are known to be large enough.
9276   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9277   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9278     QualType CastTy;
9279     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9280     if (!CastTy.isNull()) {
9281       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9282       // (long in ASTContext). Only complain to pedants.
9283       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9284           (AT.isSizeT() || AT.isPtrdiffT()) &&
9285           AT.matchesType(S.Context, CastTy))
9286         Match = ArgType::NoMatchPedantic;
9287       IntendedTy = CastTy;
9288       ShouldNotPrintDirectly = true;
9289     }
9290   }
9291 
9292   // We may be able to offer a FixItHint if it is a supported type.
9293   PrintfSpecifier fixedFS = FS;
9294   bool Success =
9295       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9296 
9297   if (Success) {
9298     // Get the fix string from the fixed format specifier
9299     SmallString<16> buf;
9300     llvm::raw_svector_ostream os(buf);
9301     fixedFS.toString(os);
9302 
9303     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9304 
9305     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9306       unsigned Diag;
9307       switch (Match) {
9308       case ArgType::Match: llvm_unreachable("expected non-matching");
9309       case ArgType::NoMatchPedantic:
9310         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9311         break;
9312       case ArgType::NoMatchTypeConfusion:
9313         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9314         break;
9315       case ArgType::NoMatch:
9316         Diag = diag::warn_format_conversion_argument_type_mismatch;
9317         break;
9318       }
9319 
9320       // In this case, the specifier is wrong and should be changed to match
9321       // the argument.
9322       EmitFormatDiagnostic(S.PDiag(Diag)
9323                                << AT.getRepresentativeTypeName(S.Context)
9324                                << IntendedTy << IsEnum << E->getSourceRange(),
9325                            E->getBeginLoc(),
9326                            /*IsStringLocation*/ false, SpecRange,
9327                            FixItHint::CreateReplacement(SpecRange, os.str()));
9328     } else {
9329       // The canonical type for formatting this value is different from the
9330       // actual type of the expression. (This occurs, for example, with Darwin's
9331       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9332       // should be printed as 'long' for 64-bit compatibility.)
9333       // Rather than emitting a normal format/argument mismatch, we want to
9334       // add a cast to the recommended type (and correct the format string
9335       // if necessary).
9336       SmallString<16> CastBuf;
9337       llvm::raw_svector_ostream CastFix(CastBuf);
9338       CastFix << "(";
9339       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9340       CastFix << ")";
9341 
9342       SmallVector<FixItHint,4> Hints;
9343       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9344         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9345 
9346       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9347         // If there's already a cast present, just replace it.
9348         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9349         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9350 
9351       } else if (!requiresParensToAddCast(E)) {
9352         // If the expression has high enough precedence,
9353         // just write the C-style cast.
9354         Hints.push_back(
9355             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9356       } else {
9357         // Otherwise, add parens around the expression as well as the cast.
9358         CastFix << "(";
9359         Hints.push_back(
9360             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9361 
9362         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9363         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9364       }
9365 
9366       if (ShouldNotPrintDirectly) {
9367         // The expression has a type that should not be printed directly.
9368         // We extract the name from the typedef because we don't want to show
9369         // the underlying type in the diagnostic.
9370         StringRef Name;
9371         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9372           Name = TypedefTy->getDecl()->getName();
9373         else
9374           Name = CastTyName;
9375         unsigned Diag = Match == ArgType::NoMatchPedantic
9376                             ? diag::warn_format_argument_needs_cast_pedantic
9377                             : diag::warn_format_argument_needs_cast;
9378         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9379                                            << E->getSourceRange(),
9380                              E->getBeginLoc(), /*IsStringLocation=*/false,
9381                              SpecRange, Hints);
9382       } else {
9383         // In this case, the expression could be printed using a different
9384         // specifier, but we've decided that the specifier is probably correct
9385         // and we should cast instead. Just use the normal warning message.
9386         EmitFormatDiagnostic(
9387             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9388                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9389                 << E->getSourceRange(),
9390             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9391       }
9392     }
9393   } else {
9394     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9395                                                    SpecifierLen);
9396     // Since the warning for passing non-POD types to variadic functions
9397     // was deferred until now, we emit a warning for non-POD
9398     // arguments here.
9399     switch (S.isValidVarArgType(ExprTy)) {
9400     case Sema::VAK_Valid:
9401     case Sema::VAK_ValidInCXX11: {
9402       unsigned Diag;
9403       switch (Match) {
9404       case ArgType::Match: llvm_unreachable("expected non-matching");
9405       case ArgType::NoMatchPedantic:
9406         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9407         break;
9408       case ArgType::NoMatchTypeConfusion:
9409         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9410         break;
9411       case ArgType::NoMatch:
9412         Diag = diag::warn_format_conversion_argument_type_mismatch;
9413         break;
9414       }
9415 
9416       EmitFormatDiagnostic(
9417           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9418                         << IsEnum << CSR << E->getSourceRange(),
9419           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9420       break;
9421     }
9422     case Sema::VAK_Undefined:
9423     case Sema::VAK_MSVCUndefined:
9424       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9425                                << S.getLangOpts().CPlusPlus11 << ExprTy
9426                                << CallType
9427                                << AT.getRepresentativeTypeName(S.Context) << CSR
9428                                << E->getSourceRange(),
9429                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9430       checkForCStrMembers(AT, E);
9431       break;
9432 
9433     case Sema::VAK_Invalid:
9434       if (ExprTy->isObjCObjectType())
9435         EmitFormatDiagnostic(
9436             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9437                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9438                 << AT.getRepresentativeTypeName(S.Context) << CSR
9439                 << E->getSourceRange(),
9440             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9441       else
9442         // FIXME: If this is an initializer list, suggest removing the braces
9443         // or inserting a cast to the target type.
9444         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9445             << isa<InitListExpr>(E) << ExprTy << CallType
9446             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9447       break;
9448     }
9449 
9450     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9451            "format string specifier index out of range");
9452     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9453   }
9454 
9455   return true;
9456 }
9457 
9458 //===--- CHECK: Scanf format string checking ------------------------------===//
9459 
9460 namespace {
9461 
9462 class CheckScanfHandler : public CheckFormatHandler {
9463 public:
9464   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9465                     const Expr *origFormatExpr, Sema::FormatStringType type,
9466                     unsigned firstDataArg, unsigned numDataArgs,
9467                     const char *beg, bool hasVAListArg,
9468                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9469                     bool inFunctionCall, Sema::VariadicCallType CallType,
9470                     llvm::SmallBitVector &CheckedVarArgs,
9471                     UncoveredArgHandler &UncoveredArg)
9472       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9473                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9474                            inFunctionCall, CallType, CheckedVarArgs,
9475                            UncoveredArg) {}
9476 
9477   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9478                             const char *startSpecifier,
9479                             unsigned specifierLen) override;
9480 
9481   bool HandleInvalidScanfConversionSpecifier(
9482           const analyze_scanf::ScanfSpecifier &FS,
9483           const char *startSpecifier,
9484           unsigned specifierLen) override;
9485 
9486   void HandleIncompleteScanList(const char *start, const char *end) override;
9487 };
9488 
9489 } // namespace
9490 
9491 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9492                                                  const char *end) {
9493   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9494                        getLocationOfByte(end), /*IsStringLocation*/true,
9495                        getSpecifierRange(start, end - start));
9496 }
9497 
9498 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9499                                         const analyze_scanf::ScanfSpecifier &FS,
9500                                         const char *startSpecifier,
9501                                         unsigned specifierLen) {
9502   const analyze_scanf::ScanfConversionSpecifier &CS =
9503     FS.getConversionSpecifier();
9504 
9505   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9506                                           getLocationOfByte(CS.getStart()),
9507                                           startSpecifier, specifierLen,
9508                                           CS.getStart(), CS.getLength());
9509 }
9510 
9511 bool CheckScanfHandler::HandleScanfSpecifier(
9512                                        const analyze_scanf::ScanfSpecifier &FS,
9513                                        const char *startSpecifier,
9514                                        unsigned specifierLen) {
9515   using namespace analyze_scanf;
9516   using namespace analyze_format_string;
9517 
9518   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9519 
9520   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9521   // be used to decide if we are using positional arguments consistently.
9522   if (FS.consumesDataArgument()) {
9523     if (atFirstArg) {
9524       atFirstArg = false;
9525       usesPositionalArgs = FS.usesPositionalArg();
9526     }
9527     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9528       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9529                                         startSpecifier, specifierLen);
9530       return false;
9531     }
9532   }
9533 
9534   // Check if the field with is non-zero.
9535   const OptionalAmount &Amt = FS.getFieldWidth();
9536   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9537     if (Amt.getConstantAmount() == 0) {
9538       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9539                                                    Amt.getConstantLength());
9540       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9541                            getLocationOfByte(Amt.getStart()),
9542                            /*IsStringLocation*/true, R,
9543                            FixItHint::CreateRemoval(R));
9544     }
9545   }
9546 
9547   if (!FS.consumesDataArgument()) {
9548     // FIXME: Technically specifying a precision or field width here
9549     // makes no sense.  Worth issuing a warning at some point.
9550     return true;
9551   }
9552 
9553   // Consume the argument.
9554   unsigned argIndex = FS.getArgIndex();
9555   if (argIndex < NumDataArgs) {
9556       // The check to see if the argIndex is valid will come later.
9557       // We set the bit here because we may exit early from this
9558       // function if we encounter some other error.
9559     CoveredArgs.set(argIndex);
9560   }
9561 
9562   // Check the length modifier is valid with the given conversion specifier.
9563   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9564                                  S.getLangOpts()))
9565     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9566                                 diag::warn_format_nonsensical_length);
9567   else if (!FS.hasStandardLengthModifier())
9568     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9569   else if (!FS.hasStandardLengthConversionCombination())
9570     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9571                                 diag::warn_format_non_standard_conversion_spec);
9572 
9573   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9574     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9575 
9576   // The remaining checks depend on the data arguments.
9577   if (HasVAListArg)
9578     return true;
9579 
9580   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9581     return false;
9582 
9583   // Check that the argument type matches the format specifier.
9584   const Expr *Ex = getDataArg(argIndex);
9585   if (!Ex)
9586     return true;
9587 
9588   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9589 
9590   if (!AT.isValid()) {
9591     return true;
9592   }
9593 
9594   analyze_format_string::ArgType::MatchKind Match =
9595       AT.matchesType(S.Context, Ex->getType());
9596   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9597   if (Match == analyze_format_string::ArgType::Match)
9598     return true;
9599 
9600   ScanfSpecifier fixedFS = FS;
9601   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9602                                  S.getLangOpts(), S.Context);
9603 
9604   unsigned Diag =
9605       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9606                : diag::warn_format_conversion_argument_type_mismatch;
9607 
9608   if (Success) {
9609     // Get the fix string from the fixed format specifier.
9610     SmallString<128> buf;
9611     llvm::raw_svector_ostream os(buf);
9612     fixedFS.toString(os);
9613 
9614     EmitFormatDiagnostic(
9615         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9616                       << Ex->getType() << false << Ex->getSourceRange(),
9617         Ex->getBeginLoc(),
9618         /*IsStringLocation*/ false,
9619         getSpecifierRange(startSpecifier, specifierLen),
9620         FixItHint::CreateReplacement(
9621             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9622   } else {
9623     EmitFormatDiagnostic(S.PDiag(Diag)
9624                              << AT.getRepresentativeTypeName(S.Context)
9625                              << Ex->getType() << false << Ex->getSourceRange(),
9626                          Ex->getBeginLoc(),
9627                          /*IsStringLocation*/ false,
9628                          getSpecifierRange(startSpecifier, specifierLen));
9629   }
9630 
9631   return true;
9632 }
9633 
9634 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9635                               const Expr *OrigFormatExpr,
9636                               ArrayRef<const Expr *> Args,
9637                               bool HasVAListArg, unsigned format_idx,
9638                               unsigned firstDataArg,
9639                               Sema::FormatStringType Type,
9640                               bool inFunctionCall,
9641                               Sema::VariadicCallType CallType,
9642                               llvm::SmallBitVector &CheckedVarArgs,
9643                               UncoveredArgHandler &UncoveredArg,
9644                               bool IgnoreStringsWithoutSpecifiers) {
9645   // CHECK: is the format string a wide literal?
9646   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9647     CheckFormatHandler::EmitFormatDiagnostic(
9648         S, inFunctionCall, Args[format_idx],
9649         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9650         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9651     return;
9652   }
9653 
9654   // Str - The format string.  NOTE: this is NOT null-terminated!
9655   StringRef StrRef = FExpr->getString();
9656   const char *Str = StrRef.data();
9657   // Account for cases where the string literal is truncated in a declaration.
9658   const ConstantArrayType *T =
9659     S.Context.getAsConstantArrayType(FExpr->getType());
9660   assert(T && "String literal not of constant array type!");
9661   size_t TypeSize = T->getSize().getZExtValue();
9662   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9663   const unsigned numDataArgs = Args.size() - firstDataArg;
9664 
9665   if (IgnoreStringsWithoutSpecifiers &&
9666       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9667           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9668     return;
9669 
9670   // Emit a warning if the string literal is truncated and does not contain an
9671   // embedded null character.
9672   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9673     CheckFormatHandler::EmitFormatDiagnostic(
9674         S, inFunctionCall, Args[format_idx],
9675         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9676         FExpr->getBeginLoc(),
9677         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9678     return;
9679   }
9680 
9681   // CHECK: empty format string?
9682   if (StrLen == 0 && numDataArgs > 0) {
9683     CheckFormatHandler::EmitFormatDiagnostic(
9684         S, inFunctionCall, Args[format_idx],
9685         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9686         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9687     return;
9688   }
9689 
9690   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9691       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9692       Type == Sema::FST_OSTrace) {
9693     CheckPrintfHandler H(
9694         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9695         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9696         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9697         CheckedVarArgs, UncoveredArg);
9698 
9699     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9700                                                   S.getLangOpts(),
9701                                                   S.Context.getTargetInfo(),
9702                                             Type == Sema::FST_FreeBSDKPrintf))
9703       H.DoneProcessing();
9704   } else if (Type == Sema::FST_Scanf) {
9705     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9706                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9707                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9708 
9709     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9710                                                  S.getLangOpts(),
9711                                                  S.Context.getTargetInfo()))
9712       H.DoneProcessing();
9713   } // TODO: handle other formats
9714 }
9715 
9716 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9717   // Str - The format string.  NOTE: this is NOT null-terminated!
9718   StringRef StrRef = FExpr->getString();
9719   const char *Str = StrRef.data();
9720   // Account for cases where the string literal is truncated in a declaration.
9721   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9722   assert(T && "String literal not of constant array type!");
9723   size_t TypeSize = T->getSize().getZExtValue();
9724   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9725   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9726                                                          getLangOpts(),
9727                                                          Context.getTargetInfo());
9728 }
9729 
9730 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9731 
9732 // Returns the related absolute value function that is larger, of 0 if one
9733 // does not exist.
9734 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9735   switch (AbsFunction) {
9736   default:
9737     return 0;
9738 
9739   case Builtin::BI__builtin_abs:
9740     return Builtin::BI__builtin_labs;
9741   case Builtin::BI__builtin_labs:
9742     return Builtin::BI__builtin_llabs;
9743   case Builtin::BI__builtin_llabs:
9744     return 0;
9745 
9746   case Builtin::BI__builtin_fabsf:
9747     return Builtin::BI__builtin_fabs;
9748   case Builtin::BI__builtin_fabs:
9749     return Builtin::BI__builtin_fabsl;
9750   case Builtin::BI__builtin_fabsl:
9751     return 0;
9752 
9753   case Builtin::BI__builtin_cabsf:
9754     return Builtin::BI__builtin_cabs;
9755   case Builtin::BI__builtin_cabs:
9756     return Builtin::BI__builtin_cabsl;
9757   case Builtin::BI__builtin_cabsl:
9758     return 0;
9759 
9760   case Builtin::BIabs:
9761     return Builtin::BIlabs;
9762   case Builtin::BIlabs:
9763     return Builtin::BIllabs;
9764   case Builtin::BIllabs:
9765     return 0;
9766 
9767   case Builtin::BIfabsf:
9768     return Builtin::BIfabs;
9769   case Builtin::BIfabs:
9770     return Builtin::BIfabsl;
9771   case Builtin::BIfabsl:
9772     return 0;
9773 
9774   case Builtin::BIcabsf:
9775    return Builtin::BIcabs;
9776   case Builtin::BIcabs:
9777     return Builtin::BIcabsl;
9778   case Builtin::BIcabsl:
9779     return 0;
9780   }
9781 }
9782 
9783 // Returns the argument type of the absolute value function.
9784 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9785                                              unsigned AbsType) {
9786   if (AbsType == 0)
9787     return QualType();
9788 
9789   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9790   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9791   if (Error != ASTContext::GE_None)
9792     return QualType();
9793 
9794   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9795   if (!FT)
9796     return QualType();
9797 
9798   if (FT->getNumParams() != 1)
9799     return QualType();
9800 
9801   return FT->getParamType(0);
9802 }
9803 
9804 // Returns the best absolute value function, or zero, based on type and
9805 // current absolute value function.
9806 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9807                                    unsigned AbsFunctionKind) {
9808   unsigned BestKind = 0;
9809   uint64_t ArgSize = Context.getTypeSize(ArgType);
9810   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9811        Kind = getLargerAbsoluteValueFunction(Kind)) {
9812     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9813     if (Context.getTypeSize(ParamType) >= ArgSize) {
9814       if (BestKind == 0)
9815         BestKind = Kind;
9816       else if (Context.hasSameType(ParamType, ArgType)) {
9817         BestKind = Kind;
9818         break;
9819       }
9820     }
9821   }
9822   return BestKind;
9823 }
9824 
9825 enum AbsoluteValueKind {
9826   AVK_Integer,
9827   AVK_Floating,
9828   AVK_Complex
9829 };
9830 
9831 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9832   if (T->isIntegralOrEnumerationType())
9833     return AVK_Integer;
9834   if (T->isRealFloatingType())
9835     return AVK_Floating;
9836   if (T->isAnyComplexType())
9837     return AVK_Complex;
9838 
9839   llvm_unreachable("Type not integer, floating, or complex");
9840 }
9841 
9842 // Changes the absolute value function to a different type.  Preserves whether
9843 // the function is a builtin.
9844 static unsigned changeAbsFunction(unsigned AbsKind,
9845                                   AbsoluteValueKind ValueKind) {
9846   switch (ValueKind) {
9847   case AVK_Integer:
9848     switch (AbsKind) {
9849     default:
9850       return 0;
9851     case Builtin::BI__builtin_fabsf:
9852     case Builtin::BI__builtin_fabs:
9853     case Builtin::BI__builtin_fabsl:
9854     case Builtin::BI__builtin_cabsf:
9855     case Builtin::BI__builtin_cabs:
9856     case Builtin::BI__builtin_cabsl:
9857       return Builtin::BI__builtin_abs;
9858     case Builtin::BIfabsf:
9859     case Builtin::BIfabs:
9860     case Builtin::BIfabsl:
9861     case Builtin::BIcabsf:
9862     case Builtin::BIcabs:
9863     case Builtin::BIcabsl:
9864       return Builtin::BIabs;
9865     }
9866   case AVK_Floating:
9867     switch (AbsKind) {
9868     default:
9869       return 0;
9870     case Builtin::BI__builtin_abs:
9871     case Builtin::BI__builtin_labs:
9872     case Builtin::BI__builtin_llabs:
9873     case Builtin::BI__builtin_cabsf:
9874     case Builtin::BI__builtin_cabs:
9875     case Builtin::BI__builtin_cabsl:
9876       return Builtin::BI__builtin_fabsf;
9877     case Builtin::BIabs:
9878     case Builtin::BIlabs:
9879     case Builtin::BIllabs:
9880     case Builtin::BIcabsf:
9881     case Builtin::BIcabs:
9882     case Builtin::BIcabsl:
9883       return Builtin::BIfabsf;
9884     }
9885   case AVK_Complex:
9886     switch (AbsKind) {
9887     default:
9888       return 0;
9889     case Builtin::BI__builtin_abs:
9890     case Builtin::BI__builtin_labs:
9891     case Builtin::BI__builtin_llabs:
9892     case Builtin::BI__builtin_fabsf:
9893     case Builtin::BI__builtin_fabs:
9894     case Builtin::BI__builtin_fabsl:
9895       return Builtin::BI__builtin_cabsf;
9896     case Builtin::BIabs:
9897     case Builtin::BIlabs:
9898     case Builtin::BIllabs:
9899     case Builtin::BIfabsf:
9900     case Builtin::BIfabs:
9901     case Builtin::BIfabsl:
9902       return Builtin::BIcabsf;
9903     }
9904   }
9905   llvm_unreachable("Unable to convert function");
9906 }
9907 
9908 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9909   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9910   if (!FnInfo)
9911     return 0;
9912 
9913   switch (FDecl->getBuiltinID()) {
9914   default:
9915     return 0;
9916   case Builtin::BI__builtin_abs:
9917   case Builtin::BI__builtin_fabs:
9918   case Builtin::BI__builtin_fabsf:
9919   case Builtin::BI__builtin_fabsl:
9920   case Builtin::BI__builtin_labs:
9921   case Builtin::BI__builtin_llabs:
9922   case Builtin::BI__builtin_cabs:
9923   case Builtin::BI__builtin_cabsf:
9924   case Builtin::BI__builtin_cabsl:
9925   case Builtin::BIabs:
9926   case Builtin::BIlabs:
9927   case Builtin::BIllabs:
9928   case Builtin::BIfabs:
9929   case Builtin::BIfabsf:
9930   case Builtin::BIfabsl:
9931   case Builtin::BIcabs:
9932   case Builtin::BIcabsf:
9933   case Builtin::BIcabsl:
9934     return FDecl->getBuiltinID();
9935   }
9936   llvm_unreachable("Unknown Builtin type");
9937 }
9938 
9939 // If the replacement is valid, emit a note with replacement function.
9940 // Additionally, suggest including the proper header if not already included.
9941 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9942                             unsigned AbsKind, QualType ArgType) {
9943   bool EmitHeaderHint = true;
9944   const char *HeaderName = nullptr;
9945   const char *FunctionName = nullptr;
9946   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9947     FunctionName = "std::abs";
9948     if (ArgType->isIntegralOrEnumerationType()) {
9949       HeaderName = "cstdlib";
9950     } else if (ArgType->isRealFloatingType()) {
9951       HeaderName = "cmath";
9952     } else {
9953       llvm_unreachable("Invalid Type");
9954     }
9955 
9956     // Lookup all std::abs
9957     if (NamespaceDecl *Std = S.getStdNamespace()) {
9958       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9959       R.suppressDiagnostics();
9960       S.LookupQualifiedName(R, Std);
9961 
9962       for (const auto *I : R) {
9963         const FunctionDecl *FDecl = nullptr;
9964         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9965           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9966         } else {
9967           FDecl = dyn_cast<FunctionDecl>(I);
9968         }
9969         if (!FDecl)
9970           continue;
9971 
9972         // Found std::abs(), check that they are the right ones.
9973         if (FDecl->getNumParams() != 1)
9974           continue;
9975 
9976         // Check that the parameter type can handle the argument.
9977         QualType ParamType = FDecl->getParamDecl(0)->getType();
9978         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9979             S.Context.getTypeSize(ArgType) <=
9980                 S.Context.getTypeSize(ParamType)) {
9981           // Found a function, don't need the header hint.
9982           EmitHeaderHint = false;
9983           break;
9984         }
9985       }
9986     }
9987   } else {
9988     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9989     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9990 
9991     if (HeaderName) {
9992       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9993       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9994       R.suppressDiagnostics();
9995       S.LookupName(R, S.getCurScope());
9996 
9997       if (R.isSingleResult()) {
9998         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9999         if (FD && FD->getBuiltinID() == AbsKind) {
10000           EmitHeaderHint = false;
10001         } else {
10002           return;
10003         }
10004       } else if (!R.empty()) {
10005         return;
10006       }
10007     }
10008   }
10009 
10010   S.Diag(Loc, diag::note_replace_abs_function)
10011       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
10012 
10013   if (!HeaderName)
10014     return;
10015 
10016   if (!EmitHeaderHint)
10017     return;
10018 
10019   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
10020                                                     << FunctionName;
10021 }
10022 
10023 template <std::size_t StrLen>
10024 static bool IsStdFunction(const FunctionDecl *FDecl,
10025                           const char (&Str)[StrLen]) {
10026   if (!FDecl)
10027     return false;
10028   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10029     return false;
10030   if (!FDecl->isInStdNamespace())
10031     return false;
10032 
10033   return true;
10034 }
10035 
10036 // Warn when using the wrong abs() function.
10037 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10038                                       const FunctionDecl *FDecl) {
10039   if (Call->getNumArgs() != 1)
10040     return;
10041 
10042   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10043   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10044   if (AbsKind == 0 && !IsStdAbs)
10045     return;
10046 
10047   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10048   QualType ParamType = Call->getArg(0)->getType();
10049 
10050   // Unsigned types cannot be negative.  Suggest removing the absolute value
10051   // function call.
10052   if (ArgType->isUnsignedIntegerType()) {
10053     const char *FunctionName =
10054         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10055     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10056     Diag(Call->getExprLoc(), diag::note_remove_abs)
10057         << FunctionName
10058         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10059     return;
10060   }
10061 
10062   // Taking the absolute value of a pointer is very suspicious, they probably
10063   // wanted to index into an array, dereference a pointer, call a function, etc.
10064   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10065     unsigned DiagType = 0;
10066     if (ArgType->isFunctionType())
10067       DiagType = 1;
10068     else if (ArgType->isArrayType())
10069       DiagType = 2;
10070 
10071     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10072     return;
10073   }
10074 
10075   // std::abs has overloads which prevent most of the absolute value problems
10076   // from occurring.
10077   if (IsStdAbs)
10078     return;
10079 
10080   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10081   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10082 
10083   // The argument and parameter are the same kind.  Check if they are the right
10084   // size.
10085   if (ArgValueKind == ParamValueKind) {
10086     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10087       return;
10088 
10089     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10090     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10091         << FDecl << ArgType << ParamType;
10092 
10093     if (NewAbsKind == 0)
10094       return;
10095 
10096     emitReplacement(*this, Call->getExprLoc(),
10097                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10098     return;
10099   }
10100 
10101   // ArgValueKind != ParamValueKind
10102   // The wrong type of absolute value function was used.  Attempt to find the
10103   // proper one.
10104   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10105   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10106   if (NewAbsKind == 0)
10107     return;
10108 
10109   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10110       << FDecl << ParamValueKind << ArgValueKind;
10111 
10112   emitReplacement(*this, Call->getExprLoc(),
10113                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10114 }
10115 
10116 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10117 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10118                                 const FunctionDecl *FDecl) {
10119   if (!Call || !FDecl) return;
10120 
10121   // Ignore template specializations and macros.
10122   if (inTemplateInstantiation()) return;
10123   if (Call->getExprLoc().isMacroID()) return;
10124 
10125   // Only care about the one template argument, two function parameter std::max
10126   if (Call->getNumArgs() != 2) return;
10127   if (!IsStdFunction(FDecl, "max")) return;
10128   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10129   if (!ArgList) return;
10130   if (ArgList->size() != 1) return;
10131 
10132   // Check that template type argument is unsigned integer.
10133   const auto& TA = ArgList->get(0);
10134   if (TA.getKind() != TemplateArgument::Type) return;
10135   QualType ArgType = TA.getAsType();
10136   if (!ArgType->isUnsignedIntegerType()) return;
10137 
10138   // See if either argument is a literal zero.
10139   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10140     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10141     if (!MTE) return false;
10142     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10143     if (!Num) return false;
10144     if (Num->getValue() != 0) return false;
10145     return true;
10146   };
10147 
10148   const Expr *FirstArg = Call->getArg(0);
10149   const Expr *SecondArg = Call->getArg(1);
10150   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10151   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10152 
10153   // Only warn when exactly one argument is zero.
10154   if (IsFirstArgZero == IsSecondArgZero) return;
10155 
10156   SourceRange FirstRange = FirstArg->getSourceRange();
10157   SourceRange SecondRange = SecondArg->getSourceRange();
10158 
10159   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10160 
10161   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10162       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10163 
10164   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10165   SourceRange RemovalRange;
10166   if (IsFirstArgZero) {
10167     RemovalRange = SourceRange(FirstRange.getBegin(),
10168                                SecondRange.getBegin().getLocWithOffset(-1));
10169   } else {
10170     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10171                                SecondRange.getEnd());
10172   }
10173 
10174   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10175         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10176         << FixItHint::CreateRemoval(RemovalRange);
10177 }
10178 
10179 //===--- CHECK: Standard memory functions ---------------------------------===//
10180 
10181 /// Takes the expression passed to the size_t parameter of functions
10182 /// such as memcmp, strncat, etc and warns if it's a comparison.
10183 ///
10184 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10185 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10186                                            IdentifierInfo *FnName,
10187                                            SourceLocation FnLoc,
10188                                            SourceLocation RParenLoc) {
10189   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10190   if (!Size)
10191     return false;
10192 
10193   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10194   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10195     return false;
10196 
10197   SourceRange SizeRange = Size->getSourceRange();
10198   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10199       << SizeRange << FnName;
10200   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10201       << FnName
10202       << FixItHint::CreateInsertion(
10203              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10204       << FixItHint::CreateRemoval(RParenLoc);
10205   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10206       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10207       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10208                                     ")");
10209 
10210   return true;
10211 }
10212 
10213 /// Determine whether the given type is or contains a dynamic class type
10214 /// (e.g., whether it has a vtable).
10215 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10216                                                      bool &IsContained) {
10217   // Look through array types while ignoring qualifiers.
10218   const Type *Ty = T->getBaseElementTypeUnsafe();
10219   IsContained = false;
10220 
10221   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10222   RD = RD ? RD->getDefinition() : nullptr;
10223   if (!RD || RD->isInvalidDecl())
10224     return nullptr;
10225 
10226   if (RD->isDynamicClass())
10227     return RD;
10228 
10229   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10230   // It's impossible for a class to transitively contain itself by value, so
10231   // infinite recursion is impossible.
10232   for (auto *FD : RD->fields()) {
10233     bool SubContained;
10234     if (const CXXRecordDecl *ContainedRD =
10235             getContainedDynamicClass(FD->getType(), SubContained)) {
10236       IsContained = true;
10237       return ContainedRD;
10238     }
10239   }
10240 
10241   return nullptr;
10242 }
10243 
10244 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10245   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10246     if (Unary->getKind() == UETT_SizeOf)
10247       return Unary;
10248   return nullptr;
10249 }
10250 
10251 /// If E is a sizeof expression, returns its argument expression,
10252 /// otherwise returns NULL.
10253 static const Expr *getSizeOfExprArg(const Expr *E) {
10254   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10255     if (!SizeOf->isArgumentType())
10256       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10257   return nullptr;
10258 }
10259 
10260 /// If E is a sizeof expression, returns its argument type.
10261 static QualType getSizeOfArgType(const Expr *E) {
10262   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10263     return SizeOf->getTypeOfArgument();
10264   return QualType();
10265 }
10266 
10267 namespace {
10268 
10269 struct SearchNonTrivialToInitializeField
10270     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10271   using Super =
10272       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10273 
10274   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10275 
10276   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10277                      SourceLocation SL) {
10278     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10279       asDerived().visitArray(PDIK, AT, SL);
10280       return;
10281     }
10282 
10283     Super::visitWithKind(PDIK, FT, SL);
10284   }
10285 
10286   void visitARCStrong(QualType FT, SourceLocation SL) {
10287     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10288   }
10289   void visitARCWeak(QualType FT, SourceLocation SL) {
10290     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10291   }
10292   void visitStruct(QualType FT, SourceLocation SL) {
10293     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10294       visit(FD->getType(), FD->getLocation());
10295   }
10296   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10297                   const ArrayType *AT, SourceLocation SL) {
10298     visit(getContext().getBaseElementType(AT), SL);
10299   }
10300   void visitTrivial(QualType FT, SourceLocation SL) {}
10301 
10302   static void diag(QualType RT, const Expr *E, Sema &S) {
10303     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10304   }
10305 
10306   ASTContext &getContext() { return S.getASTContext(); }
10307 
10308   const Expr *E;
10309   Sema &S;
10310 };
10311 
10312 struct SearchNonTrivialToCopyField
10313     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10314   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10315 
10316   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10317 
10318   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10319                      SourceLocation SL) {
10320     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10321       asDerived().visitArray(PCK, AT, SL);
10322       return;
10323     }
10324 
10325     Super::visitWithKind(PCK, FT, SL);
10326   }
10327 
10328   void visitARCStrong(QualType FT, SourceLocation SL) {
10329     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10330   }
10331   void visitARCWeak(QualType FT, SourceLocation SL) {
10332     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10333   }
10334   void visitStruct(QualType FT, SourceLocation SL) {
10335     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10336       visit(FD->getType(), FD->getLocation());
10337   }
10338   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10339                   SourceLocation SL) {
10340     visit(getContext().getBaseElementType(AT), SL);
10341   }
10342   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10343                 SourceLocation SL) {}
10344   void visitTrivial(QualType FT, SourceLocation SL) {}
10345   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10346 
10347   static void diag(QualType RT, const Expr *E, Sema &S) {
10348     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10349   }
10350 
10351   ASTContext &getContext() { return S.getASTContext(); }
10352 
10353   const Expr *E;
10354   Sema &S;
10355 };
10356 
10357 }
10358 
10359 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10360 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10361   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10362 
10363   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10364     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10365       return false;
10366 
10367     return doesExprLikelyComputeSize(BO->getLHS()) ||
10368            doesExprLikelyComputeSize(BO->getRHS());
10369   }
10370 
10371   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10372 }
10373 
10374 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10375 ///
10376 /// \code
10377 ///   #define MACRO 0
10378 ///   foo(MACRO);
10379 ///   foo(0);
10380 /// \endcode
10381 ///
10382 /// This should return true for the first call to foo, but not for the second
10383 /// (regardless of whether foo is a macro or function).
10384 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10385                                         SourceLocation CallLoc,
10386                                         SourceLocation ArgLoc) {
10387   if (!CallLoc.isMacroID())
10388     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10389 
10390   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10391          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10392 }
10393 
10394 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10395 /// last two arguments transposed.
10396 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10397   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10398     return;
10399 
10400   const Expr *SizeArg =
10401     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10402 
10403   auto isLiteralZero = [](const Expr *E) {
10404     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10405   };
10406 
10407   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10408   SourceLocation CallLoc = Call->getRParenLoc();
10409   SourceManager &SM = S.getSourceManager();
10410   if (isLiteralZero(SizeArg) &&
10411       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10412 
10413     SourceLocation DiagLoc = SizeArg->getExprLoc();
10414 
10415     // Some platforms #define bzero to __builtin_memset. See if this is the
10416     // case, and if so, emit a better diagnostic.
10417     if (BId == Builtin::BIbzero ||
10418         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10419                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10420       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10421       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10422     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10423       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10424       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10425     }
10426     return;
10427   }
10428 
10429   // If the second argument to a memset is a sizeof expression and the third
10430   // isn't, this is also likely an error. This should catch
10431   // 'memset(buf, sizeof(buf), 0xff)'.
10432   if (BId == Builtin::BImemset &&
10433       doesExprLikelyComputeSize(Call->getArg(1)) &&
10434       !doesExprLikelyComputeSize(Call->getArg(2))) {
10435     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10436     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10437     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10438     return;
10439   }
10440 }
10441 
10442 /// Check for dangerous or invalid arguments to memset().
10443 ///
10444 /// This issues warnings on known problematic, dangerous or unspecified
10445 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10446 /// function calls.
10447 ///
10448 /// \param Call The call expression to diagnose.
10449 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10450                                    unsigned BId,
10451                                    IdentifierInfo *FnName) {
10452   assert(BId != 0);
10453 
10454   // It is possible to have a non-standard definition of memset.  Validate
10455   // we have enough arguments, and if not, abort further checking.
10456   unsigned ExpectedNumArgs =
10457       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10458   if (Call->getNumArgs() < ExpectedNumArgs)
10459     return;
10460 
10461   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10462                       BId == Builtin::BIstrndup ? 1 : 2);
10463   unsigned LenArg =
10464       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10465   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10466 
10467   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10468                                      Call->getBeginLoc(), Call->getRParenLoc()))
10469     return;
10470 
10471   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10472   CheckMemaccessSize(*this, BId, Call);
10473 
10474   // We have special checking when the length is a sizeof expression.
10475   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10476   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10477   llvm::FoldingSetNodeID SizeOfArgID;
10478 
10479   // Although widely used, 'bzero' is not a standard function. Be more strict
10480   // with the argument types before allowing diagnostics and only allow the
10481   // form bzero(ptr, sizeof(...)).
10482   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10483   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10484     return;
10485 
10486   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10487     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10488     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10489 
10490     QualType DestTy = Dest->getType();
10491     QualType PointeeTy;
10492     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10493       PointeeTy = DestPtrTy->getPointeeType();
10494 
10495       // Never warn about void type pointers. This can be used to suppress
10496       // false positives.
10497       if (PointeeTy->isVoidType())
10498         continue;
10499 
10500       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10501       // actually comparing the expressions for equality. Because computing the
10502       // expression IDs can be expensive, we only do this if the diagnostic is
10503       // enabled.
10504       if (SizeOfArg &&
10505           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10506                            SizeOfArg->getExprLoc())) {
10507         // We only compute IDs for expressions if the warning is enabled, and
10508         // cache the sizeof arg's ID.
10509         if (SizeOfArgID == llvm::FoldingSetNodeID())
10510           SizeOfArg->Profile(SizeOfArgID, Context, true);
10511         llvm::FoldingSetNodeID DestID;
10512         Dest->Profile(DestID, Context, true);
10513         if (DestID == SizeOfArgID) {
10514           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10515           //       over sizeof(src) as well.
10516           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10517           StringRef ReadableName = FnName->getName();
10518 
10519           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10520             if (UnaryOp->getOpcode() == UO_AddrOf)
10521               ActionIdx = 1; // If its an address-of operator, just remove it.
10522           if (!PointeeTy->isIncompleteType() &&
10523               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10524             ActionIdx = 2; // If the pointee's size is sizeof(char),
10525                            // suggest an explicit length.
10526 
10527           // If the function is defined as a builtin macro, do not show macro
10528           // expansion.
10529           SourceLocation SL = SizeOfArg->getExprLoc();
10530           SourceRange DSR = Dest->getSourceRange();
10531           SourceRange SSR = SizeOfArg->getSourceRange();
10532           SourceManager &SM = getSourceManager();
10533 
10534           if (SM.isMacroArgExpansion(SL)) {
10535             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10536             SL = SM.getSpellingLoc(SL);
10537             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10538                              SM.getSpellingLoc(DSR.getEnd()));
10539             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10540                              SM.getSpellingLoc(SSR.getEnd()));
10541           }
10542 
10543           DiagRuntimeBehavior(SL, SizeOfArg,
10544                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10545                                 << ReadableName
10546                                 << PointeeTy
10547                                 << DestTy
10548                                 << DSR
10549                                 << SSR);
10550           DiagRuntimeBehavior(SL, SizeOfArg,
10551                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10552                                 << ActionIdx
10553                                 << SSR);
10554 
10555           break;
10556         }
10557       }
10558 
10559       // Also check for cases where the sizeof argument is the exact same
10560       // type as the memory argument, and where it points to a user-defined
10561       // record type.
10562       if (SizeOfArgTy != QualType()) {
10563         if (PointeeTy->isRecordType() &&
10564             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10565           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10566                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10567                                 << FnName << SizeOfArgTy << ArgIdx
10568                                 << PointeeTy << Dest->getSourceRange()
10569                                 << LenExpr->getSourceRange());
10570           break;
10571         }
10572       }
10573     } else if (DestTy->isArrayType()) {
10574       PointeeTy = DestTy;
10575     }
10576 
10577     if (PointeeTy == QualType())
10578       continue;
10579 
10580     // Always complain about dynamic classes.
10581     bool IsContained;
10582     if (const CXXRecordDecl *ContainedRD =
10583             getContainedDynamicClass(PointeeTy, IsContained)) {
10584 
10585       unsigned OperationType = 0;
10586       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10587       // "overwritten" if we're warning about the destination for any call
10588       // but memcmp; otherwise a verb appropriate to the call.
10589       if (ArgIdx != 0 || IsCmp) {
10590         if (BId == Builtin::BImemcpy)
10591           OperationType = 1;
10592         else if(BId == Builtin::BImemmove)
10593           OperationType = 2;
10594         else if (IsCmp)
10595           OperationType = 3;
10596       }
10597 
10598       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10599                           PDiag(diag::warn_dyn_class_memaccess)
10600                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10601                               << IsContained << ContainedRD << OperationType
10602                               << Call->getCallee()->getSourceRange());
10603     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10604              BId != Builtin::BImemset)
10605       DiagRuntimeBehavior(
10606         Dest->getExprLoc(), Dest,
10607         PDiag(diag::warn_arc_object_memaccess)
10608           << ArgIdx << FnName << PointeeTy
10609           << Call->getCallee()->getSourceRange());
10610     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10611       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10612           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10613         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10614                             PDiag(diag::warn_cstruct_memaccess)
10615                                 << ArgIdx << FnName << PointeeTy << 0);
10616         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10617       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10618                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10619         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10620                             PDiag(diag::warn_cstruct_memaccess)
10621                                 << ArgIdx << FnName << PointeeTy << 1);
10622         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10623       } else {
10624         continue;
10625       }
10626     } else
10627       continue;
10628 
10629     DiagRuntimeBehavior(
10630       Dest->getExprLoc(), Dest,
10631       PDiag(diag::note_bad_memaccess_silence)
10632         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10633     break;
10634   }
10635 }
10636 
10637 // A little helper routine: ignore addition and subtraction of integer literals.
10638 // This intentionally does not ignore all integer constant expressions because
10639 // we don't want to remove sizeof().
10640 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10641   Ex = Ex->IgnoreParenCasts();
10642 
10643   while (true) {
10644     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10645     if (!BO || !BO->isAdditiveOp())
10646       break;
10647 
10648     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10649     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10650 
10651     if (isa<IntegerLiteral>(RHS))
10652       Ex = LHS;
10653     else if (isa<IntegerLiteral>(LHS))
10654       Ex = RHS;
10655     else
10656       break;
10657   }
10658 
10659   return Ex;
10660 }
10661 
10662 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10663                                                       ASTContext &Context) {
10664   // Only handle constant-sized or VLAs, but not flexible members.
10665   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10666     // Only issue the FIXIT for arrays of size > 1.
10667     if (CAT->getSize().getSExtValue() <= 1)
10668       return false;
10669   } else if (!Ty->isVariableArrayType()) {
10670     return false;
10671   }
10672   return true;
10673 }
10674 
10675 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10676 // be the size of the source, instead of the destination.
10677 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10678                                     IdentifierInfo *FnName) {
10679 
10680   // Don't crash if the user has the wrong number of arguments
10681   unsigned NumArgs = Call->getNumArgs();
10682   if ((NumArgs != 3) && (NumArgs != 4))
10683     return;
10684 
10685   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10686   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10687   const Expr *CompareWithSrc = nullptr;
10688 
10689   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10690                                      Call->getBeginLoc(), Call->getRParenLoc()))
10691     return;
10692 
10693   // Look for 'strlcpy(dst, x, sizeof(x))'
10694   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10695     CompareWithSrc = Ex;
10696   else {
10697     // Look for 'strlcpy(dst, x, strlen(x))'
10698     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10699       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10700           SizeCall->getNumArgs() == 1)
10701         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10702     }
10703   }
10704 
10705   if (!CompareWithSrc)
10706     return;
10707 
10708   // Determine if the argument to sizeof/strlen is equal to the source
10709   // argument.  In principle there's all kinds of things you could do
10710   // here, for instance creating an == expression and evaluating it with
10711   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10712   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10713   if (!SrcArgDRE)
10714     return;
10715 
10716   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10717   if (!CompareWithSrcDRE ||
10718       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10719     return;
10720 
10721   const Expr *OriginalSizeArg = Call->getArg(2);
10722   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10723       << OriginalSizeArg->getSourceRange() << FnName;
10724 
10725   // Output a FIXIT hint if the destination is an array (rather than a
10726   // pointer to an array).  This could be enhanced to handle some
10727   // pointers if we know the actual size, like if DstArg is 'array+2'
10728   // we could say 'sizeof(array)-2'.
10729   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10730   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10731     return;
10732 
10733   SmallString<128> sizeString;
10734   llvm::raw_svector_ostream OS(sizeString);
10735   OS << "sizeof(";
10736   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10737   OS << ")";
10738 
10739   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10740       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10741                                       OS.str());
10742 }
10743 
10744 /// Check if two expressions refer to the same declaration.
10745 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10746   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10747     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10748       return D1->getDecl() == D2->getDecl();
10749   return false;
10750 }
10751 
10752 static const Expr *getStrlenExprArg(const Expr *E) {
10753   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10754     const FunctionDecl *FD = CE->getDirectCallee();
10755     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10756       return nullptr;
10757     return CE->getArg(0)->IgnoreParenCasts();
10758   }
10759   return nullptr;
10760 }
10761 
10762 // Warn on anti-patterns as the 'size' argument to strncat.
10763 // The correct size argument should look like following:
10764 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10765 void Sema::CheckStrncatArguments(const CallExpr *CE,
10766                                  IdentifierInfo *FnName) {
10767   // Don't crash if the user has the wrong number of arguments.
10768   if (CE->getNumArgs() < 3)
10769     return;
10770   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10771   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10772   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10773 
10774   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10775                                      CE->getRParenLoc()))
10776     return;
10777 
10778   // Identify common expressions, which are wrongly used as the size argument
10779   // to strncat and may lead to buffer overflows.
10780   unsigned PatternType = 0;
10781   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10782     // - sizeof(dst)
10783     if (referToTheSameDecl(SizeOfArg, DstArg))
10784       PatternType = 1;
10785     // - sizeof(src)
10786     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10787       PatternType = 2;
10788   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10789     if (BE->getOpcode() == BO_Sub) {
10790       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10791       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10792       // - sizeof(dst) - strlen(dst)
10793       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10794           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10795         PatternType = 1;
10796       // - sizeof(src) - (anything)
10797       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10798         PatternType = 2;
10799     }
10800   }
10801 
10802   if (PatternType == 0)
10803     return;
10804 
10805   // Generate the diagnostic.
10806   SourceLocation SL = LenArg->getBeginLoc();
10807   SourceRange SR = LenArg->getSourceRange();
10808   SourceManager &SM = getSourceManager();
10809 
10810   // If the function is defined as a builtin macro, do not show macro expansion.
10811   if (SM.isMacroArgExpansion(SL)) {
10812     SL = SM.getSpellingLoc(SL);
10813     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10814                      SM.getSpellingLoc(SR.getEnd()));
10815   }
10816 
10817   // Check if the destination is an array (rather than a pointer to an array).
10818   QualType DstTy = DstArg->getType();
10819   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10820                                                                     Context);
10821   if (!isKnownSizeArray) {
10822     if (PatternType == 1)
10823       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10824     else
10825       Diag(SL, diag::warn_strncat_src_size) << SR;
10826     return;
10827   }
10828 
10829   if (PatternType == 1)
10830     Diag(SL, diag::warn_strncat_large_size) << SR;
10831   else
10832     Diag(SL, diag::warn_strncat_src_size) << SR;
10833 
10834   SmallString<128> sizeString;
10835   llvm::raw_svector_ostream OS(sizeString);
10836   OS << "sizeof(";
10837   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10838   OS << ") - ";
10839   OS << "strlen(";
10840   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10841   OS << ") - 1";
10842 
10843   Diag(SL, diag::note_strncat_wrong_size)
10844     << FixItHint::CreateReplacement(SR, OS.str());
10845 }
10846 
10847 namespace {
10848 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10849                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10850   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10851     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10852         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10853     return;
10854   }
10855 }
10856 
10857 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10858                                  const UnaryOperator *UnaryExpr) {
10859   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10860     const Decl *D = Lvalue->getDecl();
10861     if (isa<DeclaratorDecl>(D))
10862       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10863         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10864   }
10865 
10866   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10867     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10868                                       Lvalue->getMemberDecl());
10869 }
10870 
10871 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10872                             const UnaryOperator *UnaryExpr) {
10873   const auto *Lambda = dyn_cast<LambdaExpr>(
10874       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10875   if (!Lambda)
10876     return;
10877 
10878   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10879       << CalleeName << 2 /*object: lambda expression*/;
10880 }
10881 
10882 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10883                                   const DeclRefExpr *Lvalue) {
10884   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10885   if (Var == nullptr)
10886     return;
10887 
10888   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10889       << CalleeName << 0 /*object: */ << Var;
10890 }
10891 
10892 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10893                             const CastExpr *Cast) {
10894   SmallString<128> SizeString;
10895   llvm::raw_svector_ostream OS(SizeString);
10896 
10897   clang::CastKind Kind = Cast->getCastKind();
10898   if (Kind == clang::CK_BitCast &&
10899       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10900     return;
10901   if (Kind == clang::CK_IntegralToPointer &&
10902       !isa<IntegerLiteral>(
10903           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10904     return;
10905 
10906   switch (Cast->getCastKind()) {
10907   case clang::CK_BitCast:
10908   case clang::CK_IntegralToPointer:
10909   case clang::CK_FunctionToPointerDecay:
10910     OS << '\'';
10911     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10912     OS << '\'';
10913     break;
10914   default:
10915     return;
10916   }
10917 
10918   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10919       << CalleeName << 0 /*object: */ << OS.str();
10920 }
10921 } // namespace
10922 
10923 /// Alerts the user that they are attempting to free a non-malloc'd object.
10924 void Sema::CheckFreeArguments(const CallExpr *E) {
10925   const std::string CalleeName =
10926       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10927 
10928   { // Prefer something that doesn't involve a cast to make things simpler.
10929     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10930     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10931       switch (UnaryExpr->getOpcode()) {
10932       case UnaryOperator::Opcode::UO_AddrOf:
10933         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10934       case UnaryOperator::Opcode::UO_Plus:
10935         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10936       default:
10937         break;
10938       }
10939 
10940     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10941       if (Lvalue->getType()->isArrayType())
10942         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10943 
10944     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10945       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10946           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10947       return;
10948     }
10949 
10950     if (isa<BlockExpr>(Arg)) {
10951       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10952           << CalleeName << 1 /*object: block*/;
10953       return;
10954     }
10955   }
10956   // Maybe the cast was important, check after the other cases.
10957   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10958     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10959 }
10960 
10961 void
10962 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10963                          SourceLocation ReturnLoc,
10964                          bool isObjCMethod,
10965                          const AttrVec *Attrs,
10966                          const FunctionDecl *FD) {
10967   // Check if the return value is null but should not be.
10968   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10969        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10970       CheckNonNullExpr(*this, RetValExp))
10971     Diag(ReturnLoc, diag::warn_null_ret)
10972       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10973 
10974   // C++11 [basic.stc.dynamic.allocation]p4:
10975   //   If an allocation function declared with a non-throwing
10976   //   exception-specification fails to allocate storage, it shall return
10977   //   a null pointer. Any other allocation function that fails to allocate
10978   //   storage shall indicate failure only by throwing an exception [...]
10979   if (FD) {
10980     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10981     if (Op == OO_New || Op == OO_Array_New) {
10982       const FunctionProtoType *Proto
10983         = FD->getType()->castAs<FunctionProtoType>();
10984       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10985           CheckNonNullExpr(*this, RetValExp))
10986         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10987           << FD << getLangOpts().CPlusPlus11;
10988     }
10989   }
10990 
10991   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10992   // here prevent the user from using a PPC MMA type as trailing return type.
10993   if (Context.getTargetInfo().getTriple().isPPC64())
10994     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10995 }
10996 
10997 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10998 
10999 /// Check for comparisons of floating point operands using != and ==.
11000 /// Issue a warning if these are no self-comparisons, as they are not likely
11001 /// to do what the programmer intended.
11002 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
11003   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
11004   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
11005 
11006   // Special case: check for x == x (which is OK).
11007   // Do not emit warnings for such cases.
11008   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
11009     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
11010       if (DRL->getDecl() == DRR->getDecl())
11011         return;
11012 
11013   // Special case: check for comparisons against literals that can be exactly
11014   //  represented by APFloat.  In such cases, do not emit a warning.  This
11015   //  is a heuristic: often comparison against such literals are used to
11016   //  detect if a value in a variable has not changed.  This clearly can
11017   //  lead to false negatives.
11018   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
11019     if (FLL->isExact())
11020       return;
11021   } else
11022     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
11023       if (FLR->isExact())
11024         return;
11025 
11026   // Check for comparisons with builtin types.
11027   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11028     if (CL->getBuiltinCallee())
11029       return;
11030 
11031   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11032     if (CR->getBuiltinCallee())
11033       return;
11034 
11035   // Emit the diagnostic.
11036   Diag(Loc, diag::warn_floatingpoint_eq)
11037     << LHS->getSourceRange() << RHS->getSourceRange();
11038 }
11039 
11040 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11041 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11042 
11043 namespace {
11044 
11045 /// Structure recording the 'active' range of an integer-valued
11046 /// expression.
11047 struct IntRange {
11048   /// The number of bits active in the int. Note that this includes exactly one
11049   /// sign bit if !NonNegative.
11050   unsigned Width;
11051 
11052   /// True if the int is known not to have negative values. If so, all leading
11053   /// bits before Width are known zero, otherwise they are known to be the
11054   /// same as the MSB within Width.
11055   bool NonNegative;
11056 
11057   IntRange(unsigned Width, bool NonNegative)
11058       : Width(Width), NonNegative(NonNegative) {}
11059 
11060   /// Number of bits excluding the sign bit.
11061   unsigned valueBits() const {
11062     return NonNegative ? Width : Width - 1;
11063   }
11064 
11065   /// Returns the range of the bool type.
11066   static IntRange forBoolType() {
11067     return IntRange(1, true);
11068   }
11069 
11070   /// Returns the range of an opaque value of the given integral type.
11071   static IntRange forValueOfType(ASTContext &C, QualType T) {
11072     return forValueOfCanonicalType(C,
11073                           T->getCanonicalTypeInternal().getTypePtr());
11074   }
11075 
11076   /// Returns the range of an opaque value of a canonical integral type.
11077   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11078     assert(T->isCanonicalUnqualified());
11079 
11080     if (const VectorType *VT = dyn_cast<VectorType>(T))
11081       T = VT->getElementType().getTypePtr();
11082     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11083       T = CT->getElementType().getTypePtr();
11084     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11085       T = AT->getValueType().getTypePtr();
11086 
11087     if (!C.getLangOpts().CPlusPlus) {
11088       // For enum types in C code, use the underlying datatype.
11089       if (const EnumType *ET = dyn_cast<EnumType>(T))
11090         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11091     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11092       // For enum types in C++, use the known bit width of the enumerators.
11093       EnumDecl *Enum = ET->getDecl();
11094       // In C++11, enums can have a fixed underlying type. Use this type to
11095       // compute the range.
11096       if (Enum->isFixed()) {
11097         return IntRange(C.getIntWidth(QualType(T, 0)),
11098                         !ET->isSignedIntegerOrEnumerationType());
11099       }
11100 
11101       unsigned NumPositive = Enum->getNumPositiveBits();
11102       unsigned NumNegative = Enum->getNumNegativeBits();
11103 
11104       if (NumNegative == 0)
11105         return IntRange(NumPositive, true/*NonNegative*/);
11106       else
11107         return IntRange(std::max(NumPositive + 1, NumNegative),
11108                         false/*NonNegative*/);
11109     }
11110 
11111     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11112       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11113 
11114     const BuiltinType *BT = cast<BuiltinType>(T);
11115     assert(BT->isInteger());
11116 
11117     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11118   }
11119 
11120   /// Returns the "target" range of a canonical integral type, i.e.
11121   /// the range of values expressible in the type.
11122   ///
11123   /// This matches forValueOfCanonicalType except that enums have the
11124   /// full range of their type, not the range of their enumerators.
11125   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11126     assert(T->isCanonicalUnqualified());
11127 
11128     if (const VectorType *VT = dyn_cast<VectorType>(T))
11129       T = VT->getElementType().getTypePtr();
11130     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11131       T = CT->getElementType().getTypePtr();
11132     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11133       T = AT->getValueType().getTypePtr();
11134     if (const EnumType *ET = dyn_cast<EnumType>(T))
11135       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11136 
11137     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11138       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11139 
11140     const BuiltinType *BT = cast<BuiltinType>(T);
11141     assert(BT->isInteger());
11142 
11143     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11144   }
11145 
11146   /// Returns the supremum of two ranges: i.e. their conservative merge.
11147   static IntRange join(IntRange L, IntRange R) {
11148     bool Unsigned = L.NonNegative && R.NonNegative;
11149     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11150                     L.NonNegative && R.NonNegative);
11151   }
11152 
11153   /// Return the range of a bitwise-AND of the two ranges.
11154   static IntRange bit_and(IntRange L, IntRange R) {
11155     unsigned Bits = std::max(L.Width, R.Width);
11156     bool NonNegative = false;
11157     if (L.NonNegative) {
11158       Bits = std::min(Bits, L.Width);
11159       NonNegative = true;
11160     }
11161     if (R.NonNegative) {
11162       Bits = std::min(Bits, R.Width);
11163       NonNegative = true;
11164     }
11165     return IntRange(Bits, NonNegative);
11166   }
11167 
11168   /// Return the range of a sum of the two ranges.
11169   static IntRange sum(IntRange L, IntRange R) {
11170     bool Unsigned = L.NonNegative && R.NonNegative;
11171     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11172                     Unsigned);
11173   }
11174 
11175   /// Return the range of a difference of the two ranges.
11176   static IntRange difference(IntRange L, IntRange R) {
11177     // We need a 1-bit-wider range if:
11178     //   1) LHS can be negative: least value can be reduced.
11179     //   2) RHS can be negative: greatest value can be increased.
11180     bool CanWiden = !L.NonNegative || !R.NonNegative;
11181     bool Unsigned = L.NonNegative && R.Width == 0;
11182     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11183                         !Unsigned,
11184                     Unsigned);
11185   }
11186 
11187   /// Return the range of a product of the two ranges.
11188   static IntRange product(IntRange L, IntRange R) {
11189     // If both LHS and RHS can be negative, we can form
11190     //   -2^L * -2^R = 2^(L + R)
11191     // which requires L + R + 1 value bits to represent.
11192     bool CanWiden = !L.NonNegative && !R.NonNegative;
11193     bool Unsigned = L.NonNegative && R.NonNegative;
11194     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11195                     Unsigned);
11196   }
11197 
11198   /// Return the range of a remainder operation between the two ranges.
11199   static IntRange rem(IntRange L, IntRange R) {
11200     // The result of a remainder can't be larger than the result of
11201     // either side. The sign of the result is the sign of the LHS.
11202     bool Unsigned = L.NonNegative;
11203     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11204                     Unsigned);
11205   }
11206 };
11207 
11208 } // namespace
11209 
11210 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11211                               unsigned MaxWidth) {
11212   if (value.isSigned() && value.isNegative())
11213     return IntRange(value.getMinSignedBits(), false);
11214 
11215   if (value.getBitWidth() > MaxWidth)
11216     value = value.trunc(MaxWidth);
11217 
11218   // isNonNegative() just checks the sign bit without considering
11219   // signedness.
11220   return IntRange(value.getActiveBits(), true);
11221 }
11222 
11223 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11224                               unsigned MaxWidth) {
11225   if (result.isInt())
11226     return GetValueRange(C, result.getInt(), MaxWidth);
11227 
11228   if (result.isVector()) {
11229     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11230     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11231       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11232       R = IntRange::join(R, El);
11233     }
11234     return R;
11235   }
11236 
11237   if (result.isComplexInt()) {
11238     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11239     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11240     return IntRange::join(R, I);
11241   }
11242 
11243   // This can happen with lossless casts to intptr_t of "based" lvalues.
11244   // Assume it might use arbitrary bits.
11245   // FIXME: The only reason we need to pass the type in here is to get
11246   // the sign right on this one case.  It would be nice if APValue
11247   // preserved this.
11248   assert(result.isLValue() || result.isAddrLabelDiff());
11249   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11250 }
11251 
11252 static QualType GetExprType(const Expr *E) {
11253   QualType Ty = E->getType();
11254   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11255     Ty = AtomicRHS->getValueType();
11256   return Ty;
11257 }
11258 
11259 /// Pseudo-evaluate the given integer expression, estimating the
11260 /// range of values it might take.
11261 ///
11262 /// \param MaxWidth The width to which the value will be truncated.
11263 /// \param Approximate If \c true, return a likely range for the result: in
11264 ///        particular, assume that arithmetic on narrower types doesn't leave
11265 ///        those types. If \c false, return a range including all possible
11266 ///        result values.
11267 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11268                              bool InConstantContext, bool Approximate) {
11269   E = E->IgnoreParens();
11270 
11271   // Try a full evaluation first.
11272   Expr::EvalResult result;
11273   if (E->EvaluateAsRValue(result, C, InConstantContext))
11274     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11275 
11276   // I think we only want to look through implicit casts here; if the
11277   // user has an explicit widening cast, we should treat the value as
11278   // being of the new, wider type.
11279   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11280     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11281       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11282                           Approximate);
11283 
11284     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11285 
11286     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11287                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11288 
11289     // Assume that non-integer casts can span the full range of the type.
11290     if (!isIntegerCast)
11291       return OutputTypeRange;
11292 
11293     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11294                                      std::min(MaxWidth, OutputTypeRange.Width),
11295                                      InConstantContext, Approximate);
11296 
11297     // Bail out if the subexpr's range is as wide as the cast type.
11298     if (SubRange.Width >= OutputTypeRange.Width)
11299       return OutputTypeRange;
11300 
11301     // Otherwise, we take the smaller width, and we're non-negative if
11302     // either the output type or the subexpr is.
11303     return IntRange(SubRange.Width,
11304                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11305   }
11306 
11307   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11308     // If we can fold the condition, just take that operand.
11309     bool CondResult;
11310     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11311       return GetExprRange(C,
11312                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11313                           MaxWidth, InConstantContext, Approximate);
11314 
11315     // Otherwise, conservatively merge.
11316     // GetExprRange requires an integer expression, but a throw expression
11317     // results in a void type.
11318     Expr *E = CO->getTrueExpr();
11319     IntRange L = E->getType()->isVoidType()
11320                      ? IntRange{0, true}
11321                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11322     E = CO->getFalseExpr();
11323     IntRange R = E->getType()->isVoidType()
11324                      ? IntRange{0, true}
11325                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11326     return IntRange::join(L, R);
11327   }
11328 
11329   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11330     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11331 
11332     switch (BO->getOpcode()) {
11333     case BO_Cmp:
11334       llvm_unreachable("builtin <=> should have class type");
11335 
11336     // Boolean-valued operations are single-bit and positive.
11337     case BO_LAnd:
11338     case BO_LOr:
11339     case BO_LT:
11340     case BO_GT:
11341     case BO_LE:
11342     case BO_GE:
11343     case BO_EQ:
11344     case BO_NE:
11345       return IntRange::forBoolType();
11346 
11347     // The type of the assignments is the type of the LHS, so the RHS
11348     // is not necessarily the same type.
11349     case BO_MulAssign:
11350     case BO_DivAssign:
11351     case BO_RemAssign:
11352     case BO_AddAssign:
11353     case BO_SubAssign:
11354     case BO_XorAssign:
11355     case BO_OrAssign:
11356       // TODO: bitfields?
11357       return IntRange::forValueOfType(C, GetExprType(E));
11358 
11359     // Simple assignments just pass through the RHS, which will have
11360     // been coerced to the LHS type.
11361     case BO_Assign:
11362       // TODO: bitfields?
11363       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11364                           Approximate);
11365 
11366     // Operations with opaque sources are black-listed.
11367     case BO_PtrMemD:
11368     case BO_PtrMemI:
11369       return IntRange::forValueOfType(C, GetExprType(E));
11370 
11371     // Bitwise-and uses the *infinum* of the two source ranges.
11372     case BO_And:
11373     case BO_AndAssign:
11374       Combine = IntRange::bit_and;
11375       break;
11376 
11377     // Left shift gets black-listed based on a judgement call.
11378     case BO_Shl:
11379       // ...except that we want to treat '1 << (blah)' as logically
11380       // positive.  It's an important idiom.
11381       if (IntegerLiteral *I
11382             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11383         if (I->getValue() == 1) {
11384           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11385           return IntRange(R.Width, /*NonNegative*/ true);
11386         }
11387       }
11388       LLVM_FALLTHROUGH;
11389 
11390     case BO_ShlAssign:
11391       return IntRange::forValueOfType(C, GetExprType(E));
11392 
11393     // Right shift by a constant can narrow its left argument.
11394     case BO_Shr:
11395     case BO_ShrAssign: {
11396       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11397                                 Approximate);
11398 
11399       // If the shift amount is a positive constant, drop the width by
11400       // that much.
11401       if (Optional<llvm::APSInt> shift =
11402               BO->getRHS()->getIntegerConstantExpr(C)) {
11403         if (shift->isNonNegative()) {
11404           unsigned zext = shift->getZExtValue();
11405           if (zext >= L.Width)
11406             L.Width = (L.NonNegative ? 0 : 1);
11407           else
11408             L.Width -= zext;
11409         }
11410       }
11411 
11412       return L;
11413     }
11414 
11415     // Comma acts as its right operand.
11416     case BO_Comma:
11417       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11418                           Approximate);
11419 
11420     case BO_Add:
11421       if (!Approximate)
11422         Combine = IntRange::sum;
11423       break;
11424 
11425     case BO_Sub:
11426       if (BO->getLHS()->getType()->isPointerType())
11427         return IntRange::forValueOfType(C, GetExprType(E));
11428       if (!Approximate)
11429         Combine = IntRange::difference;
11430       break;
11431 
11432     case BO_Mul:
11433       if (!Approximate)
11434         Combine = IntRange::product;
11435       break;
11436 
11437     // The width of a division result is mostly determined by the size
11438     // of the LHS.
11439     case BO_Div: {
11440       // Don't 'pre-truncate' the operands.
11441       unsigned opWidth = C.getIntWidth(GetExprType(E));
11442       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11443                                 Approximate);
11444 
11445       // If the divisor is constant, use that.
11446       if (Optional<llvm::APSInt> divisor =
11447               BO->getRHS()->getIntegerConstantExpr(C)) {
11448         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11449         if (log2 >= L.Width)
11450           L.Width = (L.NonNegative ? 0 : 1);
11451         else
11452           L.Width = std::min(L.Width - log2, MaxWidth);
11453         return L;
11454       }
11455 
11456       // Otherwise, just use the LHS's width.
11457       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11458       // could be -1.
11459       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11460                                 Approximate);
11461       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11462     }
11463 
11464     case BO_Rem:
11465       Combine = IntRange::rem;
11466       break;
11467 
11468     // The default behavior is okay for these.
11469     case BO_Xor:
11470     case BO_Or:
11471       break;
11472     }
11473 
11474     // Combine the two ranges, but limit the result to the type in which we
11475     // performed the computation.
11476     QualType T = GetExprType(E);
11477     unsigned opWidth = C.getIntWidth(T);
11478     IntRange L =
11479         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11480     IntRange R =
11481         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11482     IntRange C = Combine(L, R);
11483     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11484     C.Width = std::min(C.Width, MaxWidth);
11485     return C;
11486   }
11487 
11488   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11489     switch (UO->getOpcode()) {
11490     // Boolean-valued operations are white-listed.
11491     case UO_LNot:
11492       return IntRange::forBoolType();
11493 
11494     // Operations with opaque sources are black-listed.
11495     case UO_Deref:
11496     case UO_AddrOf: // should be impossible
11497       return IntRange::forValueOfType(C, GetExprType(E));
11498 
11499     default:
11500       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11501                           Approximate);
11502     }
11503   }
11504 
11505   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11506     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11507                         Approximate);
11508 
11509   if (const auto *BitField = E->getSourceBitField())
11510     return IntRange(BitField->getBitWidthValue(C),
11511                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11512 
11513   return IntRange::forValueOfType(C, GetExprType(E));
11514 }
11515 
11516 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11517                              bool InConstantContext, bool Approximate) {
11518   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11519                       Approximate);
11520 }
11521 
11522 /// Checks whether the given value, which currently has the given
11523 /// source semantics, has the same value when coerced through the
11524 /// target semantics.
11525 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11526                                  const llvm::fltSemantics &Src,
11527                                  const llvm::fltSemantics &Tgt) {
11528   llvm::APFloat truncated = value;
11529 
11530   bool ignored;
11531   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11532   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11533 
11534   return truncated.bitwiseIsEqual(value);
11535 }
11536 
11537 /// Checks whether the given value, which currently has the given
11538 /// source semantics, has the same value when coerced through the
11539 /// target semantics.
11540 ///
11541 /// The value might be a vector of floats (or a complex number).
11542 static bool IsSameFloatAfterCast(const APValue &value,
11543                                  const llvm::fltSemantics &Src,
11544                                  const llvm::fltSemantics &Tgt) {
11545   if (value.isFloat())
11546     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11547 
11548   if (value.isVector()) {
11549     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11550       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11551         return false;
11552     return true;
11553   }
11554 
11555   assert(value.isComplexFloat());
11556   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11557           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11558 }
11559 
11560 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11561                                        bool IsListInit = false);
11562 
11563 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11564   // Suppress cases where we are comparing against an enum constant.
11565   if (const DeclRefExpr *DR =
11566       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11567     if (isa<EnumConstantDecl>(DR->getDecl()))
11568       return true;
11569 
11570   // Suppress cases where the value is expanded from a macro, unless that macro
11571   // is how a language represents a boolean literal. This is the case in both C
11572   // and Objective-C.
11573   SourceLocation BeginLoc = E->getBeginLoc();
11574   if (BeginLoc.isMacroID()) {
11575     StringRef MacroName = Lexer::getImmediateMacroName(
11576         BeginLoc, S.getSourceManager(), S.getLangOpts());
11577     return MacroName != "YES" && MacroName != "NO" &&
11578            MacroName != "true" && MacroName != "false";
11579   }
11580 
11581   return false;
11582 }
11583 
11584 static bool isKnownToHaveUnsignedValue(Expr *E) {
11585   return E->getType()->isIntegerType() &&
11586          (!E->getType()->isSignedIntegerType() ||
11587           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11588 }
11589 
11590 namespace {
11591 /// The promoted range of values of a type. In general this has the
11592 /// following structure:
11593 ///
11594 ///     |-----------| . . . |-----------|
11595 ///     ^           ^       ^           ^
11596 ///    Min       HoleMin  HoleMax      Max
11597 ///
11598 /// ... where there is only a hole if a signed type is promoted to unsigned
11599 /// (in which case Min and Max are the smallest and largest representable
11600 /// values).
11601 struct PromotedRange {
11602   // Min, or HoleMax if there is a hole.
11603   llvm::APSInt PromotedMin;
11604   // Max, or HoleMin if there is a hole.
11605   llvm::APSInt PromotedMax;
11606 
11607   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11608     if (R.Width == 0)
11609       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11610     else if (R.Width >= BitWidth && !Unsigned) {
11611       // Promotion made the type *narrower*. This happens when promoting
11612       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11613       // Treat all values of 'signed int' as being in range for now.
11614       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11615       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11616     } else {
11617       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11618                         .extOrTrunc(BitWidth);
11619       PromotedMin.setIsUnsigned(Unsigned);
11620 
11621       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11622                         .extOrTrunc(BitWidth);
11623       PromotedMax.setIsUnsigned(Unsigned);
11624     }
11625   }
11626 
11627   // Determine whether this range is contiguous (has no hole).
11628   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11629 
11630   // Where a constant value is within the range.
11631   enum ComparisonResult {
11632     LT = 0x1,
11633     LE = 0x2,
11634     GT = 0x4,
11635     GE = 0x8,
11636     EQ = 0x10,
11637     NE = 0x20,
11638     InRangeFlag = 0x40,
11639 
11640     Less = LE | LT | NE,
11641     Min = LE | InRangeFlag,
11642     InRange = InRangeFlag,
11643     Max = GE | InRangeFlag,
11644     Greater = GE | GT | NE,
11645 
11646     OnlyValue = LE | GE | EQ | InRangeFlag,
11647     InHole = NE
11648   };
11649 
11650   ComparisonResult compare(const llvm::APSInt &Value) const {
11651     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11652            Value.isUnsigned() == PromotedMin.isUnsigned());
11653     if (!isContiguous()) {
11654       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11655       if (Value.isMinValue()) return Min;
11656       if (Value.isMaxValue()) return Max;
11657       if (Value >= PromotedMin) return InRange;
11658       if (Value <= PromotedMax) return InRange;
11659       return InHole;
11660     }
11661 
11662     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11663     case -1: return Less;
11664     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11665     case 1:
11666       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11667       case -1: return InRange;
11668       case 0: return Max;
11669       case 1: return Greater;
11670       }
11671     }
11672 
11673     llvm_unreachable("impossible compare result");
11674   }
11675 
11676   static llvm::Optional<StringRef>
11677   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11678     if (Op == BO_Cmp) {
11679       ComparisonResult LTFlag = LT, GTFlag = GT;
11680       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11681 
11682       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11683       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11684       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11685       return llvm::None;
11686     }
11687 
11688     ComparisonResult TrueFlag, FalseFlag;
11689     if (Op == BO_EQ) {
11690       TrueFlag = EQ;
11691       FalseFlag = NE;
11692     } else if (Op == BO_NE) {
11693       TrueFlag = NE;
11694       FalseFlag = EQ;
11695     } else {
11696       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11697         TrueFlag = LT;
11698         FalseFlag = GE;
11699       } else {
11700         TrueFlag = GT;
11701         FalseFlag = LE;
11702       }
11703       if (Op == BO_GE || Op == BO_LE)
11704         std::swap(TrueFlag, FalseFlag);
11705     }
11706     if (R & TrueFlag)
11707       return StringRef("true");
11708     if (R & FalseFlag)
11709       return StringRef("false");
11710     return llvm::None;
11711   }
11712 };
11713 }
11714 
11715 static bool HasEnumType(Expr *E) {
11716   // Strip off implicit integral promotions.
11717   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11718     if (ICE->getCastKind() != CK_IntegralCast &&
11719         ICE->getCastKind() != CK_NoOp)
11720       break;
11721     E = ICE->getSubExpr();
11722   }
11723 
11724   return E->getType()->isEnumeralType();
11725 }
11726 
11727 static int classifyConstantValue(Expr *Constant) {
11728   // The values of this enumeration are used in the diagnostics
11729   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11730   enum ConstantValueKind {
11731     Miscellaneous = 0,
11732     LiteralTrue,
11733     LiteralFalse
11734   };
11735   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11736     return BL->getValue() ? ConstantValueKind::LiteralTrue
11737                           : ConstantValueKind::LiteralFalse;
11738   return ConstantValueKind::Miscellaneous;
11739 }
11740 
11741 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11742                                         Expr *Constant, Expr *Other,
11743                                         const llvm::APSInt &Value,
11744                                         bool RhsConstant) {
11745   if (S.inTemplateInstantiation())
11746     return false;
11747 
11748   Expr *OriginalOther = Other;
11749 
11750   Constant = Constant->IgnoreParenImpCasts();
11751   Other = Other->IgnoreParenImpCasts();
11752 
11753   // Suppress warnings on tautological comparisons between values of the same
11754   // enumeration type. There are only two ways we could warn on this:
11755   //  - If the constant is outside the range of representable values of
11756   //    the enumeration. In such a case, we should warn about the cast
11757   //    to enumeration type, not about the comparison.
11758   //  - If the constant is the maximum / minimum in-range value. For an
11759   //    enumeratin type, such comparisons can be meaningful and useful.
11760   if (Constant->getType()->isEnumeralType() &&
11761       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11762     return false;
11763 
11764   IntRange OtherValueRange = GetExprRange(
11765       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11766 
11767   QualType OtherT = Other->getType();
11768   if (const auto *AT = OtherT->getAs<AtomicType>())
11769     OtherT = AT->getValueType();
11770   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11771 
11772   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11773   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11774   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11775                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11776                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11777 
11778   // Whether we're treating Other as being a bool because of the form of
11779   // expression despite it having another type (typically 'int' in C).
11780   bool OtherIsBooleanDespiteType =
11781       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11782   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11783     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11784 
11785   // Check if all values in the range of possible values of this expression
11786   // lead to the same comparison outcome.
11787   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11788                                         Value.isUnsigned());
11789   auto Cmp = OtherPromotedValueRange.compare(Value);
11790   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11791   if (!Result)
11792     return false;
11793 
11794   // Also consider the range determined by the type alone. This allows us to
11795   // classify the warning under the proper diagnostic group.
11796   bool TautologicalTypeCompare = false;
11797   {
11798     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11799                                          Value.isUnsigned());
11800     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11801     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11802                                                        RhsConstant)) {
11803       TautologicalTypeCompare = true;
11804       Cmp = TypeCmp;
11805       Result = TypeResult;
11806     }
11807   }
11808 
11809   // Don't warn if the non-constant operand actually always evaluates to the
11810   // same value.
11811   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11812     return false;
11813 
11814   // Suppress the diagnostic for an in-range comparison if the constant comes
11815   // from a macro or enumerator. We don't want to diagnose
11816   //
11817   //   some_long_value <= INT_MAX
11818   //
11819   // when sizeof(int) == sizeof(long).
11820   bool InRange = Cmp & PromotedRange::InRangeFlag;
11821   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11822     return false;
11823 
11824   // A comparison of an unsigned bit-field against 0 is really a type problem,
11825   // even though at the type level the bit-field might promote to 'signed int'.
11826   if (Other->refersToBitField() && InRange && Value == 0 &&
11827       Other->getType()->isUnsignedIntegerOrEnumerationType())
11828     TautologicalTypeCompare = true;
11829 
11830   // If this is a comparison to an enum constant, include that
11831   // constant in the diagnostic.
11832   const EnumConstantDecl *ED = nullptr;
11833   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11834     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11835 
11836   // Should be enough for uint128 (39 decimal digits)
11837   SmallString<64> PrettySourceValue;
11838   llvm::raw_svector_ostream OS(PrettySourceValue);
11839   if (ED) {
11840     OS << '\'' << *ED << "' (" << Value << ")";
11841   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11842                Constant->IgnoreParenImpCasts())) {
11843     OS << (BL->getValue() ? "YES" : "NO");
11844   } else {
11845     OS << Value;
11846   }
11847 
11848   if (!TautologicalTypeCompare) {
11849     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11850         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11851         << E->getOpcodeStr() << OS.str() << *Result
11852         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11853     return true;
11854   }
11855 
11856   if (IsObjCSignedCharBool) {
11857     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11858                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11859                               << OS.str() << *Result);
11860     return true;
11861   }
11862 
11863   // FIXME: We use a somewhat different formatting for the in-range cases and
11864   // cases involving boolean values for historical reasons. We should pick a
11865   // consistent way of presenting these diagnostics.
11866   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11867 
11868     S.DiagRuntimeBehavior(
11869         E->getOperatorLoc(), E,
11870         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11871                          : diag::warn_tautological_bool_compare)
11872             << OS.str() << classifyConstantValue(Constant) << OtherT
11873             << OtherIsBooleanDespiteType << *Result
11874             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11875   } else {
11876     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11877     unsigned Diag =
11878         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11879             ? (HasEnumType(OriginalOther)
11880                    ? diag::warn_unsigned_enum_always_true_comparison
11881                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11882                               : diag::warn_unsigned_always_true_comparison)
11883             : diag::warn_tautological_constant_compare;
11884 
11885     S.Diag(E->getOperatorLoc(), Diag)
11886         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11887         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11888   }
11889 
11890   return true;
11891 }
11892 
11893 /// Analyze the operands of the given comparison.  Implements the
11894 /// fallback case from AnalyzeComparison.
11895 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11896   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11897   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11898 }
11899 
11900 /// Implements -Wsign-compare.
11901 ///
11902 /// \param E the binary operator to check for warnings
11903 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11904   // The type the comparison is being performed in.
11905   QualType T = E->getLHS()->getType();
11906 
11907   // Only analyze comparison operators where both sides have been converted to
11908   // the same type.
11909   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11910     return AnalyzeImpConvsInComparison(S, E);
11911 
11912   // Don't analyze value-dependent comparisons directly.
11913   if (E->isValueDependent())
11914     return AnalyzeImpConvsInComparison(S, E);
11915 
11916   Expr *LHS = E->getLHS();
11917   Expr *RHS = E->getRHS();
11918 
11919   if (T->isIntegralType(S.Context)) {
11920     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11921     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11922 
11923     // We don't care about expressions whose result is a constant.
11924     if (RHSValue && LHSValue)
11925       return AnalyzeImpConvsInComparison(S, E);
11926 
11927     // We only care about expressions where just one side is literal
11928     if ((bool)RHSValue ^ (bool)LHSValue) {
11929       // Is the constant on the RHS or LHS?
11930       const bool RhsConstant = (bool)RHSValue;
11931       Expr *Const = RhsConstant ? RHS : LHS;
11932       Expr *Other = RhsConstant ? LHS : RHS;
11933       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11934 
11935       // Check whether an integer constant comparison results in a value
11936       // of 'true' or 'false'.
11937       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11938         return AnalyzeImpConvsInComparison(S, E);
11939     }
11940   }
11941 
11942   if (!T->hasUnsignedIntegerRepresentation()) {
11943     // We don't do anything special if this isn't an unsigned integral
11944     // comparison:  we're only interested in integral comparisons, and
11945     // signed comparisons only happen in cases we don't care to warn about.
11946     return AnalyzeImpConvsInComparison(S, E);
11947   }
11948 
11949   LHS = LHS->IgnoreParenImpCasts();
11950   RHS = RHS->IgnoreParenImpCasts();
11951 
11952   if (!S.getLangOpts().CPlusPlus) {
11953     // Avoid warning about comparison of integers with different signs when
11954     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11955     // the type of `E`.
11956     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11957       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11958     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11959       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11960   }
11961 
11962   // Check to see if one of the (unmodified) operands is of different
11963   // signedness.
11964   Expr *signedOperand, *unsignedOperand;
11965   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11966     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11967            "unsigned comparison between two signed integer expressions?");
11968     signedOperand = LHS;
11969     unsignedOperand = RHS;
11970   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11971     signedOperand = RHS;
11972     unsignedOperand = LHS;
11973   } else {
11974     return AnalyzeImpConvsInComparison(S, E);
11975   }
11976 
11977   // Otherwise, calculate the effective range of the signed operand.
11978   IntRange signedRange = GetExprRange(
11979       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11980 
11981   // Go ahead and analyze implicit conversions in the operands.  Note
11982   // that we skip the implicit conversions on both sides.
11983   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11984   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11985 
11986   // If the signed range is non-negative, -Wsign-compare won't fire.
11987   if (signedRange.NonNegative)
11988     return;
11989 
11990   // For (in)equality comparisons, if the unsigned operand is a
11991   // constant which cannot collide with a overflowed signed operand,
11992   // then reinterpreting the signed operand as unsigned will not
11993   // change the result of the comparison.
11994   if (E->isEqualityOp()) {
11995     unsigned comparisonWidth = S.Context.getIntWidth(T);
11996     IntRange unsignedRange =
11997         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11998                      /*Approximate*/ true);
11999 
12000     // We should never be unable to prove that the unsigned operand is
12001     // non-negative.
12002     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
12003 
12004     if (unsignedRange.Width < comparisonWidth)
12005       return;
12006   }
12007 
12008   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
12009                         S.PDiag(diag::warn_mixed_sign_comparison)
12010                             << LHS->getType() << RHS->getType()
12011                             << LHS->getSourceRange() << RHS->getSourceRange());
12012 }
12013 
12014 /// Analyzes an attempt to assign the given value to a bitfield.
12015 ///
12016 /// Returns true if there was something fishy about the attempt.
12017 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
12018                                       SourceLocation InitLoc) {
12019   assert(Bitfield->isBitField());
12020   if (Bitfield->isInvalidDecl())
12021     return false;
12022 
12023   // White-list bool bitfields.
12024   QualType BitfieldType = Bitfield->getType();
12025   if (BitfieldType->isBooleanType())
12026      return false;
12027 
12028   if (BitfieldType->isEnumeralType()) {
12029     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12030     // If the underlying enum type was not explicitly specified as an unsigned
12031     // type and the enum contain only positive values, MSVC++ will cause an
12032     // inconsistency by storing this as a signed type.
12033     if (S.getLangOpts().CPlusPlus11 &&
12034         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12035         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12036         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12037       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12038           << BitfieldEnumDecl;
12039     }
12040   }
12041 
12042   if (Bitfield->getType()->isBooleanType())
12043     return false;
12044 
12045   // Ignore value- or type-dependent expressions.
12046   if (Bitfield->getBitWidth()->isValueDependent() ||
12047       Bitfield->getBitWidth()->isTypeDependent() ||
12048       Init->isValueDependent() ||
12049       Init->isTypeDependent())
12050     return false;
12051 
12052   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12053   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12054 
12055   Expr::EvalResult Result;
12056   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12057                                    Expr::SE_AllowSideEffects)) {
12058     // The RHS is not constant.  If the RHS has an enum type, make sure the
12059     // bitfield is wide enough to hold all the values of the enum without
12060     // truncation.
12061     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12062       EnumDecl *ED = EnumTy->getDecl();
12063       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12064 
12065       // Enum types are implicitly signed on Windows, so check if there are any
12066       // negative enumerators to see if the enum was intended to be signed or
12067       // not.
12068       bool SignedEnum = ED->getNumNegativeBits() > 0;
12069 
12070       // Check for surprising sign changes when assigning enum values to a
12071       // bitfield of different signedness.  If the bitfield is signed and we
12072       // have exactly the right number of bits to store this unsigned enum,
12073       // suggest changing the enum to an unsigned type. This typically happens
12074       // on Windows where unfixed enums always use an underlying type of 'int'.
12075       unsigned DiagID = 0;
12076       if (SignedEnum && !SignedBitfield) {
12077         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12078       } else if (SignedBitfield && !SignedEnum &&
12079                  ED->getNumPositiveBits() == FieldWidth) {
12080         DiagID = diag::warn_signed_bitfield_enum_conversion;
12081       }
12082 
12083       if (DiagID) {
12084         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12085         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12086         SourceRange TypeRange =
12087             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12088         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12089             << SignedEnum << TypeRange;
12090       }
12091 
12092       // Compute the required bitwidth. If the enum has negative values, we need
12093       // one more bit than the normal number of positive bits to represent the
12094       // sign bit.
12095       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12096                                                   ED->getNumNegativeBits())
12097                                        : ED->getNumPositiveBits();
12098 
12099       // Check the bitwidth.
12100       if (BitsNeeded > FieldWidth) {
12101         Expr *WidthExpr = Bitfield->getBitWidth();
12102         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12103             << Bitfield << ED;
12104         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12105             << BitsNeeded << ED << WidthExpr->getSourceRange();
12106       }
12107     }
12108 
12109     return false;
12110   }
12111 
12112   llvm::APSInt Value = Result.Val.getInt();
12113 
12114   unsigned OriginalWidth = Value.getBitWidth();
12115 
12116   if (!Value.isSigned() || Value.isNegative())
12117     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12118       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12119         OriginalWidth = Value.getMinSignedBits();
12120 
12121   if (OriginalWidth <= FieldWidth)
12122     return false;
12123 
12124   // Compute the value which the bitfield will contain.
12125   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12126   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12127 
12128   // Check whether the stored value is equal to the original value.
12129   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12130   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12131     return false;
12132 
12133   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12134   // therefore don't strictly fit into a signed bitfield of width 1.
12135   if (FieldWidth == 1 && Value == 1)
12136     return false;
12137 
12138   std::string PrettyValue = toString(Value, 10);
12139   std::string PrettyTrunc = toString(TruncatedValue, 10);
12140 
12141   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12142     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12143     << Init->getSourceRange();
12144 
12145   return true;
12146 }
12147 
12148 /// Analyze the given simple or compound assignment for warning-worthy
12149 /// operations.
12150 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12151   // Just recurse on the LHS.
12152   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12153 
12154   // We want to recurse on the RHS as normal unless we're assigning to
12155   // a bitfield.
12156   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12157     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12158                                   E->getOperatorLoc())) {
12159       // Recurse, ignoring any implicit conversions on the RHS.
12160       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12161                                         E->getOperatorLoc());
12162     }
12163   }
12164 
12165   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12166 
12167   // Diagnose implicitly sequentially-consistent atomic assignment.
12168   if (E->getLHS()->getType()->isAtomicType())
12169     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12170 }
12171 
12172 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12173 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12174                             SourceLocation CContext, unsigned diag,
12175                             bool pruneControlFlow = false) {
12176   if (pruneControlFlow) {
12177     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12178                           S.PDiag(diag)
12179                               << SourceType << T << E->getSourceRange()
12180                               << SourceRange(CContext));
12181     return;
12182   }
12183   S.Diag(E->getExprLoc(), diag)
12184     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12185 }
12186 
12187 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12188 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12189                             SourceLocation CContext,
12190                             unsigned diag, bool pruneControlFlow = false) {
12191   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12192 }
12193 
12194 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12195   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12196       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12197 }
12198 
12199 static void adornObjCBoolConversionDiagWithTernaryFixit(
12200     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12201   Expr *Ignored = SourceExpr->IgnoreImplicit();
12202   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12203     Ignored = OVE->getSourceExpr();
12204   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12205                      isa<BinaryOperator>(Ignored) ||
12206                      isa<CXXOperatorCallExpr>(Ignored);
12207   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12208   if (NeedsParens)
12209     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12210             << FixItHint::CreateInsertion(EndLoc, ")");
12211   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12212 }
12213 
12214 /// Diagnose an implicit cast from a floating point value to an integer value.
12215 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12216                                     SourceLocation CContext) {
12217   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12218   const bool PruneWarnings = S.inTemplateInstantiation();
12219 
12220   Expr *InnerE = E->IgnoreParenImpCasts();
12221   // We also want to warn on, e.g., "int i = -1.234"
12222   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12223     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12224       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12225 
12226   const bool IsLiteral =
12227       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12228 
12229   llvm::APFloat Value(0.0);
12230   bool IsConstant =
12231     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12232   if (!IsConstant) {
12233     if (isObjCSignedCharBool(S, T)) {
12234       return adornObjCBoolConversionDiagWithTernaryFixit(
12235           S, E,
12236           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12237               << E->getType());
12238     }
12239 
12240     return DiagnoseImpCast(S, E, T, CContext,
12241                            diag::warn_impcast_float_integer, PruneWarnings);
12242   }
12243 
12244   bool isExact = false;
12245 
12246   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12247                             T->hasUnsignedIntegerRepresentation());
12248   llvm::APFloat::opStatus Result = Value.convertToInteger(
12249       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12250 
12251   // FIXME: Force the precision of the source value down so we don't print
12252   // digits which are usually useless (we don't really care here if we
12253   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12254   // would automatically print the shortest representation, but it's a bit
12255   // tricky to implement.
12256   SmallString<16> PrettySourceValue;
12257   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12258   precision = (precision * 59 + 195) / 196;
12259   Value.toString(PrettySourceValue, precision);
12260 
12261   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12262     return adornObjCBoolConversionDiagWithTernaryFixit(
12263         S, E,
12264         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12265             << PrettySourceValue);
12266   }
12267 
12268   if (Result == llvm::APFloat::opOK && isExact) {
12269     if (IsLiteral) return;
12270     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12271                            PruneWarnings);
12272   }
12273 
12274   // Conversion of a floating-point value to a non-bool integer where the
12275   // integral part cannot be represented by the integer type is undefined.
12276   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12277     return DiagnoseImpCast(
12278         S, E, T, CContext,
12279         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12280                   : diag::warn_impcast_float_to_integer_out_of_range,
12281         PruneWarnings);
12282 
12283   unsigned DiagID = 0;
12284   if (IsLiteral) {
12285     // Warn on floating point literal to integer.
12286     DiagID = diag::warn_impcast_literal_float_to_integer;
12287   } else if (IntegerValue == 0) {
12288     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12289       return DiagnoseImpCast(S, E, T, CContext,
12290                              diag::warn_impcast_float_integer, PruneWarnings);
12291     }
12292     // Warn on non-zero to zero conversion.
12293     DiagID = diag::warn_impcast_float_to_integer_zero;
12294   } else {
12295     if (IntegerValue.isUnsigned()) {
12296       if (!IntegerValue.isMaxValue()) {
12297         return DiagnoseImpCast(S, E, T, CContext,
12298                                diag::warn_impcast_float_integer, PruneWarnings);
12299       }
12300     } else {  // IntegerValue.isSigned()
12301       if (!IntegerValue.isMaxSignedValue() &&
12302           !IntegerValue.isMinSignedValue()) {
12303         return DiagnoseImpCast(S, E, T, CContext,
12304                                diag::warn_impcast_float_integer, PruneWarnings);
12305       }
12306     }
12307     // Warn on evaluatable floating point expression to integer conversion.
12308     DiagID = diag::warn_impcast_float_to_integer;
12309   }
12310 
12311   SmallString<16> PrettyTargetValue;
12312   if (IsBool)
12313     PrettyTargetValue = Value.isZero() ? "false" : "true";
12314   else
12315     IntegerValue.toString(PrettyTargetValue);
12316 
12317   if (PruneWarnings) {
12318     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12319                           S.PDiag(DiagID)
12320                               << E->getType() << T.getUnqualifiedType()
12321                               << PrettySourceValue << PrettyTargetValue
12322                               << E->getSourceRange() << SourceRange(CContext));
12323   } else {
12324     S.Diag(E->getExprLoc(), DiagID)
12325         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12326         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12327   }
12328 }
12329 
12330 /// Analyze the given compound assignment for the possible losing of
12331 /// floating-point precision.
12332 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12333   assert(isa<CompoundAssignOperator>(E) &&
12334          "Must be compound assignment operation");
12335   // Recurse on the LHS and RHS in here
12336   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12337   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12338 
12339   if (E->getLHS()->getType()->isAtomicType())
12340     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12341 
12342   // Now check the outermost expression
12343   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12344   const auto *RBT = cast<CompoundAssignOperator>(E)
12345                         ->getComputationResultType()
12346                         ->getAs<BuiltinType>();
12347 
12348   // The below checks assume source is floating point.
12349   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12350 
12351   // If source is floating point but target is an integer.
12352   if (ResultBT->isInteger())
12353     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12354                            E->getExprLoc(), diag::warn_impcast_float_integer);
12355 
12356   if (!ResultBT->isFloatingPoint())
12357     return;
12358 
12359   // If both source and target are floating points, warn about losing precision.
12360   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12361       QualType(ResultBT, 0), QualType(RBT, 0));
12362   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12363     // warn about dropping FP rank.
12364     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12365                     diag::warn_impcast_float_result_precision);
12366 }
12367 
12368 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12369                                       IntRange Range) {
12370   if (!Range.Width) return "0";
12371 
12372   llvm::APSInt ValueInRange = Value;
12373   ValueInRange.setIsSigned(!Range.NonNegative);
12374   ValueInRange = ValueInRange.trunc(Range.Width);
12375   return toString(ValueInRange, 10);
12376 }
12377 
12378 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12379   if (!isa<ImplicitCastExpr>(Ex))
12380     return false;
12381 
12382   Expr *InnerE = Ex->IgnoreParenImpCasts();
12383   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12384   const Type *Source =
12385     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12386   if (Target->isDependentType())
12387     return false;
12388 
12389   const BuiltinType *FloatCandidateBT =
12390     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12391   const Type *BoolCandidateType = ToBool ? Target : Source;
12392 
12393   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12394           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12395 }
12396 
12397 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12398                                              SourceLocation CC) {
12399   unsigned NumArgs = TheCall->getNumArgs();
12400   for (unsigned i = 0; i < NumArgs; ++i) {
12401     Expr *CurrA = TheCall->getArg(i);
12402     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12403       continue;
12404 
12405     bool IsSwapped = ((i > 0) &&
12406         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12407     IsSwapped |= ((i < (NumArgs - 1)) &&
12408         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12409     if (IsSwapped) {
12410       // Warn on this floating-point to bool conversion.
12411       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12412                       CurrA->getType(), CC,
12413                       diag::warn_impcast_floating_point_to_bool);
12414     }
12415   }
12416 }
12417 
12418 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12419                                    SourceLocation CC) {
12420   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12421                         E->getExprLoc()))
12422     return;
12423 
12424   // Don't warn on functions which have return type nullptr_t.
12425   if (isa<CallExpr>(E))
12426     return;
12427 
12428   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12429   const Expr::NullPointerConstantKind NullKind =
12430       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12431   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12432     return;
12433 
12434   // Return if target type is a safe conversion.
12435   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12436       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12437     return;
12438 
12439   SourceLocation Loc = E->getSourceRange().getBegin();
12440 
12441   // Venture through the macro stacks to get to the source of macro arguments.
12442   // The new location is a better location than the complete location that was
12443   // passed in.
12444   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12445   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12446 
12447   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12448   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12449     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12450         Loc, S.SourceMgr, S.getLangOpts());
12451     if (MacroName == "NULL")
12452       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12453   }
12454 
12455   // Only warn if the null and context location are in the same macro expansion.
12456   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12457     return;
12458 
12459   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12460       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12461       << FixItHint::CreateReplacement(Loc,
12462                                       S.getFixItZeroLiteralForType(T, Loc));
12463 }
12464 
12465 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12466                                   ObjCArrayLiteral *ArrayLiteral);
12467 
12468 static void
12469 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12470                            ObjCDictionaryLiteral *DictionaryLiteral);
12471 
12472 /// Check a single element within a collection literal against the
12473 /// target element type.
12474 static void checkObjCCollectionLiteralElement(Sema &S,
12475                                               QualType TargetElementType,
12476                                               Expr *Element,
12477                                               unsigned ElementKind) {
12478   // Skip a bitcast to 'id' or qualified 'id'.
12479   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12480     if (ICE->getCastKind() == CK_BitCast &&
12481         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12482       Element = ICE->getSubExpr();
12483   }
12484 
12485   QualType ElementType = Element->getType();
12486   ExprResult ElementResult(Element);
12487   if (ElementType->getAs<ObjCObjectPointerType>() &&
12488       S.CheckSingleAssignmentConstraints(TargetElementType,
12489                                          ElementResult,
12490                                          false, false)
12491         != Sema::Compatible) {
12492     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12493         << ElementType << ElementKind << TargetElementType
12494         << Element->getSourceRange();
12495   }
12496 
12497   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12498     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12499   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12500     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12501 }
12502 
12503 /// Check an Objective-C array literal being converted to the given
12504 /// target type.
12505 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12506                                   ObjCArrayLiteral *ArrayLiteral) {
12507   if (!S.NSArrayDecl)
12508     return;
12509 
12510   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12511   if (!TargetObjCPtr)
12512     return;
12513 
12514   if (TargetObjCPtr->isUnspecialized() ||
12515       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12516         != S.NSArrayDecl->getCanonicalDecl())
12517     return;
12518 
12519   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12520   if (TypeArgs.size() != 1)
12521     return;
12522 
12523   QualType TargetElementType = TypeArgs[0];
12524   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12525     checkObjCCollectionLiteralElement(S, TargetElementType,
12526                                       ArrayLiteral->getElement(I),
12527                                       0);
12528   }
12529 }
12530 
12531 /// Check an Objective-C dictionary literal being converted to the given
12532 /// target type.
12533 static void
12534 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12535                            ObjCDictionaryLiteral *DictionaryLiteral) {
12536   if (!S.NSDictionaryDecl)
12537     return;
12538 
12539   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12540   if (!TargetObjCPtr)
12541     return;
12542 
12543   if (TargetObjCPtr->isUnspecialized() ||
12544       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12545         != S.NSDictionaryDecl->getCanonicalDecl())
12546     return;
12547 
12548   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12549   if (TypeArgs.size() != 2)
12550     return;
12551 
12552   QualType TargetKeyType = TypeArgs[0];
12553   QualType TargetObjectType = TypeArgs[1];
12554   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12555     auto Element = DictionaryLiteral->getKeyValueElement(I);
12556     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12557     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12558   }
12559 }
12560 
12561 // Helper function to filter out cases for constant width constant conversion.
12562 // Don't warn on char array initialization or for non-decimal values.
12563 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12564                                           SourceLocation CC) {
12565   // If initializing from a constant, and the constant starts with '0',
12566   // then it is a binary, octal, or hexadecimal.  Allow these constants
12567   // to fill all the bits, even if there is a sign change.
12568   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12569     const char FirstLiteralCharacter =
12570         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12571     if (FirstLiteralCharacter == '0')
12572       return false;
12573   }
12574 
12575   // If the CC location points to a '{', and the type is char, then assume
12576   // assume it is an array initialization.
12577   if (CC.isValid() && T->isCharType()) {
12578     const char FirstContextCharacter =
12579         S.getSourceManager().getCharacterData(CC)[0];
12580     if (FirstContextCharacter == '{')
12581       return false;
12582   }
12583 
12584   return true;
12585 }
12586 
12587 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12588   const auto *IL = dyn_cast<IntegerLiteral>(E);
12589   if (!IL) {
12590     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12591       if (UO->getOpcode() == UO_Minus)
12592         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12593     }
12594   }
12595 
12596   return IL;
12597 }
12598 
12599 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12600   E = E->IgnoreParenImpCasts();
12601   SourceLocation ExprLoc = E->getExprLoc();
12602 
12603   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12604     BinaryOperator::Opcode Opc = BO->getOpcode();
12605     Expr::EvalResult Result;
12606     // Do not diagnose unsigned shifts.
12607     if (Opc == BO_Shl) {
12608       const auto *LHS = getIntegerLiteral(BO->getLHS());
12609       const auto *RHS = getIntegerLiteral(BO->getRHS());
12610       if (LHS && LHS->getValue() == 0)
12611         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12612       else if (!E->isValueDependent() && LHS && RHS &&
12613                RHS->getValue().isNonNegative() &&
12614                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12615         S.Diag(ExprLoc, diag::warn_left_shift_always)
12616             << (Result.Val.getInt() != 0);
12617       else if (E->getType()->isSignedIntegerType())
12618         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12619     }
12620   }
12621 
12622   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12623     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12624     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12625     if (!LHS || !RHS)
12626       return;
12627     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12628         (RHS->getValue() == 0 || RHS->getValue() == 1))
12629       // Do not diagnose common idioms.
12630       return;
12631     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12632       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12633   }
12634 }
12635 
12636 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12637                                     SourceLocation CC,
12638                                     bool *ICContext = nullptr,
12639                                     bool IsListInit = false) {
12640   if (E->isTypeDependent() || E->isValueDependent()) return;
12641 
12642   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12643   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12644   if (Source == Target) return;
12645   if (Target->isDependentType()) return;
12646 
12647   // If the conversion context location is invalid don't complain. We also
12648   // don't want to emit a warning if the issue occurs from the expansion of
12649   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12650   // delay this check as long as possible. Once we detect we are in that
12651   // scenario, we just return.
12652   if (CC.isInvalid())
12653     return;
12654 
12655   if (Source->isAtomicType())
12656     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12657 
12658   // Diagnose implicit casts to bool.
12659   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12660     if (isa<StringLiteral>(E))
12661       // Warn on string literal to bool.  Checks for string literals in logical
12662       // and expressions, for instance, assert(0 && "error here"), are
12663       // prevented by a check in AnalyzeImplicitConversions().
12664       return DiagnoseImpCast(S, E, T, CC,
12665                              diag::warn_impcast_string_literal_to_bool);
12666     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12667         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12668       // This covers the literal expressions that evaluate to Objective-C
12669       // objects.
12670       return DiagnoseImpCast(S, E, T, CC,
12671                              diag::warn_impcast_objective_c_literal_to_bool);
12672     }
12673     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12674       // Warn on pointer to bool conversion that is always true.
12675       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12676                                      SourceRange(CC));
12677     }
12678   }
12679 
12680   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12681   // is a typedef for signed char (macOS), then that constant value has to be 1
12682   // or 0.
12683   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12684     Expr::EvalResult Result;
12685     if (E->EvaluateAsInt(Result, S.getASTContext(),
12686                          Expr::SE_AllowSideEffects)) {
12687       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12688         adornObjCBoolConversionDiagWithTernaryFixit(
12689             S, E,
12690             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12691                 << toString(Result.Val.getInt(), 10));
12692       }
12693       return;
12694     }
12695   }
12696 
12697   // Check implicit casts from Objective-C collection literals to specialized
12698   // collection types, e.g., NSArray<NSString *> *.
12699   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12700     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12701   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12702     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12703 
12704   // Strip vector types.
12705   if (isa<VectorType>(Source)) {
12706     if (Target->isVLSTBuiltinType() &&
12707         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12708                                          QualType(Source, 0)) ||
12709          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12710                                             QualType(Source, 0))))
12711       return;
12712 
12713     if (!isa<VectorType>(Target)) {
12714       if (S.SourceMgr.isInSystemMacro(CC))
12715         return;
12716       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12717     }
12718 
12719     // If the vector cast is cast between two vectors of the same size, it is
12720     // a bitcast, not a conversion.
12721     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12722       return;
12723 
12724     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12725     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12726   }
12727   if (auto VecTy = dyn_cast<VectorType>(Target))
12728     Target = VecTy->getElementType().getTypePtr();
12729 
12730   // Strip complex types.
12731   if (isa<ComplexType>(Source)) {
12732     if (!isa<ComplexType>(Target)) {
12733       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12734         return;
12735 
12736       return DiagnoseImpCast(S, E, T, CC,
12737                              S.getLangOpts().CPlusPlus
12738                                  ? diag::err_impcast_complex_scalar
12739                                  : diag::warn_impcast_complex_scalar);
12740     }
12741 
12742     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12743     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12744   }
12745 
12746   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12747   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12748 
12749   // If the source is floating point...
12750   if (SourceBT && SourceBT->isFloatingPoint()) {
12751     // ...and the target is floating point...
12752     if (TargetBT && TargetBT->isFloatingPoint()) {
12753       // ...then warn if we're dropping FP rank.
12754 
12755       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12756           QualType(SourceBT, 0), QualType(TargetBT, 0));
12757       if (Order > 0) {
12758         // Don't warn about float constants that are precisely
12759         // representable in the target type.
12760         Expr::EvalResult result;
12761         if (E->EvaluateAsRValue(result, S.Context)) {
12762           // Value might be a float, a float vector, or a float complex.
12763           if (IsSameFloatAfterCast(result.Val,
12764                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12765                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12766             return;
12767         }
12768 
12769         if (S.SourceMgr.isInSystemMacro(CC))
12770           return;
12771 
12772         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12773       }
12774       // ... or possibly if we're increasing rank, too
12775       else if (Order < 0) {
12776         if (S.SourceMgr.isInSystemMacro(CC))
12777           return;
12778 
12779         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12780       }
12781       return;
12782     }
12783 
12784     // If the target is integral, always warn.
12785     if (TargetBT && TargetBT->isInteger()) {
12786       if (S.SourceMgr.isInSystemMacro(CC))
12787         return;
12788 
12789       DiagnoseFloatingImpCast(S, E, T, CC);
12790     }
12791 
12792     // Detect the case where a call result is converted from floating-point to
12793     // to bool, and the final argument to the call is converted from bool, to
12794     // discover this typo:
12795     //
12796     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12797     //
12798     // FIXME: This is an incredibly special case; is there some more general
12799     // way to detect this class of misplaced-parentheses bug?
12800     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12801       // Check last argument of function call to see if it is an
12802       // implicit cast from a type matching the type the result
12803       // is being cast to.
12804       CallExpr *CEx = cast<CallExpr>(E);
12805       if (unsigned NumArgs = CEx->getNumArgs()) {
12806         Expr *LastA = CEx->getArg(NumArgs - 1);
12807         Expr *InnerE = LastA->IgnoreParenImpCasts();
12808         if (isa<ImplicitCastExpr>(LastA) &&
12809             InnerE->getType()->isBooleanType()) {
12810           // Warn on this floating-point to bool conversion
12811           DiagnoseImpCast(S, E, T, CC,
12812                           diag::warn_impcast_floating_point_to_bool);
12813         }
12814       }
12815     }
12816     return;
12817   }
12818 
12819   // Valid casts involving fixed point types should be accounted for here.
12820   if (Source->isFixedPointType()) {
12821     if (Target->isUnsaturatedFixedPointType()) {
12822       Expr::EvalResult Result;
12823       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12824                                   S.isConstantEvaluated())) {
12825         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12826         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12827         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12828         if (Value > MaxVal || Value < MinVal) {
12829           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12830                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12831                                     << Value.toString() << T
12832                                     << E->getSourceRange()
12833                                     << clang::SourceRange(CC));
12834           return;
12835         }
12836       }
12837     } else if (Target->isIntegerType()) {
12838       Expr::EvalResult Result;
12839       if (!S.isConstantEvaluated() &&
12840           E->EvaluateAsFixedPoint(Result, S.Context,
12841                                   Expr::SE_AllowSideEffects)) {
12842         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12843 
12844         bool Overflowed;
12845         llvm::APSInt IntResult = FXResult.convertToInt(
12846             S.Context.getIntWidth(T),
12847             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12848 
12849         if (Overflowed) {
12850           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12851                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12852                                     << FXResult.toString() << T
12853                                     << E->getSourceRange()
12854                                     << clang::SourceRange(CC));
12855           return;
12856         }
12857       }
12858     }
12859   } else if (Target->isUnsaturatedFixedPointType()) {
12860     if (Source->isIntegerType()) {
12861       Expr::EvalResult Result;
12862       if (!S.isConstantEvaluated() &&
12863           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12864         llvm::APSInt Value = Result.Val.getInt();
12865 
12866         bool Overflowed;
12867         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12868             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12869 
12870         if (Overflowed) {
12871           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12872                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12873                                     << toString(Value, /*Radix=*/10) << T
12874                                     << E->getSourceRange()
12875                                     << clang::SourceRange(CC));
12876           return;
12877         }
12878       }
12879     }
12880   }
12881 
12882   // If we are casting an integer type to a floating point type without
12883   // initialization-list syntax, we might lose accuracy if the floating
12884   // point type has a narrower significand than the integer type.
12885   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12886       TargetBT->isFloatingType() && !IsListInit) {
12887     // Determine the number of precision bits in the source integer type.
12888     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12889                                         /*Approximate*/ true);
12890     unsigned int SourcePrecision = SourceRange.Width;
12891 
12892     // Determine the number of precision bits in the
12893     // target floating point type.
12894     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12895         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12896 
12897     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12898         SourcePrecision > TargetPrecision) {
12899 
12900       if (Optional<llvm::APSInt> SourceInt =
12901               E->getIntegerConstantExpr(S.Context)) {
12902         // If the source integer is a constant, convert it to the target
12903         // floating point type. Issue a warning if the value changes
12904         // during the whole conversion.
12905         llvm::APFloat TargetFloatValue(
12906             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12907         llvm::APFloat::opStatus ConversionStatus =
12908             TargetFloatValue.convertFromAPInt(
12909                 *SourceInt, SourceBT->isSignedInteger(),
12910                 llvm::APFloat::rmNearestTiesToEven);
12911 
12912         if (ConversionStatus != llvm::APFloat::opOK) {
12913           SmallString<32> PrettySourceValue;
12914           SourceInt->toString(PrettySourceValue, 10);
12915           SmallString<32> PrettyTargetValue;
12916           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12917 
12918           S.DiagRuntimeBehavior(
12919               E->getExprLoc(), E,
12920               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12921                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12922                   << E->getSourceRange() << clang::SourceRange(CC));
12923         }
12924       } else {
12925         // Otherwise, the implicit conversion may lose precision.
12926         DiagnoseImpCast(S, E, T, CC,
12927                         diag::warn_impcast_integer_float_precision);
12928       }
12929     }
12930   }
12931 
12932   DiagnoseNullConversion(S, E, T, CC);
12933 
12934   S.DiscardMisalignedMemberAddress(Target, E);
12935 
12936   if (Target->isBooleanType())
12937     DiagnoseIntInBoolContext(S, E);
12938 
12939   if (!Source->isIntegerType() || !Target->isIntegerType())
12940     return;
12941 
12942   // TODO: remove this early return once the false positives for constant->bool
12943   // in templates, macros, etc, are reduced or removed.
12944   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12945     return;
12946 
12947   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12948       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12949     return adornObjCBoolConversionDiagWithTernaryFixit(
12950         S, E,
12951         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12952             << E->getType());
12953   }
12954 
12955   IntRange SourceTypeRange =
12956       IntRange::forTargetOfCanonicalType(S.Context, Source);
12957   IntRange LikelySourceRange =
12958       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12959   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12960 
12961   if (LikelySourceRange.Width > TargetRange.Width) {
12962     // If the source is a constant, use a default-on diagnostic.
12963     // TODO: this should happen for bitfield stores, too.
12964     Expr::EvalResult Result;
12965     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12966                          S.isConstantEvaluated())) {
12967       llvm::APSInt Value(32);
12968       Value = Result.Val.getInt();
12969 
12970       if (S.SourceMgr.isInSystemMacro(CC))
12971         return;
12972 
12973       std::string PrettySourceValue = toString(Value, 10);
12974       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12975 
12976       S.DiagRuntimeBehavior(
12977           E->getExprLoc(), E,
12978           S.PDiag(diag::warn_impcast_integer_precision_constant)
12979               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12980               << E->getSourceRange() << SourceRange(CC));
12981       return;
12982     }
12983 
12984     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12985     if (S.SourceMgr.isInSystemMacro(CC))
12986       return;
12987 
12988     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12989       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12990                              /* pruneControlFlow */ true);
12991     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12992   }
12993 
12994   if (TargetRange.Width > SourceTypeRange.Width) {
12995     if (auto *UO = dyn_cast<UnaryOperator>(E))
12996       if (UO->getOpcode() == UO_Minus)
12997         if (Source->isUnsignedIntegerType()) {
12998           if (Target->isUnsignedIntegerType())
12999             return DiagnoseImpCast(S, E, T, CC,
13000                                    diag::warn_impcast_high_order_zero_bits);
13001           if (Target->isSignedIntegerType())
13002             return DiagnoseImpCast(S, E, T, CC,
13003                                    diag::warn_impcast_nonnegative_result);
13004         }
13005   }
13006 
13007   if (TargetRange.Width == LikelySourceRange.Width &&
13008       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13009       Source->isSignedIntegerType()) {
13010     // Warn when doing a signed to signed conversion, warn if the positive
13011     // source value is exactly the width of the target type, which will
13012     // cause a negative value to be stored.
13013 
13014     Expr::EvalResult Result;
13015     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
13016         !S.SourceMgr.isInSystemMacro(CC)) {
13017       llvm::APSInt Value = Result.Val.getInt();
13018       if (isSameWidthConstantConversion(S, E, T, CC)) {
13019         std::string PrettySourceValue = toString(Value, 10);
13020         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
13021 
13022         S.DiagRuntimeBehavior(
13023             E->getExprLoc(), E,
13024             S.PDiag(diag::warn_impcast_integer_precision_constant)
13025                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
13026                 << E->getSourceRange() << SourceRange(CC));
13027         return;
13028       }
13029     }
13030 
13031     // Fall through for non-constants to give a sign conversion warning.
13032   }
13033 
13034   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13035       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13036        LikelySourceRange.Width == TargetRange.Width)) {
13037     if (S.SourceMgr.isInSystemMacro(CC))
13038       return;
13039 
13040     unsigned DiagID = diag::warn_impcast_integer_sign;
13041 
13042     // Traditionally, gcc has warned about this under -Wsign-compare.
13043     // We also want to warn about it in -Wconversion.
13044     // So if -Wconversion is off, use a completely identical diagnostic
13045     // in the sign-compare group.
13046     // The conditional-checking code will
13047     if (ICContext) {
13048       DiagID = diag::warn_impcast_integer_sign_conditional;
13049       *ICContext = true;
13050     }
13051 
13052     return DiagnoseImpCast(S, E, T, CC, DiagID);
13053   }
13054 
13055   // Diagnose conversions between different enumeration types.
13056   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13057   // type, to give us better diagnostics.
13058   QualType SourceType = E->getType();
13059   if (!S.getLangOpts().CPlusPlus) {
13060     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13061       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13062         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13063         SourceType = S.Context.getTypeDeclType(Enum);
13064         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13065       }
13066   }
13067 
13068   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13069     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13070       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13071           TargetEnum->getDecl()->hasNameForLinkage() &&
13072           SourceEnum != TargetEnum) {
13073         if (S.SourceMgr.isInSystemMacro(CC))
13074           return;
13075 
13076         return DiagnoseImpCast(S, E, SourceType, T, CC,
13077                                diag::warn_impcast_different_enum_types);
13078       }
13079 }
13080 
13081 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13082                                      SourceLocation CC, QualType T);
13083 
13084 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13085                                     SourceLocation CC, bool &ICContext) {
13086   E = E->IgnoreParenImpCasts();
13087 
13088   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13089     return CheckConditionalOperator(S, CO, CC, T);
13090 
13091   AnalyzeImplicitConversions(S, E, CC);
13092   if (E->getType() != T)
13093     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13094 }
13095 
13096 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13097                                      SourceLocation CC, QualType T) {
13098   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13099 
13100   Expr *TrueExpr = E->getTrueExpr();
13101   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13102     TrueExpr = BCO->getCommon();
13103 
13104   bool Suspicious = false;
13105   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13106   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13107 
13108   if (T->isBooleanType())
13109     DiagnoseIntInBoolContext(S, E);
13110 
13111   // If -Wconversion would have warned about either of the candidates
13112   // for a signedness conversion to the context type...
13113   if (!Suspicious) return;
13114 
13115   // ...but it's currently ignored...
13116   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13117     return;
13118 
13119   // ...then check whether it would have warned about either of the
13120   // candidates for a signedness conversion to the condition type.
13121   if (E->getType() == T) return;
13122 
13123   Suspicious = false;
13124   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13125                           E->getType(), CC, &Suspicious);
13126   if (!Suspicious)
13127     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13128                             E->getType(), CC, &Suspicious);
13129 }
13130 
13131 /// Check conversion of given expression to boolean.
13132 /// Input argument E is a logical expression.
13133 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13134   if (S.getLangOpts().Bool)
13135     return;
13136   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13137     return;
13138   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13139 }
13140 
13141 namespace {
13142 struct AnalyzeImplicitConversionsWorkItem {
13143   Expr *E;
13144   SourceLocation CC;
13145   bool IsListInit;
13146 };
13147 }
13148 
13149 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13150 /// that should be visited are added to WorkList.
13151 static void AnalyzeImplicitConversions(
13152     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13153     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13154   Expr *OrigE = Item.E;
13155   SourceLocation CC = Item.CC;
13156 
13157   QualType T = OrigE->getType();
13158   Expr *E = OrigE->IgnoreParenImpCasts();
13159 
13160   // Propagate whether we are in a C++ list initialization expression.
13161   // If so, we do not issue warnings for implicit int-float conversion
13162   // precision loss, because C++11 narrowing already handles it.
13163   bool IsListInit = Item.IsListInit ||
13164                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13165 
13166   if (E->isTypeDependent() || E->isValueDependent())
13167     return;
13168 
13169   Expr *SourceExpr = E;
13170   // Examine, but don't traverse into the source expression of an
13171   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13172   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13173   // evaluate it in the context of checking the specific conversion to T though.
13174   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13175     if (auto *Src = OVE->getSourceExpr())
13176       SourceExpr = Src;
13177 
13178   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13179     if (UO->getOpcode() == UO_Not &&
13180         UO->getSubExpr()->isKnownToHaveBooleanValue())
13181       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13182           << OrigE->getSourceRange() << T->isBooleanType()
13183           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13184 
13185   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13186     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13187         BO->getLHS()->isKnownToHaveBooleanValue() &&
13188         BO->getRHS()->isKnownToHaveBooleanValue() &&
13189         BO->getLHS()->HasSideEffects(S.Context) &&
13190         BO->getRHS()->HasSideEffects(S.Context)) {
13191       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13192           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13193           << FixItHint::CreateReplacement(
13194                  BO->getOperatorLoc(),
13195                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13196       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13197     }
13198 
13199   // For conditional operators, we analyze the arguments as if they
13200   // were being fed directly into the output.
13201   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13202     CheckConditionalOperator(S, CO, CC, T);
13203     return;
13204   }
13205 
13206   // Check implicit argument conversions for function calls.
13207   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13208     CheckImplicitArgumentConversions(S, Call, CC);
13209 
13210   // Go ahead and check any implicit conversions we might have skipped.
13211   // The non-canonical typecheck is just an optimization;
13212   // CheckImplicitConversion will filter out dead implicit conversions.
13213   if (SourceExpr->getType() != T)
13214     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13215 
13216   // Now continue drilling into this expression.
13217 
13218   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13219     // The bound subexpressions in a PseudoObjectExpr are not reachable
13220     // as transitive children.
13221     // FIXME: Use a more uniform representation for this.
13222     for (auto *SE : POE->semantics())
13223       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13224         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13225   }
13226 
13227   // Skip past explicit casts.
13228   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13229     E = CE->getSubExpr()->IgnoreParenImpCasts();
13230     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13231       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13232     WorkList.push_back({E, CC, IsListInit});
13233     return;
13234   }
13235 
13236   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13237     // Do a somewhat different check with comparison operators.
13238     if (BO->isComparisonOp())
13239       return AnalyzeComparison(S, BO);
13240 
13241     // And with simple assignments.
13242     if (BO->getOpcode() == BO_Assign)
13243       return AnalyzeAssignment(S, BO);
13244     // And with compound assignments.
13245     if (BO->isAssignmentOp())
13246       return AnalyzeCompoundAssignment(S, BO);
13247   }
13248 
13249   // These break the otherwise-useful invariant below.  Fortunately,
13250   // we don't really need to recurse into them, because any internal
13251   // expressions should have been analyzed already when they were
13252   // built into statements.
13253   if (isa<StmtExpr>(E)) return;
13254 
13255   // Don't descend into unevaluated contexts.
13256   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13257 
13258   // Now just recurse over the expression's children.
13259   CC = E->getExprLoc();
13260   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13261   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13262   for (Stmt *SubStmt : E->children()) {
13263     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13264     if (!ChildExpr)
13265       continue;
13266 
13267     if (IsLogicalAndOperator &&
13268         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13269       // Ignore checking string literals that are in logical and operators.
13270       // This is a common pattern for asserts.
13271       continue;
13272     WorkList.push_back({ChildExpr, CC, IsListInit});
13273   }
13274 
13275   if (BO && BO->isLogicalOp()) {
13276     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13277     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13278       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13279 
13280     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13281     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13282       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13283   }
13284 
13285   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13286     if (U->getOpcode() == UO_LNot) {
13287       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13288     } else if (U->getOpcode() != UO_AddrOf) {
13289       if (U->getSubExpr()->getType()->isAtomicType())
13290         S.Diag(U->getSubExpr()->getBeginLoc(),
13291                diag::warn_atomic_implicit_seq_cst);
13292     }
13293   }
13294 }
13295 
13296 /// AnalyzeImplicitConversions - Find and report any interesting
13297 /// implicit conversions in the given expression.  There are a couple
13298 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13299 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13300                                        bool IsListInit/*= false*/) {
13301   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13302   WorkList.push_back({OrigE, CC, IsListInit});
13303   while (!WorkList.empty())
13304     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13305 }
13306 
13307 /// Diagnose integer type and any valid implicit conversion to it.
13308 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13309   // Taking into account implicit conversions,
13310   // allow any integer.
13311   if (!E->getType()->isIntegerType()) {
13312     S.Diag(E->getBeginLoc(),
13313            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13314     return true;
13315   }
13316   // Potentially emit standard warnings for implicit conversions if enabled
13317   // using -Wconversion.
13318   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13319   return false;
13320 }
13321 
13322 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13323 // Returns true when emitting a warning about taking the address of a reference.
13324 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13325                               const PartialDiagnostic &PD) {
13326   E = E->IgnoreParenImpCasts();
13327 
13328   const FunctionDecl *FD = nullptr;
13329 
13330   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13331     if (!DRE->getDecl()->getType()->isReferenceType())
13332       return false;
13333   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13334     if (!M->getMemberDecl()->getType()->isReferenceType())
13335       return false;
13336   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13337     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13338       return false;
13339     FD = Call->getDirectCallee();
13340   } else {
13341     return false;
13342   }
13343 
13344   SemaRef.Diag(E->getExprLoc(), PD);
13345 
13346   // If possible, point to location of function.
13347   if (FD) {
13348     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13349   }
13350 
13351   return true;
13352 }
13353 
13354 // Returns true if the SourceLocation is expanded from any macro body.
13355 // Returns false if the SourceLocation is invalid, is from not in a macro
13356 // expansion, or is from expanded from a top-level macro argument.
13357 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13358   if (Loc.isInvalid())
13359     return false;
13360 
13361   while (Loc.isMacroID()) {
13362     if (SM.isMacroBodyExpansion(Loc))
13363       return true;
13364     Loc = SM.getImmediateMacroCallerLoc(Loc);
13365   }
13366 
13367   return false;
13368 }
13369 
13370 /// Diagnose pointers that are always non-null.
13371 /// \param E the expression containing the pointer
13372 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13373 /// compared to a null pointer
13374 /// \param IsEqual True when the comparison is equal to a null pointer
13375 /// \param Range Extra SourceRange to highlight in the diagnostic
13376 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13377                                         Expr::NullPointerConstantKind NullKind,
13378                                         bool IsEqual, SourceRange Range) {
13379   if (!E)
13380     return;
13381 
13382   // Don't warn inside macros.
13383   if (E->getExprLoc().isMacroID()) {
13384     const SourceManager &SM = getSourceManager();
13385     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13386         IsInAnyMacroBody(SM, Range.getBegin()))
13387       return;
13388   }
13389   E = E->IgnoreImpCasts();
13390 
13391   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13392 
13393   if (isa<CXXThisExpr>(E)) {
13394     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13395                                 : diag::warn_this_bool_conversion;
13396     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13397     return;
13398   }
13399 
13400   bool IsAddressOf = false;
13401 
13402   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13403     if (UO->getOpcode() != UO_AddrOf)
13404       return;
13405     IsAddressOf = true;
13406     E = UO->getSubExpr();
13407   }
13408 
13409   if (IsAddressOf) {
13410     unsigned DiagID = IsCompare
13411                           ? diag::warn_address_of_reference_null_compare
13412                           : diag::warn_address_of_reference_bool_conversion;
13413     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13414                                          << IsEqual;
13415     if (CheckForReference(*this, E, PD)) {
13416       return;
13417     }
13418   }
13419 
13420   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13421     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13422     std::string Str;
13423     llvm::raw_string_ostream S(Str);
13424     E->printPretty(S, nullptr, getPrintingPolicy());
13425     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13426                                 : diag::warn_cast_nonnull_to_bool;
13427     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13428       << E->getSourceRange() << Range << IsEqual;
13429     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13430   };
13431 
13432   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13433   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13434     if (auto *Callee = Call->getDirectCallee()) {
13435       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13436         ComplainAboutNonnullParamOrCall(A);
13437         return;
13438       }
13439     }
13440   }
13441 
13442   // Expect to find a single Decl.  Skip anything more complicated.
13443   ValueDecl *D = nullptr;
13444   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13445     D = R->getDecl();
13446   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13447     D = M->getMemberDecl();
13448   }
13449 
13450   // Weak Decls can be null.
13451   if (!D || D->isWeak())
13452     return;
13453 
13454   // Check for parameter decl with nonnull attribute
13455   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13456     if (getCurFunction() &&
13457         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13458       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13459         ComplainAboutNonnullParamOrCall(A);
13460         return;
13461       }
13462 
13463       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13464         // Skip function template not specialized yet.
13465         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13466           return;
13467         auto ParamIter = llvm::find(FD->parameters(), PV);
13468         assert(ParamIter != FD->param_end());
13469         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13470 
13471         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13472           if (!NonNull->args_size()) {
13473               ComplainAboutNonnullParamOrCall(NonNull);
13474               return;
13475           }
13476 
13477           for (const ParamIdx &ArgNo : NonNull->args()) {
13478             if (ArgNo.getASTIndex() == ParamNo) {
13479               ComplainAboutNonnullParamOrCall(NonNull);
13480               return;
13481             }
13482           }
13483         }
13484       }
13485     }
13486   }
13487 
13488   QualType T = D->getType();
13489   const bool IsArray = T->isArrayType();
13490   const bool IsFunction = T->isFunctionType();
13491 
13492   // Address of function is used to silence the function warning.
13493   if (IsAddressOf && IsFunction) {
13494     return;
13495   }
13496 
13497   // Found nothing.
13498   if (!IsAddressOf && !IsFunction && !IsArray)
13499     return;
13500 
13501   // Pretty print the expression for the diagnostic.
13502   std::string Str;
13503   llvm::raw_string_ostream S(Str);
13504   E->printPretty(S, nullptr, getPrintingPolicy());
13505 
13506   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13507                               : diag::warn_impcast_pointer_to_bool;
13508   enum {
13509     AddressOf,
13510     FunctionPointer,
13511     ArrayPointer
13512   } DiagType;
13513   if (IsAddressOf)
13514     DiagType = AddressOf;
13515   else if (IsFunction)
13516     DiagType = FunctionPointer;
13517   else if (IsArray)
13518     DiagType = ArrayPointer;
13519   else
13520     llvm_unreachable("Could not determine diagnostic.");
13521   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13522                                 << Range << IsEqual;
13523 
13524   if (!IsFunction)
13525     return;
13526 
13527   // Suggest '&' to silence the function warning.
13528   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13529       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13530 
13531   // Check to see if '()' fixit should be emitted.
13532   QualType ReturnType;
13533   UnresolvedSet<4> NonTemplateOverloads;
13534   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13535   if (ReturnType.isNull())
13536     return;
13537 
13538   if (IsCompare) {
13539     // There are two cases here.  If there is null constant, the only suggest
13540     // for a pointer return type.  If the null is 0, then suggest if the return
13541     // type is a pointer or an integer type.
13542     if (!ReturnType->isPointerType()) {
13543       if (NullKind == Expr::NPCK_ZeroExpression ||
13544           NullKind == Expr::NPCK_ZeroLiteral) {
13545         if (!ReturnType->isIntegerType())
13546           return;
13547       } else {
13548         return;
13549       }
13550     }
13551   } else { // !IsCompare
13552     // For function to bool, only suggest if the function pointer has bool
13553     // return type.
13554     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13555       return;
13556   }
13557   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13558       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13559 }
13560 
13561 /// Diagnoses "dangerous" implicit conversions within the given
13562 /// expression (which is a full expression).  Implements -Wconversion
13563 /// and -Wsign-compare.
13564 ///
13565 /// \param CC the "context" location of the implicit conversion, i.e.
13566 ///   the most location of the syntactic entity requiring the implicit
13567 ///   conversion
13568 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13569   // Don't diagnose in unevaluated contexts.
13570   if (isUnevaluatedContext())
13571     return;
13572 
13573   // Don't diagnose for value- or type-dependent expressions.
13574   if (E->isTypeDependent() || E->isValueDependent())
13575     return;
13576 
13577   // Check for array bounds violations in cases where the check isn't triggered
13578   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13579   // ArraySubscriptExpr is on the RHS of a variable initialization.
13580   CheckArrayAccess(E);
13581 
13582   // This is not the right CC for (e.g.) a variable initialization.
13583   AnalyzeImplicitConversions(*this, E, CC);
13584 }
13585 
13586 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13587 /// Input argument E is a logical expression.
13588 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13589   ::CheckBoolLikeConversion(*this, E, CC);
13590 }
13591 
13592 /// Diagnose when expression is an integer constant expression and its evaluation
13593 /// results in integer overflow
13594 void Sema::CheckForIntOverflow (Expr *E) {
13595   // Use a work list to deal with nested struct initializers.
13596   SmallVector<Expr *, 2> Exprs(1, E);
13597 
13598   do {
13599     Expr *OriginalE = Exprs.pop_back_val();
13600     Expr *E = OriginalE->IgnoreParenCasts();
13601 
13602     if (isa<BinaryOperator>(E)) {
13603       E->EvaluateForOverflow(Context);
13604       continue;
13605     }
13606 
13607     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13608       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13609     else if (isa<ObjCBoxedExpr>(OriginalE))
13610       E->EvaluateForOverflow(Context);
13611     else if (auto Call = dyn_cast<CallExpr>(E))
13612       Exprs.append(Call->arg_begin(), Call->arg_end());
13613     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13614       Exprs.append(Message->arg_begin(), Message->arg_end());
13615   } while (!Exprs.empty());
13616 }
13617 
13618 namespace {
13619 
13620 /// Visitor for expressions which looks for unsequenced operations on the
13621 /// same object.
13622 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13623   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13624 
13625   /// A tree of sequenced regions within an expression. Two regions are
13626   /// unsequenced if one is an ancestor or a descendent of the other. When we
13627   /// finish processing an expression with sequencing, such as a comma
13628   /// expression, we fold its tree nodes into its parent, since they are
13629   /// unsequenced with respect to nodes we will visit later.
13630   class SequenceTree {
13631     struct Value {
13632       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13633       unsigned Parent : 31;
13634       unsigned Merged : 1;
13635     };
13636     SmallVector<Value, 8> Values;
13637 
13638   public:
13639     /// A region within an expression which may be sequenced with respect
13640     /// to some other region.
13641     class Seq {
13642       friend class SequenceTree;
13643 
13644       unsigned Index;
13645 
13646       explicit Seq(unsigned N) : Index(N) {}
13647 
13648     public:
13649       Seq() : Index(0) {}
13650     };
13651 
13652     SequenceTree() { Values.push_back(Value(0)); }
13653     Seq root() const { return Seq(0); }
13654 
13655     /// Create a new sequence of operations, which is an unsequenced
13656     /// subset of \p Parent. This sequence of operations is sequenced with
13657     /// respect to other children of \p Parent.
13658     Seq allocate(Seq Parent) {
13659       Values.push_back(Value(Parent.Index));
13660       return Seq(Values.size() - 1);
13661     }
13662 
13663     /// Merge a sequence of operations into its parent.
13664     void merge(Seq S) {
13665       Values[S.Index].Merged = true;
13666     }
13667 
13668     /// Determine whether two operations are unsequenced. This operation
13669     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13670     /// should have been merged into its parent as appropriate.
13671     bool isUnsequenced(Seq Cur, Seq Old) {
13672       unsigned C = representative(Cur.Index);
13673       unsigned Target = representative(Old.Index);
13674       while (C >= Target) {
13675         if (C == Target)
13676           return true;
13677         C = Values[C].Parent;
13678       }
13679       return false;
13680     }
13681 
13682   private:
13683     /// Pick a representative for a sequence.
13684     unsigned representative(unsigned K) {
13685       if (Values[K].Merged)
13686         // Perform path compression as we go.
13687         return Values[K].Parent = representative(Values[K].Parent);
13688       return K;
13689     }
13690   };
13691 
13692   /// An object for which we can track unsequenced uses.
13693   using Object = const NamedDecl *;
13694 
13695   /// Different flavors of object usage which we track. We only track the
13696   /// least-sequenced usage of each kind.
13697   enum UsageKind {
13698     /// A read of an object. Multiple unsequenced reads are OK.
13699     UK_Use,
13700 
13701     /// A modification of an object which is sequenced before the value
13702     /// computation of the expression, such as ++n in C++.
13703     UK_ModAsValue,
13704 
13705     /// A modification of an object which is not sequenced before the value
13706     /// computation of the expression, such as n++.
13707     UK_ModAsSideEffect,
13708 
13709     UK_Count = UK_ModAsSideEffect + 1
13710   };
13711 
13712   /// Bundle together a sequencing region and the expression corresponding
13713   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13714   struct Usage {
13715     const Expr *UsageExpr;
13716     SequenceTree::Seq Seq;
13717 
13718     Usage() : UsageExpr(nullptr), Seq() {}
13719   };
13720 
13721   struct UsageInfo {
13722     Usage Uses[UK_Count];
13723 
13724     /// Have we issued a diagnostic for this object already?
13725     bool Diagnosed;
13726 
13727     UsageInfo() : Uses(), Diagnosed(false) {}
13728   };
13729   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13730 
13731   Sema &SemaRef;
13732 
13733   /// Sequenced regions within the expression.
13734   SequenceTree Tree;
13735 
13736   /// Declaration modifications and references which we have seen.
13737   UsageInfoMap UsageMap;
13738 
13739   /// The region we are currently within.
13740   SequenceTree::Seq Region;
13741 
13742   /// Filled in with declarations which were modified as a side-effect
13743   /// (that is, post-increment operations).
13744   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13745 
13746   /// Expressions to check later. We defer checking these to reduce
13747   /// stack usage.
13748   SmallVectorImpl<const Expr *> &WorkList;
13749 
13750   /// RAII object wrapping the visitation of a sequenced subexpression of an
13751   /// expression. At the end of this process, the side-effects of the evaluation
13752   /// become sequenced with respect to the value computation of the result, so
13753   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13754   /// UK_ModAsValue.
13755   struct SequencedSubexpression {
13756     SequencedSubexpression(SequenceChecker &Self)
13757       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13758       Self.ModAsSideEffect = &ModAsSideEffect;
13759     }
13760 
13761     ~SequencedSubexpression() {
13762       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13763         // Add a new usage with usage kind UK_ModAsValue, and then restore
13764         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13765         // the previous one was empty).
13766         UsageInfo &UI = Self.UsageMap[M.first];
13767         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13768         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13769         SideEffectUsage = M.second;
13770       }
13771       Self.ModAsSideEffect = OldModAsSideEffect;
13772     }
13773 
13774     SequenceChecker &Self;
13775     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13776     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13777   };
13778 
13779   /// RAII object wrapping the visitation of a subexpression which we might
13780   /// choose to evaluate as a constant. If any subexpression is evaluated and
13781   /// found to be non-constant, this allows us to suppress the evaluation of
13782   /// the outer expression.
13783   class EvaluationTracker {
13784   public:
13785     EvaluationTracker(SequenceChecker &Self)
13786         : Self(Self), Prev(Self.EvalTracker) {
13787       Self.EvalTracker = this;
13788     }
13789 
13790     ~EvaluationTracker() {
13791       Self.EvalTracker = Prev;
13792       if (Prev)
13793         Prev->EvalOK &= EvalOK;
13794     }
13795 
13796     bool evaluate(const Expr *E, bool &Result) {
13797       if (!EvalOK || E->isValueDependent())
13798         return false;
13799       EvalOK = E->EvaluateAsBooleanCondition(
13800           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13801       return EvalOK;
13802     }
13803 
13804   private:
13805     SequenceChecker &Self;
13806     EvaluationTracker *Prev;
13807     bool EvalOK = true;
13808   } *EvalTracker = nullptr;
13809 
13810   /// Find the object which is produced by the specified expression,
13811   /// if any.
13812   Object getObject(const Expr *E, bool Mod) const {
13813     E = E->IgnoreParenCasts();
13814     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13815       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13816         return getObject(UO->getSubExpr(), Mod);
13817     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13818       if (BO->getOpcode() == BO_Comma)
13819         return getObject(BO->getRHS(), Mod);
13820       if (Mod && BO->isAssignmentOp())
13821         return getObject(BO->getLHS(), Mod);
13822     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13823       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13824       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13825         return ME->getMemberDecl();
13826     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13827       // FIXME: If this is a reference, map through to its value.
13828       return DRE->getDecl();
13829     return nullptr;
13830   }
13831 
13832   /// Note that an object \p O was modified or used by an expression
13833   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13834   /// the object \p O as obtained via the \p UsageMap.
13835   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13836     // Get the old usage for the given object and usage kind.
13837     Usage &U = UI.Uses[UK];
13838     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13839       // If we have a modification as side effect and are in a sequenced
13840       // subexpression, save the old Usage so that we can restore it later
13841       // in SequencedSubexpression::~SequencedSubexpression.
13842       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13843         ModAsSideEffect->push_back(std::make_pair(O, U));
13844       // Then record the new usage with the current sequencing region.
13845       U.UsageExpr = UsageExpr;
13846       U.Seq = Region;
13847     }
13848   }
13849 
13850   /// Check whether a modification or use of an object \p O in an expression
13851   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13852   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13853   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13854   /// usage and false we are checking for a mod-use unsequenced usage.
13855   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13856                   UsageKind OtherKind, bool IsModMod) {
13857     if (UI.Diagnosed)
13858       return;
13859 
13860     const Usage &U = UI.Uses[OtherKind];
13861     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13862       return;
13863 
13864     const Expr *Mod = U.UsageExpr;
13865     const Expr *ModOrUse = UsageExpr;
13866     if (OtherKind == UK_Use)
13867       std::swap(Mod, ModOrUse);
13868 
13869     SemaRef.DiagRuntimeBehavior(
13870         Mod->getExprLoc(), {Mod, ModOrUse},
13871         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13872                                : diag::warn_unsequenced_mod_use)
13873             << O << SourceRange(ModOrUse->getExprLoc()));
13874     UI.Diagnosed = true;
13875   }
13876 
13877   // A note on note{Pre, Post}{Use, Mod}:
13878   //
13879   // (It helps to follow the algorithm with an expression such as
13880   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13881   //  operations before C++17 and both are well-defined in C++17).
13882   //
13883   // When visiting a node which uses/modify an object we first call notePreUse
13884   // or notePreMod before visiting its sub-expression(s). At this point the
13885   // children of the current node have not yet been visited and so the eventual
13886   // uses/modifications resulting from the children of the current node have not
13887   // been recorded yet.
13888   //
13889   // We then visit the children of the current node. After that notePostUse or
13890   // notePostMod is called. These will 1) detect an unsequenced modification
13891   // as side effect (as in "k++ + k") and 2) add a new usage with the
13892   // appropriate usage kind.
13893   //
13894   // We also have to be careful that some operation sequences modification as
13895   // side effect as well (for example: || or ,). To account for this we wrap
13896   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13897   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13898   // which record usages which are modifications as side effect, and then
13899   // downgrade them (or more accurately restore the previous usage which was a
13900   // modification as side effect) when exiting the scope of the sequenced
13901   // subexpression.
13902 
13903   void notePreUse(Object O, const Expr *UseExpr) {
13904     UsageInfo &UI = UsageMap[O];
13905     // Uses conflict with other modifications.
13906     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13907   }
13908 
13909   void notePostUse(Object O, const Expr *UseExpr) {
13910     UsageInfo &UI = UsageMap[O];
13911     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13912                /*IsModMod=*/false);
13913     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13914   }
13915 
13916   void notePreMod(Object O, const Expr *ModExpr) {
13917     UsageInfo &UI = UsageMap[O];
13918     // Modifications conflict with other modifications and with uses.
13919     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13920     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13921   }
13922 
13923   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13924     UsageInfo &UI = UsageMap[O];
13925     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13926                /*IsModMod=*/true);
13927     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13928   }
13929 
13930 public:
13931   SequenceChecker(Sema &S, const Expr *E,
13932                   SmallVectorImpl<const Expr *> &WorkList)
13933       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13934     Visit(E);
13935     // Silence a -Wunused-private-field since WorkList is now unused.
13936     // TODO: Evaluate if it can be used, and if not remove it.
13937     (void)this->WorkList;
13938   }
13939 
13940   void VisitStmt(const Stmt *S) {
13941     // Skip all statements which aren't expressions for now.
13942   }
13943 
13944   void VisitExpr(const Expr *E) {
13945     // By default, just recurse to evaluated subexpressions.
13946     Base::VisitStmt(E);
13947   }
13948 
13949   void VisitCastExpr(const CastExpr *E) {
13950     Object O = Object();
13951     if (E->getCastKind() == CK_LValueToRValue)
13952       O = getObject(E->getSubExpr(), false);
13953 
13954     if (O)
13955       notePreUse(O, E);
13956     VisitExpr(E);
13957     if (O)
13958       notePostUse(O, E);
13959   }
13960 
13961   void VisitSequencedExpressions(const Expr *SequencedBefore,
13962                                  const Expr *SequencedAfter) {
13963     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13964     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13965     SequenceTree::Seq OldRegion = Region;
13966 
13967     {
13968       SequencedSubexpression SeqBefore(*this);
13969       Region = BeforeRegion;
13970       Visit(SequencedBefore);
13971     }
13972 
13973     Region = AfterRegion;
13974     Visit(SequencedAfter);
13975 
13976     Region = OldRegion;
13977 
13978     Tree.merge(BeforeRegion);
13979     Tree.merge(AfterRegion);
13980   }
13981 
13982   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13983     // C++17 [expr.sub]p1:
13984     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13985     //   expression E1 is sequenced before the expression E2.
13986     if (SemaRef.getLangOpts().CPlusPlus17)
13987       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13988     else {
13989       Visit(ASE->getLHS());
13990       Visit(ASE->getRHS());
13991     }
13992   }
13993 
13994   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13995   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13996   void VisitBinPtrMem(const BinaryOperator *BO) {
13997     // C++17 [expr.mptr.oper]p4:
13998     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13999     //  the expression E1 is sequenced before the expression E2.
14000     if (SemaRef.getLangOpts().CPlusPlus17)
14001       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14002     else {
14003       Visit(BO->getLHS());
14004       Visit(BO->getRHS());
14005     }
14006   }
14007 
14008   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14009   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
14010   void VisitBinShlShr(const BinaryOperator *BO) {
14011     // C++17 [expr.shift]p4:
14012     //  The expression E1 is sequenced before the expression E2.
14013     if (SemaRef.getLangOpts().CPlusPlus17)
14014       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14015     else {
14016       Visit(BO->getLHS());
14017       Visit(BO->getRHS());
14018     }
14019   }
14020 
14021   void VisitBinComma(const BinaryOperator *BO) {
14022     // C++11 [expr.comma]p1:
14023     //   Every value computation and side effect associated with the left
14024     //   expression is sequenced before every value computation and side
14025     //   effect associated with the right expression.
14026     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14027   }
14028 
14029   void VisitBinAssign(const BinaryOperator *BO) {
14030     SequenceTree::Seq RHSRegion;
14031     SequenceTree::Seq LHSRegion;
14032     if (SemaRef.getLangOpts().CPlusPlus17) {
14033       RHSRegion = Tree.allocate(Region);
14034       LHSRegion = Tree.allocate(Region);
14035     } else {
14036       RHSRegion = Region;
14037       LHSRegion = Region;
14038     }
14039     SequenceTree::Seq OldRegion = Region;
14040 
14041     // C++11 [expr.ass]p1:
14042     //  [...] the assignment is sequenced after the value computation
14043     //  of the right and left operands, [...]
14044     //
14045     // so check it before inspecting the operands and update the
14046     // map afterwards.
14047     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14048     if (O)
14049       notePreMod(O, BO);
14050 
14051     if (SemaRef.getLangOpts().CPlusPlus17) {
14052       // C++17 [expr.ass]p1:
14053       //  [...] The right operand is sequenced before the left operand. [...]
14054       {
14055         SequencedSubexpression SeqBefore(*this);
14056         Region = RHSRegion;
14057         Visit(BO->getRHS());
14058       }
14059 
14060       Region = LHSRegion;
14061       Visit(BO->getLHS());
14062 
14063       if (O && isa<CompoundAssignOperator>(BO))
14064         notePostUse(O, BO);
14065 
14066     } else {
14067       // C++11 does not specify any sequencing between the LHS and RHS.
14068       Region = LHSRegion;
14069       Visit(BO->getLHS());
14070 
14071       if (O && isa<CompoundAssignOperator>(BO))
14072         notePostUse(O, BO);
14073 
14074       Region = RHSRegion;
14075       Visit(BO->getRHS());
14076     }
14077 
14078     // C++11 [expr.ass]p1:
14079     //  the assignment is sequenced [...] before the value computation of the
14080     //  assignment expression.
14081     // C11 6.5.16/3 has no such rule.
14082     Region = OldRegion;
14083     if (O)
14084       notePostMod(O, BO,
14085                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14086                                                   : UK_ModAsSideEffect);
14087     if (SemaRef.getLangOpts().CPlusPlus17) {
14088       Tree.merge(RHSRegion);
14089       Tree.merge(LHSRegion);
14090     }
14091   }
14092 
14093   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14094     VisitBinAssign(CAO);
14095   }
14096 
14097   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14098   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14099   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14100     Object O = getObject(UO->getSubExpr(), true);
14101     if (!O)
14102       return VisitExpr(UO);
14103 
14104     notePreMod(O, UO);
14105     Visit(UO->getSubExpr());
14106     // C++11 [expr.pre.incr]p1:
14107     //   the expression ++x is equivalent to x+=1
14108     notePostMod(O, UO,
14109                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14110                                                 : UK_ModAsSideEffect);
14111   }
14112 
14113   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14114   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14115   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14116     Object O = getObject(UO->getSubExpr(), true);
14117     if (!O)
14118       return VisitExpr(UO);
14119 
14120     notePreMod(O, UO);
14121     Visit(UO->getSubExpr());
14122     notePostMod(O, UO, UK_ModAsSideEffect);
14123   }
14124 
14125   void VisitBinLOr(const BinaryOperator *BO) {
14126     // C++11 [expr.log.or]p2:
14127     //  If the second expression is evaluated, every value computation and
14128     //  side effect associated with the first expression is sequenced before
14129     //  every value computation and side effect associated with the
14130     //  second expression.
14131     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14132     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14133     SequenceTree::Seq OldRegion = Region;
14134 
14135     EvaluationTracker Eval(*this);
14136     {
14137       SequencedSubexpression Sequenced(*this);
14138       Region = LHSRegion;
14139       Visit(BO->getLHS());
14140     }
14141 
14142     // C++11 [expr.log.or]p1:
14143     //  [...] the second operand is not evaluated if the first operand
14144     //  evaluates to true.
14145     bool EvalResult = false;
14146     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14147     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14148     if (ShouldVisitRHS) {
14149       Region = RHSRegion;
14150       Visit(BO->getRHS());
14151     }
14152 
14153     Region = OldRegion;
14154     Tree.merge(LHSRegion);
14155     Tree.merge(RHSRegion);
14156   }
14157 
14158   void VisitBinLAnd(const BinaryOperator *BO) {
14159     // C++11 [expr.log.and]p2:
14160     //  If the second expression is evaluated, every value computation and
14161     //  side effect associated with the first expression is sequenced before
14162     //  every value computation and side effect associated with the
14163     //  second expression.
14164     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14165     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14166     SequenceTree::Seq OldRegion = Region;
14167 
14168     EvaluationTracker Eval(*this);
14169     {
14170       SequencedSubexpression Sequenced(*this);
14171       Region = LHSRegion;
14172       Visit(BO->getLHS());
14173     }
14174 
14175     // C++11 [expr.log.and]p1:
14176     //  [...] the second operand is not evaluated if the first operand is false.
14177     bool EvalResult = false;
14178     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14179     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14180     if (ShouldVisitRHS) {
14181       Region = RHSRegion;
14182       Visit(BO->getRHS());
14183     }
14184 
14185     Region = OldRegion;
14186     Tree.merge(LHSRegion);
14187     Tree.merge(RHSRegion);
14188   }
14189 
14190   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14191     // C++11 [expr.cond]p1:
14192     //  [...] Every value computation and side effect associated with the first
14193     //  expression is sequenced before every value computation and side effect
14194     //  associated with the second or third expression.
14195     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14196 
14197     // No sequencing is specified between the true and false expression.
14198     // However since exactly one of both is going to be evaluated we can
14199     // consider them to be sequenced. This is needed to avoid warning on
14200     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14201     // both the true and false expressions because we can't evaluate x.
14202     // This will still allow us to detect an expression like (pre C++17)
14203     // "(x ? y += 1 : y += 2) = y".
14204     //
14205     // We don't wrap the visitation of the true and false expression with
14206     // SequencedSubexpression because we don't want to downgrade modifications
14207     // as side effect in the true and false expressions after the visition
14208     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14209     // not warn between the two "y++", but we should warn between the "y++"
14210     // and the "y".
14211     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14212     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14213     SequenceTree::Seq OldRegion = Region;
14214 
14215     EvaluationTracker Eval(*this);
14216     {
14217       SequencedSubexpression Sequenced(*this);
14218       Region = ConditionRegion;
14219       Visit(CO->getCond());
14220     }
14221 
14222     // C++11 [expr.cond]p1:
14223     // [...] The first expression is contextually converted to bool (Clause 4).
14224     // It is evaluated and if it is true, the result of the conditional
14225     // expression is the value of the second expression, otherwise that of the
14226     // third expression. Only one of the second and third expressions is
14227     // evaluated. [...]
14228     bool EvalResult = false;
14229     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14230     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14231     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14232     if (ShouldVisitTrueExpr) {
14233       Region = TrueRegion;
14234       Visit(CO->getTrueExpr());
14235     }
14236     if (ShouldVisitFalseExpr) {
14237       Region = FalseRegion;
14238       Visit(CO->getFalseExpr());
14239     }
14240 
14241     Region = OldRegion;
14242     Tree.merge(ConditionRegion);
14243     Tree.merge(TrueRegion);
14244     Tree.merge(FalseRegion);
14245   }
14246 
14247   void VisitCallExpr(const CallExpr *CE) {
14248     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14249 
14250     if (CE->isUnevaluatedBuiltinCall(Context))
14251       return;
14252 
14253     // C++11 [intro.execution]p15:
14254     //   When calling a function [...], every value computation and side effect
14255     //   associated with any argument expression, or with the postfix expression
14256     //   designating the called function, is sequenced before execution of every
14257     //   expression or statement in the body of the function [and thus before
14258     //   the value computation of its result].
14259     SequencedSubexpression Sequenced(*this);
14260     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14261       // C++17 [expr.call]p5
14262       //   The postfix-expression is sequenced before each expression in the
14263       //   expression-list and any default argument. [...]
14264       SequenceTree::Seq CalleeRegion;
14265       SequenceTree::Seq OtherRegion;
14266       if (SemaRef.getLangOpts().CPlusPlus17) {
14267         CalleeRegion = Tree.allocate(Region);
14268         OtherRegion = Tree.allocate(Region);
14269       } else {
14270         CalleeRegion = Region;
14271         OtherRegion = Region;
14272       }
14273       SequenceTree::Seq OldRegion = Region;
14274 
14275       // Visit the callee expression first.
14276       Region = CalleeRegion;
14277       if (SemaRef.getLangOpts().CPlusPlus17) {
14278         SequencedSubexpression Sequenced(*this);
14279         Visit(CE->getCallee());
14280       } else {
14281         Visit(CE->getCallee());
14282       }
14283 
14284       // Then visit the argument expressions.
14285       Region = OtherRegion;
14286       for (const Expr *Argument : CE->arguments())
14287         Visit(Argument);
14288 
14289       Region = OldRegion;
14290       if (SemaRef.getLangOpts().CPlusPlus17) {
14291         Tree.merge(CalleeRegion);
14292         Tree.merge(OtherRegion);
14293       }
14294     });
14295   }
14296 
14297   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14298     // C++17 [over.match.oper]p2:
14299     //   [...] the operator notation is first transformed to the equivalent
14300     //   function-call notation as summarized in Table 12 (where @ denotes one
14301     //   of the operators covered in the specified subclause). However, the
14302     //   operands are sequenced in the order prescribed for the built-in
14303     //   operator (Clause 8).
14304     //
14305     // From the above only overloaded binary operators and overloaded call
14306     // operators have sequencing rules in C++17 that we need to handle
14307     // separately.
14308     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14309         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14310       return VisitCallExpr(CXXOCE);
14311 
14312     enum {
14313       NoSequencing,
14314       LHSBeforeRHS,
14315       RHSBeforeLHS,
14316       LHSBeforeRest
14317     } SequencingKind;
14318     switch (CXXOCE->getOperator()) {
14319     case OO_Equal:
14320     case OO_PlusEqual:
14321     case OO_MinusEqual:
14322     case OO_StarEqual:
14323     case OO_SlashEqual:
14324     case OO_PercentEqual:
14325     case OO_CaretEqual:
14326     case OO_AmpEqual:
14327     case OO_PipeEqual:
14328     case OO_LessLessEqual:
14329     case OO_GreaterGreaterEqual:
14330       SequencingKind = RHSBeforeLHS;
14331       break;
14332 
14333     case OO_LessLess:
14334     case OO_GreaterGreater:
14335     case OO_AmpAmp:
14336     case OO_PipePipe:
14337     case OO_Comma:
14338     case OO_ArrowStar:
14339     case OO_Subscript:
14340       SequencingKind = LHSBeforeRHS;
14341       break;
14342 
14343     case OO_Call:
14344       SequencingKind = LHSBeforeRest;
14345       break;
14346 
14347     default:
14348       SequencingKind = NoSequencing;
14349       break;
14350     }
14351 
14352     if (SequencingKind == NoSequencing)
14353       return VisitCallExpr(CXXOCE);
14354 
14355     // This is a call, so all subexpressions are sequenced before the result.
14356     SequencedSubexpression Sequenced(*this);
14357 
14358     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14359       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14360              "Should only get there with C++17 and above!");
14361       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14362              "Should only get there with an overloaded binary operator"
14363              " or an overloaded call operator!");
14364 
14365       if (SequencingKind == LHSBeforeRest) {
14366         assert(CXXOCE->getOperator() == OO_Call &&
14367                "We should only have an overloaded call operator here!");
14368 
14369         // This is very similar to VisitCallExpr, except that we only have the
14370         // C++17 case. The postfix-expression is the first argument of the
14371         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14372         // are in the following arguments.
14373         //
14374         // Note that we intentionally do not visit the callee expression since
14375         // it is just a decayed reference to a function.
14376         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14377         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14378         SequenceTree::Seq OldRegion = Region;
14379 
14380         assert(CXXOCE->getNumArgs() >= 1 &&
14381                "An overloaded call operator must have at least one argument"
14382                " for the postfix-expression!");
14383         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14384         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14385                                           CXXOCE->getNumArgs() - 1);
14386 
14387         // Visit the postfix-expression first.
14388         {
14389           Region = PostfixExprRegion;
14390           SequencedSubexpression Sequenced(*this);
14391           Visit(PostfixExpr);
14392         }
14393 
14394         // Then visit the argument expressions.
14395         Region = ArgsRegion;
14396         for (const Expr *Arg : Args)
14397           Visit(Arg);
14398 
14399         Region = OldRegion;
14400         Tree.merge(PostfixExprRegion);
14401         Tree.merge(ArgsRegion);
14402       } else {
14403         assert(CXXOCE->getNumArgs() == 2 &&
14404                "Should only have two arguments here!");
14405         assert((SequencingKind == LHSBeforeRHS ||
14406                 SequencingKind == RHSBeforeLHS) &&
14407                "Unexpected sequencing kind!");
14408 
14409         // We do not visit the callee expression since it is just a decayed
14410         // reference to a function.
14411         const Expr *E1 = CXXOCE->getArg(0);
14412         const Expr *E2 = CXXOCE->getArg(1);
14413         if (SequencingKind == RHSBeforeLHS)
14414           std::swap(E1, E2);
14415 
14416         return VisitSequencedExpressions(E1, E2);
14417       }
14418     });
14419   }
14420 
14421   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14422     // This is a call, so all subexpressions are sequenced before the result.
14423     SequencedSubexpression Sequenced(*this);
14424 
14425     if (!CCE->isListInitialization())
14426       return VisitExpr(CCE);
14427 
14428     // In C++11, list initializations are sequenced.
14429     SmallVector<SequenceTree::Seq, 32> Elts;
14430     SequenceTree::Seq Parent = Region;
14431     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14432                                               E = CCE->arg_end();
14433          I != E; ++I) {
14434       Region = Tree.allocate(Parent);
14435       Elts.push_back(Region);
14436       Visit(*I);
14437     }
14438 
14439     // Forget that the initializers are sequenced.
14440     Region = Parent;
14441     for (unsigned I = 0; I < Elts.size(); ++I)
14442       Tree.merge(Elts[I]);
14443   }
14444 
14445   void VisitInitListExpr(const InitListExpr *ILE) {
14446     if (!SemaRef.getLangOpts().CPlusPlus11)
14447       return VisitExpr(ILE);
14448 
14449     // In C++11, list initializations are sequenced.
14450     SmallVector<SequenceTree::Seq, 32> Elts;
14451     SequenceTree::Seq Parent = Region;
14452     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14453       const Expr *E = ILE->getInit(I);
14454       if (!E)
14455         continue;
14456       Region = Tree.allocate(Parent);
14457       Elts.push_back(Region);
14458       Visit(E);
14459     }
14460 
14461     // Forget that the initializers are sequenced.
14462     Region = Parent;
14463     for (unsigned I = 0; I < Elts.size(); ++I)
14464       Tree.merge(Elts[I]);
14465   }
14466 };
14467 
14468 } // namespace
14469 
14470 void Sema::CheckUnsequencedOperations(const Expr *E) {
14471   SmallVector<const Expr *, 8> WorkList;
14472   WorkList.push_back(E);
14473   while (!WorkList.empty()) {
14474     const Expr *Item = WorkList.pop_back_val();
14475     SequenceChecker(*this, Item, WorkList);
14476   }
14477 }
14478 
14479 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14480                               bool IsConstexpr) {
14481   llvm::SaveAndRestore<bool> ConstantContext(
14482       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14483   CheckImplicitConversions(E, CheckLoc);
14484   if (!E->isInstantiationDependent())
14485     CheckUnsequencedOperations(E);
14486   if (!IsConstexpr && !E->isValueDependent())
14487     CheckForIntOverflow(E);
14488   DiagnoseMisalignedMembers();
14489 }
14490 
14491 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14492                                        FieldDecl *BitField,
14493                                        Expr *Init) {
14494   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14495 }
14496 
14497 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14498                                          SourceLocation Loc) {
14499   if (!PType->isVariablyModifiedType())
14500     return;
14501   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14502     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14503     return;
14504   }
14505   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14506     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14507     return;
14508   }
14509   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14510     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14511     return;
14512   }
14513 
14514   const ArrayType *AT = S.Context.getAsArrayType(PType);
14515   if (!AT)
14516     return;
14517 
14518   if (AT->getSizeModifier() != ArrayType::Star) {
14519     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14520     return;
14521   }
14522 
14523   S.Diag(Loc, diag::err_array_star_in_function_definition);
14524 }
14525 
14526 /// CheckParmsForFunctionDef - Check that the parameters of the given
14527 /// function are appropriate for the definition of a function. This
14528 /// takes care of any checks that cannot be performed on the
14529 /// declaration itself, e.g., that the types of each of the function
14530 /// parameters are complete.
14531 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14532                                     bool CheckParameterNames) {
14533   bool HasInvalidParm = false;
14534   for (ParmVarDecl *Param : Parameters) {
14535     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14536     // function declarator that is part of a function definition of
14537     // that function shall not have incomplete type.
14538     //
14539     // This is also C++ [dcl.fct]p6.
14540     if (!Param->isInvalidDecl() &&
14541         RequireCompleteType(Param->getLocation(), Param->getType(),
14542                             diag::err_typecheck_decl_incomplete_type)) {
14543       Param->setInvalidDecl();
14544       HasInvalidParm = true;
14545     }
14546 
14547     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14548     // declaration of each parameter shall include an identifier.
14549     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14550         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14551       // Diagnose this as an extension in C17 and earlier.
14552       if (!getLangOpts().C2x)
14553         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14554     }
14555 
14556     // C99 6.7.5.3p12:
14557     //   If the function declarator is not part of a definition of that
14558     //   function, parameters may have incomplete type and may use the [*]
14559     //   notation in their sequences of declarator specifiers to specify
14560     //   variable length array types.
14561     QualType PType = Param->getOriginalType();
14562     // FIXME: This diagnostic should point the '[*]' if source-location
14563     // information is added for it.
14564     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14565 
14566     // If the parameter is a c++ class type and it has to be destructed in the
14567     // callee function, declare the destructor so that it can be called by the
14568     // callee function. Do not perform any direct access check on the dtor here.
14569     if (!Param->isInvalidDecl()) {
14570       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14571         if (!ClassDecl->isInvalidDecl() &&
14572             !ClassDecl->hasIrrelevantDestructor() &&
14573             !ClassDecl->isDependentContext() &&
14574             ClassDecl->isParamDestroyedInCallee()) {
14575           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14576           MarkFunctionReferenced(Param->getLocation(), Destructor);
14577           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14578         }
14579       }
14580     }
14581 
14582     // Parameters with the pass_object_size attribute only need to be marked
14583     // constant at function definitions. Because we lack information about
14584     // whether we're on a declaration or definition when we're instantiating the
14585     // attribute, we need to check for constness here.
14586     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14587       if (!Param->getType().isConstQualified())
14588         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14589             << Attr->getSpelling() << 1;
14590 
14591     // Check for parameter names shadowing fields from the class.
14592     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14593       // The owning context for the parameter should be the function, but we
14594       // want to see if this function's declaration context is a record.
14595       DeclContext *DC = Param->getDeclContext();
14596       if (DC && DC->isFunctionOrMethod()) {
14597         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14598           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14599                                      RD, /*DeclIsField*/ false);
14600       }
14601     }
14602   }
14603 
14604   return HasInvalidParm;
14605 }
14606 
14607 Optional<std::pair<CharUnits, CharUnits>>
14608 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14609 
14610 /// Compute the alignment and offset of the base class object given the
14611 /// derived-to-base cast expression and the alignment and offset of the derived
14612 /// class object.
14613 static std::pair<CharUnits, CharUnits>
14614 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14615                                    CharUnits BaseAlignment, CharUnits Offset,
14616                                    ASTContext &Ctx) {
14617   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14618        ++PathI) {
14619     const CXXBaseSpecifier *Base = *PathI;
14620     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14621     if (Base->isVirtual()) {
14622       // The complete object may have a lower alignment than the non-virtual
14623       // alignment of the base, in which case the base may be misaligned. Choose
14624       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14625       // conservative lower bound of the complete object alignment.
14626       CharUnits NonVirtualAlignment =
14627           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14628       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14629       Offset = CharUnits::Zero();
14630     } else {
14631       const ASTRecordLayout &RL =
14632           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14633       Offset += RL.getBaseClassOffset(BaseDecl);
14634     }
14635     DerivedType = Base->getType();
14636   }
14637 
14638   return std::make_pair(BaseAlignment, Offset);
14639 }
14640 
14641 /// Compute the alignment and offset of a binary additive operator.
14642 static Optional<std::pair<CharUnits, CharUnits>>
14643 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14644                                      bool IsSub, ASTContext &Ctx) {
14645   QualType PointeeType = PtrE->getType()->getPointeeType();
14646 
14647   if (!PointeeType->isConstantSizeType())
14648     return llvm::None;
14649 
14650   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14651 
14652   if (!P)
14653     return llvm::None;
14654 
14655   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14656   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14657     CharUnits Offset = EltSize * IdxRes->getExtValue();
14658     if (IsSub)
14659       Offset = -Offset;
14660     return std::make_pair(P->first, P->second + Offset);
14661   }
14662 
14663   // If the integer expression isn't a constant expression, compute the lower
14664   // bound of the alignment using the alignment and offset of the pointer
14665   // expression and the element size.
14666   return std::make_pair(
14667       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14668       CharUnits::Zero());
14669 }
14670 
14671 /// This helper function takes an lvalue expression and returns the alignment of
14672 /// a VarDecl and a constant offset from the VarDecl.
14673 Optional<std::pair<CharUnits, CharUnits>>
14674 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14675   E = E->IgnoreParens();
14676   switch (E->getStmtClass()) {
14677   default:
14678     break;
14679   case Stmt::CStyleCastExprClass:
14680   case Stmt::CXXStaticCastExprClass:
14681   case Stmt::ImplicitCastExprClass: {
14682     auto *CE = cast<CastExpr>(E);
14683     const Expr *From = CE->getSubExpr();
14684     switch (CE->getCastKind()) {
14685     default:
14686       break;
14687     case CK_NoOp:
14688       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14689     case CK_UncheckedDerivedToBase:
14690     case CK_DerivedToBase: {
14691       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14692       if (!P)
14693         break;
14694       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14695                                                 P->second, Ctx);
14696     }
14697     }
14698     break;
14699   }
14700   case Stmt::ArraySubscriptExprClass: {
14701     auto *ASE = cast<ArraySubscriptExpr>(E);
14702     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14703                                                 false, Ctx);
14704   }
14705   case Stmt::DeclRefExprClass: {
14706     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14707       // FIXME: If VD is captured by copy or is an escaping __block variable,
14708       // use the alignment of VD's type.
14709       if (!VD->getType()->isReferenceType())
14710         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14711       if (VD->hasInit())
14712         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14713     }
14714     break;
14715   }
14716   case Stmt::MemberExprClass: {
14717     auto *ME = cast<MemberExpr>(E);
14718     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14719     if (!FD || FD->getType()->isReferenceType() ||
14720         FD->getParent()->isInvalidDecl())
14721       break;
14722     Optional<std::pair<CharUnits, CharUnits>> P;
14723     if (ME->isArrow())
14724       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14725     else
14726       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14727     if (!P)
14728       break;
14729     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14730     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14731     return std::make_pair(P->first,
14732                           P->second + CharUnits::fromQuantity(Offset));
14733   }
14734   case Stmt::UnaryOperatorClass: {
14735     auto *UO = cast<UnaryOperator>(E);
14736     switch (UO->getOpcode()) {
14737     default:
14738       break;
14739     case UO_Deref:
14740       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14741     }
14742     break;
14743   }
14744   case Stmt::BinaryOperatorClass: {
14745     auto *BO = cast<BinaryOperator>(E);
14746     auto Opcode = BO->getOpcode();
14747     switch (Opcode) {
14748     default:
14749       break;
14750     case BO_Comma:
14751       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14752     }
14753     break;
14754   }
14755   }
14756   return llvm::None;
14757 }
14758 
14759 /// This helper function takes a pointer expression and returns the alignment of
14760 /// a VarDecl and a constant offset from the VarDecl.
14761 Optional<std::pair<CharUnits, CharUnits>>
14762 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14763   E = E->IgnoreParens();
14764   switch (E->getStmtClass()) {
14765   default:
14766     break;
14767   case Stmt::CStyleCastExprClass:
14768   case Stmt::CXXStaticCastExprClass:
14769   case Stmt::ImplicitCastExprClass: {
14770     auto *CE = cast<CastExpr>(E);
14771     const Expr *From = CE->getSubExpr();
14772     switch (CE->getCastKind()) {
14773     default:
14774       break;
14775     case CK_NoOp:
14776       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14777     case CK_ArrayToPointerDecay:
14778       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14779     case CK_UncheckedDerivedToBase:
14780     case CK_DerivedToBase: {
14781       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14782       if (!P)
14783         break;
14784       return getDerivedToBaseAlignmentAndOffset(
14785           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14786     }
14787     }
14788     break;
14789   }
14790   case Stmt::CXXThisExprClass: {
14791     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14792     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14793     return std::make_pair(Alignment, CharUnits::Zero());
14794   }
14795   case Stmt::UnaryOperatorClass: {
14796     auto *UO = cast<UnaryOperator>(E);
14797     if (UO->getOpcode() == UO_AddrOf)
14798       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14799     break;
14800   }
14801   case Stmt::BinaryOperatorClass: {
14802     auto *BO = cast<BinaryOperator>(E);
14803     auto Opcode = BO->getOpcode();
14804     switch (Opcode) {
14805     default:
14806       break;
14807     case BO_Add:
14808     case BO_Sub: {
14809       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14810       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14811         std::swap(LHS, RHS);
14812       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14813                                                   Ctx);
14814     }
14815     case BO_Comma:
14816       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14817     }
14818     break;
14819   }
14820   }
14821   return llvm::None;
14822 }
14823 
14824 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14825   // See if we can compute the alignment of a VarDecl and an offset from it.
14826   Optional<std::pair<CharUnits, CharUnits>> P =
14827       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14828 
14829   if (P)
14830     return P->first.alignmentAtOffset(P->second);
14831 
14832   // If that failed, return the type's alignment.
14833   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14834 }
14835 
14836 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14837 /// pointer cast increases the alignment requirements.
14838 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14839   // This is actually a lot of work to potentially be doing on every
14840   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14841   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14842     return;
14843 
14844   // Ignore dependent types.
14845   if (T->isDependentType() || Op->getType()->isDependentType())
14846     return;
14847 
14848   // Require that the destination be a pointer type.
14849   const PointerType *DestPtr = T->getAs<PointerType>();
14850   if (!DestPtr) return;
14851 
14852   // If the destination has alignment 1, we're done.
14853   QualType DestPointee = DestPtr->getPointeeType();
14854   if (DestPointee->isIncompleteType()) return;
14855   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14856   if (DestAlign.isOne()) return;
14857 
14858   // Require that the source be a pointer type.
14859   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14860   if (!SrcPtr) return;
14861   QualType SrcPointee = SrcPtr->getPointeeType();
14862 
14863   // Explicitly allow casts from cv void*.  We already implicitly
14864   // allowed casts to cv void*, since they have alignment 1.
14865   // Also allow casts involving incomplete types, which implicitly
14866   // includes 'void'.
14867   if (SrcPointee->isIncompleteType()) return;
14868 
14869   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14870 
14871   if (SrcAlign >= DestAlign) return;
14872 
14873   Diag(TRange.getBegin(), diag::warn_cast_align)
14874     << Op->getType() << T
14875     << static_cast<unsigned>(SrcAlign.getQuantity())
14876     << static_cast<unsigned>(DestAlign.getQuantity())
14877     << TRange << Op->getSourceRange();
14878 }
14879 
14880 /// Check whether this array fits the idiom of a size-one tail padded
14881 /// array member of a struct.
14882 ///
14883 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14884 /// commonly used to emulate flexible arrays in C89 code.
14885 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14886                                     const NamedDecl *ND) {
14887   if (Size != 1 || !ND) return false;
14888 
14889   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14890   if (!FD) return false;
14891 
14892   // Don't consider sizes resulting from macro expansions or template argument
14893   // substitution to form C89 tail-padded arrays.
14894 
14895   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14896   while (TInfo) {
14897     TypeLoc TL = TInfo->getTypeLoc();
14898     // Look through typedefs.
14899     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14900       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14901       TInfo = TDL->getTypeSourceInfo();
14902       continue;
14903     }
14904     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14905       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14906       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14907         return false;
14908     }
14909     break;
14910   }
14911 
14912   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14913   if (!RD) return false;
14914   if (RD->isUnion()) return false;
14915   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14916     if (!CRD->isStandardLayout()) return false;
14917   }
14918 
14919   // See if this is the last field decl in the record.
14920   const Decl *D = FD;
14921   while ((D = D->getNextDeclInContext()))
14922     if (isa<FieldDecl>(D))
14923       return false;
14924   return true;
14925 }
14926 
14927 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14928                             const ArraySubscriptExpr *ASE,
14929                             bool AllowOnePastEnd, bool IndexNegated) {
14930   // Already diagnosed by the constant evaluator.
14931   if (isConstantEvaluated())
14932     return;
14933 
14934   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14935   if (IndexExpr->isValueDependent())
14936     return;
14937 
14938   const Type *EffectiveType =
14939       BaseExpr->getType()->getPointeeOrArrayElementType();
14940   BaseExpr = BaseExpr->IgnoreParenCasts();
14941   const ConstantArrayType *ArrayTy =
14942       Context.getAsConstantArrayType(BaseExpr->getType());
14943 
14944   const Type *BaseType =
14945       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14946   bool IsUnboundedArray = (BaseType == nullptr);
14947   if (EffectiveType->isDependentType() ||
14948       (!IsUnboundedArray && BaseType->isDependentType()))
14949     return;
14950 
14951   Expr::EvalResult Result;
14952   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14953     return;
14954 
14955   llvm::APSInt index = Result.Val.getInt();
14956   if (IndexNegated) {
14957     index.setIsUnsigned(false);
14958     index = -index;
14959   }
14960 
14961   const NamedDecl *ND = nullptr;
14962   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14963     ND = DRE->getDecl();
14964   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14965     ND = ME->getMemberDecl();
14966 
14967   if (IsUnboundedArray) {
14968     if (index.isUnsigned() || !index.isNegative()) {
14969       const auto &ASTC = getASTContext();
14970       unsigned AddrBits =
14971           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14972               EffectiveType->getCanonicalTypeInternal()));
14973       if (index.getBitWidth() < AddrBits)
14974         index = index.zext(AddrBits);
14975       Optional<CharUnits> ElemCharUnits =
14976           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14977       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14978       // pointer) bounds-checking isn't meaningful.
14979       if (!ElemCharUnits)
14980         return;
14981       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14982       // If index has more active bits than address space, we already know
14983       // we have a bounds violation to warn about.  Otherwise, compute
14984       // address of (index + 1)th element, and warn about bounds violation
14985       // only if that address exceeds address space.
14986       if (index.getActiveBits() <= AddrBits) {
14987         bool Overflow;
14988         llvm::APInt Product(index);
14989         Product += 1;
14990         Product = Product.umul_ov(ElemBytes, Overflow);
14991         if (!Overflow && Product.getActiveBits() <= AddrBits)
14992           return;
14993       }
14994 
14995       // Need to compute max possible elements in address space, since that
14996       // is included in diag message.
14997       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14998       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14999       MaxElems += 1;
15000       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
15001       MaxElems = MaxElems.udiv(ElemBytes);
15002 
15003       unsigned DiagID =
15004           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
15005               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
15006 
15007       // Diag message shows element size in bits and in "bytes" (platform-
15008       // dependent CharUnits)
15009       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15010                           PDiag(DiagID)
15011                               << toString(index, 10, true) << AddrBits
15012                               << (unsigned)ASTC.toBits(*ElemCharUnits)
15013                               << toString(ElemBytes, 10, false)
15014                               << toString(MaxElems, 10, false)
15015                               << (unsigned)MaxElems.getLimitedValue(~0U)
15016                               << IndexExpr->getSourceRange());
15017 
15018       if (!ND) {
15019         // Try harder to find a NamedDecl to point at in the note.
15020         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15021           BaseExpr = ASE->getBase()->IgnoreParenCasts();
15022         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15023           ND = DRE->getDecl();
15024         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15025           ND = ME->getMemberDecl();
15026       }
15027 
15028       if (ND)
15029         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15030                             PDiag(diag::note_array_declared_here) << ND);
15031     }
15032     return;
15033   }
15034 
15035   if (index.isUnsigned() || !index.isNegative()) {
15036     // It is possible that the type of the base expression after
15037     // IgnoreParenCasts is incomplete, even though the type of the base
15038     // expression before IgnoreParenCasts is complete (see PR39746 for an
15039     // example). In this case we have no information about whether the array
15040     // access exceeds the array bounds. However we can still diagnose an array
15041     // access which precedes the array bounds.
15042     if (BaseType->isIncompleteType())
15043       return;
15044 
15045     llvm::APInt size = ArrayTy->getSize();
15046     if (!size.isStrictlyPositive())
15047       return;
15048 
15049     if (BaseType != EffectiveType) {
15050       // Make sure we're comparing apples to apples when comparing index to size
15051       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15052       uint64_t array_typesize = Context.getTypeSize(BaseType);
15053       // Handle ptrarith_typesize being zero, such as when casting to void*
15054       if (!ptrarith_typesize) ptrarith_typesize = 1;
15055       if (ptrarith_typesize != array_typesize) {
15056         // There's a cast to a different size type involved
15057         uint64_t ratio = array_typesize / ptrarith_typesize;
15058         // TODO: Be smarter about handling cases where array_typesize is not a
15059         // multiple of ptrarith_typesize
15060         if (ptrarith_typesize * ratio == array_typesize)
15061           size *= llvm::APInt(size.getBitWidth(), ratio);
15062       }
15063     }
15064 
15065     if (size.getBitWidth() > index.getBitWidth())
15066       index = index.zext(size.getBitWidth());
15067     else if (size.getBitWidth() < index.getBitWidth())
15068       size = size.zext(index.getBitWidth());
15069 
15070     // For array subscripting the index must be less than size, but for pointer
15071     // arithmetic also allow the index (offset) to be equal to size since
15072     // computing the next address after the end of the array is legal and
15073     // commonly done e.g. in C++ iterators and range-based for loops.
15074     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15075       return;
15076 
15077     // Also don't warn for arrays of size 1 which are members of some
15078     // structure. These are often used to approximate flexible arrays in C89
15079     // code.
15080     if (IsTailPaddedMemberArray(*this, size, ND))
15081       return;
15082 
15083     // Suppress the warning if the subscript expression (as identified by the
15084     // ']' location) and the index expression are both from macro expansions
15085     // within a system header.
15086     if (ASE) {
15087       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15088           ASE->getRBracketLoc());
15089       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15090         SourceLocation IndexLoc =
15091             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15092         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15093           return;
15094       }
15095     }
15096 
15097     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15098                           : diag::warn_ptr_arith_exceeds_bounds;
15099 
15100     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15101                         PDiag(DiagID) << toString(index, 10, true)
15102                                       << toString(size, 10, true)
15103                                       << (unsigned)size.getLimitedValue(~0U)
15104                                       << IndexExpr->getSourceRange());
15105   } else {
15106     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15107     if (!ASE) {
15108       DiagID = diag::warn_ptr_arith_precedes_bounds;
15109       if (index.isNegative()) index = -index;
15110     }
15111 
15112     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15113                         PDiag(DiagID) << toString(index, 10, true)
15114                                       << IndexExpr->getSourceRange());
15115   }
15116 
15117   if (!ND) {
15118     // Try harder to find a NamedDecl to point at in the note.
15119     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15120       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15121     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15122       ND = DRE->getDecl();
15123     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15124       ND = ME->getMemberDecl();
15125   }
15126 
15127   if (ND)
15128     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15129                         PDiag(diag::note_array_declared_here) << ND);
15130 }
15131 
15132 void Sema::CheckArrayAccess(const Expr *expr) {
15133   int AllowOnePastEnd = 0;
15134   while (expr) {
15135     expr = expr->IgnoreParenImpCasts();
15136     switch (expr->getStmtClass()) {
15137       case Stmt::ArraySubscriptExprClass: {
15138         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15139         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15140                          AllowOnePastEnd > 0);
15141         expr = ASE->getBase();
15142         break;
15143       }
15144       case Stmt::MemberExprClass: {
15145         expr = cast<MemberExpr>(expr)->getBase();
15146         break;
15147       }
15148       case Stmt::OMPArraySectionExprClass: {
15149         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15150         if (ASE->getLowerBound())
15151           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15152                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15153         return;
15154       }
15155       case Stmt::UnaryOperatorClass: {
15156         // Only unwrap the * and & unary operators
15157         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15158         expr = UO->getSubExpr();
15159         switch (UO->getOpcode()) {
15160           case UO_AddrOf:
15161             AllowOnePastEnd++;
15162             break;
15163           case UO_Deref:
15164             AllowOnePastEnd--;
15165             break;
15166           default:
15167             return;
15168         }
15169         break;
15170       }
15171       case Stmt::ConditionalOperatorClass: {
15172         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15173         if (const Expr *lhs = cond->getLHS())
15174           CheckArrayAccess(lhs);
15175         if (const Expr *rhs = cond->getRHS())
15176           CheckArrayAccess(rhs);
15177         return;
15178       }
15179       case Stmt::CXXOperatorCallExprClass: {
15180         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15181         for (const auto *Arg : OCE->arguments())
15182           CheckArrayAccess(Arg);
15183         return;
15184       }
15185       default:
15186         return;
15187     }
15188   }
15189 }
15190 
15191 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15192 
15193 namespace {
15194 
15195 struct RetainCycleOwner {
15196   VarDecl *Variable = nullptr;
15197   SourceRange Range;
15198   SourceLocation Loc;
15199   bool Indirect = false;
15200 
15201   RetainCycleOwner() = default;
15202 
15203   void setLocsFrom(Expr *e) {
15204     Loc = e->getExprLoc();
15205     Range = e->getSourceRange();
15206   }
15207 };
15208 
15209 } // namespace
15210 
15211 /// Consider whether capturing the given variable can possibly lead to
15212 /// a retain cycle.
15213 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15214   // In ARC, it's captured strongly iff the variable has __strong
15215   // lifetime.  In MRR, it's captured strongly if the variable is
15216   // __block and has an appropriate type.
15217   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15218     return false;
15219 
15220   owner.Variable = var;
15221   if (ref)
15222     owner.setLocsFrom(ref);
15223   return true;
15224 }
15225 
15226 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15227   while (true) {
15228     e = e->IgnoreParens();
15229     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15230       switch (cast->getCastKind()) {
15231       case CK_BitCast:
15232       case CK_LValueBitCast:
15233       case CK_LValueToRValue:
15234       case CK_ARCReclaimReturnedObject:
15235         e = cast->getSubExpr();
15236         continue;
15237 
15238       default:
15239         return false;
15240       }
15241     }
15242 
15243     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15244       ObjCIvarDecl *ivar = ref->getDecl();
15245       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15246         return false;
15247 
15248       // Try to find a retain cycle in the base.
15249       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15250         return false;
15251 
15252       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15253       owner.Indirect = true;
15254       return true;
15255     }
15256 
15257     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15258       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15259       if (!var) return false;
15260       return considerVariable(var, ref, owner);
15261     }
15262 
15263     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15264       if (member->isArrow()) return false;
15265 
15266       // Don't count this as an indirect ownership.
15267       e = member->getBase();
15268       continue;
15269     }
15270 
15271     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15272       // Only pay attention to pseudo-objects on property references.
15273       ObjCPropertyRefExpr *pre
15274         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15275                                               ->IgnoreParens());
15276       if (!pre) return false;
15277       if (pre->isImplicitProperty()) return false;
15278       ObjCPropertyDecl *property = pre->getExplicitProperty();
15279       if (!property->isRetaining() &&
15280           !(property->getPropertyIvarDecl() &&
15281             property->getPropertyIvarDecl()->getType()
15282               .getObjCLifetime() == Qualifiers::OCL_Strong))
15283           return false;
15284 
15285       owner.Indirect = true;
15286       if (pre->isSuperReceiver()) {
15287         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15288         if (!owner.Variable)
15289           return false;
15290         owner.Loc = pre->getLocation();
15291         owner.Range = pre->getSourceRange();
15292         return true;
15293       }
15294       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15295                               ->getSourceExpr());
15296       continue;
15297     }
15298 
15299     // Array ivars?
15300 
15301     return false;
15302   }
15303 }
15304 
15305 namespace {
15306 
15307   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15308     ASTContext &Context;
15309     VarDecl *Variable;
15310     Expr *Capturer = nullptr;
15311     bool VarWillBeReased = false;
15312 
15313     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15314         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15315           Context(Context), Variable(variable) {}
15316 
15317     void VisitDeclRefExpr(DeclRefExpr *ref) {
15318       if (ref->getDecl() == Variable && !Capturer)
15319         Capturer = ref;
15320     }
15321 
15322     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15323       if (Capturer) return;
15324       Visit(ref->getBase());
15325       if (Capturer && ref->isFreeIvar())
15326         Capturer = ref;
15327     }
15328 
15329     void VisitBlockExpr(BlockExpr *block) {
15330       // Look inside nested blocks
15331       if (block->getBlockDecl()->capturesVariable(Variable))
15332         Visit(block->getBlockDecl()->getBody());
15333     }
15334 
15335     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15336       if (Capturer) return;
15337       if (OVE->getSourceExpr())
15338         Visit(OVE->getSourceExpr());
15339     }
15340 
15341     void VisitBinaryOperator(BinaryOperator *BinOp) {
15342       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15343         return;
15344       Expr *LHS = BinOp->getLHS();
15345       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15346         if (DRE->getDecl() != Variable)
15347           return;
15348         if (Expr *RHS = BinOp->getRHS()) {
15349           RHS = RHS->IgnoreParenCasts();
15350           Optional<llvm::APSInt> Value;
15351           VarWillBeReased =
15352               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15353                *Value == 0);
15354         }
15355       }
15356     }
15357   };
15358 
15359 } // namespace
15360 
15361 /// Check whether the given argument is a block which captures a
15362 /// variable.
15363 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15364   assert(owner.Variable && owner.Loc.isValid());
15365 
15366   e = e->IgnoreParenCasts();
15367 
15368   // Look through [^{...} copy] and Block_copy(^{...}).
15369   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15370     Selector Cmd = ME->getSelector();
15371     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15372       e = ME->getInstanceReceiver();
15373       if (!e)
15374         return nullptr;
15375       e = e->IgnoreParenCasts();
15376     }
15377   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15378     if (CE->getNumArgs() == 1) {
15379       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15380       if (Fn) {
15381         const IdentifierInfo *FnI = Fn->getIdentifier();
15382         if (FnI && FnI->isStr("_Block_copy")) {
15383           e = CE->getArg(0)->IgnoreParenCasts();
15384         }
15385       }
15386     }
15387   }
15388 
15389   BlockExpr *block = dyn_cast<BlockExpr>(e);
15390   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15391     return nullptr;
15392 
15393   FindCaptureVisitor visitor(S.Context, owner.Variable);
15394   visitor.Visit(block->getBlockDecl()->getBody());
15395   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15396 }
15397 
15398 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15399                                 RetainCycleOwner &owner) {
15400   assert(capturer);
15401   assert(owner.Variable && owner.Loc.isValid());
15402 
15403   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15404     << owner.Variable << capturer->getSourceRange();
15405   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15406     << owner.Indirect << owner.Range;
15407 }
15408 
15409 /// Check for a keyword selector that starts with the word 'add' or
15410 /// 'set'.
15411 static bool isSetterLikeSelector(Selector sel) {
15412   if (sel.isUnarySelector()) return false;
15413 
15414   StringRef str = sel.getNameForSlot(0);
15415   while (!str.empty() && str.front() == '_') str = str.substr(1);
15416   if (str.startswith("set"))
15417     str = str.substr(3);
15418   else if (str.startswith("add")) {
15419     // Specially allow 'addOperationWithBlock:'.
15420     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15421       return false;
15422     str = str.substr(3);
15423   }
15424   else
15425     return false;
15426 
15427   if (str.empty()) return true;
15428   return !isLowercase(str.front());
15429 }
15430 
15431 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15432                                                     ObjCMessageExpr *Message) {
15433   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15434                                                 Message->getReceiverInterface(),
15435                                                 NSAPI::ClassId_NSMutableArray);
15436   if (!IsMutableArray) {
15437     return None;
15438   }
15439 
15440   Selector Sel = Message->getSelector();
15441 
15442   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15443     S.NSAPIObj->getNSArrayMethodKind(Sel);
15444   if (!MKOpt) {
15445     return None;
15446   }
15447 
15448   NSAPI::NSArrayMethodKind MK = *MKOpt;
15449 
15450   switch (MK) {
15451     case NSAPI::NSMutableArr_addObject:
15452     case NSAPI::NSMutableArr_insertObjectAtIndex:
15453     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15454       return 0;
15455     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15456       return 1;
15457 
15458     default:
15459       return None;
15460   }
15461 
15462   return None;
15463 }
15464 
15465 static
15466 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15467                                                   ObjCMessageExpr *Message) {
15468   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15469                                             Message->getReceiverInterface(),
15470                                             NSAPI::ClassId_NSMutableDictionary);
15471   if (!IsMutableDictionary) {
15472     return None;
15473   }
15474 
15475   Selector Sel = Message->getSelector();
15476 
15477   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15478     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15479   if (!MKOpt) {
15480     return None;
15481   }
15482 
15483   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15484 
15485   switch (MK) {
15486     case NSAPI::NSMutableDict_setObjectForKey:
15487     case NSAPI::NSMutableDict_setValueForKey:
15488     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15489       return 0;
15490 
15491     default:
15492       return None;
15493   }
15494 
15495   return None;
15496 }
15497 
15498 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15499   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15500                                                 Message->getReceiverInterface(),
15501                                                 NSAPI::ClassId_NSMutableSet);
15502 
15503   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15504                                             Message->getReceiverInterface(),
15505                                             NSAPI::ClassId_NSMutableOrderedSet);
15506   if (!IsMutableSet && !IsMutableOrderedSet) {
15507     return None;
15508   }
15509 
15510   Selector Sel = Message->getSelector();
15511 
15512   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15513   if (!MKOpt) {
15514     return None;
15515   }
15516 
15517   NSAPI::NSSetMethodKind MK = *MKOpt;
15518 
15519   switch (MK) {
15520     case NSAPI::NSMutableSet_addObject:
15521     case NSAPI::NSOrderedSet_setObjectAtIndex:
15522     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15523     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15524       return 0;
15525     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15526       return 1;
15527   }
15528 
15529   return None;
15530 }
15531 
15532 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15533   if (!Message->isInstanceMessage()) {
15534     return;
15535   }
15536 
15537   Optional<int> ArgOpt;
15538 
15539   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15540       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15541       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15542     return;
15543   }
15544 
15545   int ArgIndex = *ArgOpt;
15546 
15547   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15548   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15549     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15550   }
15551 
15552   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15553     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15554       if (ArgRE->isObjCSelfExpr()) {
15555         Diag(Message->getSourceRange().getBegin(),
15556              diag::warn_objc_circular_container)
15557           << ArgRE->getDecl() << StringRef("'super'");
15558       }
15559     }
15560   } else {
15561     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15562 
15563     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15564       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15565     }
15566 
15567     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15568       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15569         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15570           ValueDecl *Decl = ReceiverRE->getDecl();
15571           Diag(Message->getSourceRange().getBegin(),
15572                diag::warn_objc_circular_container)
15573             << Decl << Decl;
15574           if (!ArgRE->isObjCSelfExpr()) {
15575             Diag(Decl->getLocation(),
15576                  diag::note_objc_circular_container_declared_here)
15577               << Decl;
15578           }
15579         }
15580       }
15581     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15582       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15583         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15584           ObjCIvarDecl *Decl = IvarRE->getDecl();
15585           Diag(Message->getSourceRange().getBegin(),
15586                diag::warn_objc_circular_container)
15587             << Decl << Decl;
15588           Diag(Decl->getLocation(),
15589                diag::note_objc_circular_container_declared_here)
15590             << Decl;
15591         }
15592       }
15593     }
15594   }
15595 }
15596 
15597 /// Check a message send to see if it's likely to cause a retain cycle.
15598 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15599   // Only check instance methods whose selector looks like a setter.
15600   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15601     return;
15602 
15603   // Try to find a variable that the receiver is strongly owned by.
15604   RetainCycleOwner owner;
15605   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15606     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15607       return;
15608   } else {
15609     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15610     owner.Variable = getCurMethodDecl()->getSelfDecl();
15611     owner.Loc = msg->getSuperLoc();
15612     owner.Range = msg->getSuperLoc();
15613   }
15614 
15615   // Check whether the receiver is captured by any of the arguments.
15616   const ObjCMethodDecl *MD = msg->getMethodDecl();
15617   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15618     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15619       // noescape blocks should not be retained by the method.
15620       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15621         continue;
15622       return diagnoseRetainCycle(*this, capturer, owner);
15623     }
15624   }
15625 }
15626 
15627 /// Check a property assign to see if it's likely to cause a retain cycle.
15628 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15629   RetainCycleOwner owner;
15630   if (!findRetainCycleOwner(*this, receiver, owner))
15631     return;
15632 
15633   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15634     diagnoseRetainCycle(*this, capturer, owner);
15635 }
15636 
15637 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15638   RetainCycleOwner Owner;
15639   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15640     return;
15641 
15642   // Because we don't have an expression for the variable, we have to set the
15643   // location explicitly here.
15644   Owner.Loc = Var->getLocation();
15645   Owner.Range = Var->getSourceRange();
15646 
15647   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15648     diagnoseRetainCycle(*this, Capturer, Owner);
15649 }
15650 
15651 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15652                                      Expr *RHS, bool isProperty) {
15653   // Check if RHS is an Objective-C object literal, which also can get
15654   // immediately zapped in a weak reference.  Note that we explicitly
15655   // allow ObjCStringLiterals, since those are designed to never really die.
15656   RHS = RHS->IgnoreParenImpCasts();
15657 
15658   // This enum needs to match with the 'select' in
15659   // warn_objc_arc_literal_assign (off-by-1).
15660   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15661   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15662     return false;
15663 
15664   S.Diag(Loc, diag::warn_arc_literal_assign)
15665     << (unsigned) Kind
15666     << (isProperty ? 0 : 1)
15667     << RHS->getSourceRange();
15668 
15669   return true;
15670 }
15671 
15672 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15673                                     Qualifiers::ObjCLifetime LT,
15674                                     Expr *RHS, bool isProperty) {
15675   // Strip off any implicit cast added to get to the one ARC-specific.
15676   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15677     if (cast->getCastKind() == CK_ARCConsumeObject) {
15678       S.Diag(Loc, diag::warn_arc_retained_assign)
15679         << (LT == Qualifiers::OCL_ExplicitNone)
15680         << (isProperty ? 0 : 1)
15681         << RHS->getSourceRange();
15682       return true;
15683     }
15684     RHS = cast->getSubExpr();
15685   }
15686 
15687   if (LT == Qualifiers::OCL_Weak &&
15688       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15689     return true;
15690 
15691   return false;
15692 }
15693 
15694 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15695                               QualType LHS, Expr *RHS) {
15696   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15697 
15698   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15699     return false;
15700 
15701   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15702     return true;
15703 
15704   return false;
15705 }
15706 
15707 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15708                               Expr *LHS, Expr *RHS) {
15709   QualType LHSType;
15710   // PropertyRef on LHS type need be directly obtained from
15711   // its declaration as it has a PseudoType.
15712   ObjCPropertyRefExpr *PRE
15713     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15714   if (PRE && !PRE->isImplicitProperty()) {
15715     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15716     if (PD)
15717       LHSType = PD->getType();
15718   }
15719 
15720   if (LHSType.isNull())
15721     LHSType = LHS->getType();
15722 
15723   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15724 
15725   if (LT == Qualifiers::OCL_Weak) {
15726     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15727       getCurFunction()->markSafeWeakUse(LHS);
15728   }
15729 
15730   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15731     return;
15732 
15733   // FIXME. Check for other life times.
15734   if (LT != Qualifiers::OCL_None)
15735     return;
15736 
15737   if (PRE) {
15738     if (PRE->isImplicitProperty())
15739       return;
15740     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15741     if (!PD)
15742       return;
15743 
15744     unsigned Attributes = PD->getPropertyAttributes();
15745     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15746       // when 'assign' attribute was not explicitly specified
15747       // by user, ignore it and rely on property type itself
15748       // for lifetime info.
15749       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15750       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15751           LHSType->isObjCRetainableType())
15752         return;
15753 
15754       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15755         if (cast->getCastKind() == CK_ARCConsumeObject) {
15756           Diag(Loc, diag::warn_arc_retained_property_assign)
15757           << RHS->getSourceRange();
15758           return;
15759         }
15760         RHS = cast->getSubExpr();
15761       }
15762     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15763       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15764         return;
15765     }
15766   }
15767 }
15768 
15769 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15770 
15771 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15772                                         SourceLocation StmtLoc,
15773                                         const NullStmt *Body) {
15774   // Do not warn if the body is a macro that expands to nothing, e.g:
15775   //
15776   // #define CALL(x)
15777   // if (condition)
15778   //   CALL(0);
15779   if (Body->hasLeadingEmptyMacro())
15780     return false;
15781 
15782   // Get line numbers of statement and body.
15783   bool StmtLineInvalid;
15784   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15785                                                       &StmtLineInvalid);
15786   if (StmtLineInvalid)
15787     return false;
15788 
15789   bool BodyLineInvalid;
15790   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15791                                                       &BodyLineInvalid);
15792   if (BodyLineInvalid)
15793     return false;
15794 
15795   // Warn if null statement and body are on the same line.
15796   if (StmtLine != BodyLine)
15797     return false;
15798 
15799   return true;
15800 }
15801 
15802 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15803                                  const Stmt *Body,
15804                                  unsigned DiagID) {
15805   // Since this is a syntactic check, don't emit diagnostic for template
15806   // instantiations, this just adds noise.
15807   if (CurrentInstantiationScope)
15808     return;
15809 
15810   // The body should be a null statement.
15811   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15812   if (!NBody)
15813     return;
15814 
15815   // Do the usual checks.
15816   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15817     return;
15818 
15819   Diag(NBody->getSemiLoc(), DiagID);
15820   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15821 }
15822 
15823 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15824                                  const Stmt *PossibleBody) {
15825   assert(!CurrentInstantiationScope); // Ensured by caller
15826 
15827   SourceLocation StmtLoc;
15828   const Stmt *Body;
15829   unsigned DiagID;
15830   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15831     StmtLoc = FS->getRParenLoc();
15832     Body = FS->getBody();
15833     DiagID = diag::warn_empty_for_body;
15834   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15835     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15836     Body = WS->getBody();
15837     DiagID = diag::warn_empty_while_body;
15838   } else
15839     return; // Neither `for' nor `while'.
15840 
15841   // The body should be a null statement.
15842   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15843   if (!NBody)
15844     return;
15845 
15846   // Skip expensive checks if diagnostic is disabled.
15847   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15848     return;
15849 
15850   // Do the usual checks.
15851   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15852     return;
15853 
15854   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15855   // noise level low, emit diagnostics only if for/while is followed by a
15856   // CompoundStmt, e.g.:
15857   //    for (int i = 0; i < n; i++);
15858   //    {
15859   //      a(i);
15860   //    }
15861   // or if for/while is followed by a statement with more indentation
15862   // than for/while itself:
15863   //    for (int i = 0; i < n; i++);
15864   //      a(i);
15865   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15866   if (!ProbableTypo) {
15867     bool BodyColInvalid;
15868     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15869         PossibleBody->getBeginLoc(), &BodyColInvalid);
15870     if (BodyColInvalid)
15871       return;
15872 
15873     bool StmtColInvalid;
15874     unsigned StmtCol =
15875         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15876     if (StmtColInvalid)
15877       return;
15878 
15879     if (BodyCol > StmtCol)
15880       ProbableTypo = true;
15881   }
15882 
15883   if (ProbableTypo) {
15884     Diag(NBody->getSemiLoc(), DiagID);
15885     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15886   }
15887 }
15888 
15889 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15890 
15891 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15892 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15893                              SourceLocation OpLoc) {
15894   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15895     return;
15896 
15897   if (inTemplateInstantiation())
15898     return;
15899 
15900   // Strip parens and casts away.
15901   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15902   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15903 
15904   // Check for a call expression
15905   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15906   if (!CE || CE->getNumArgs() != 1)
15907     return;
15908 
15909   // Check for a call to std::move
15910   if (!CE->isCallToStdMove())
15911     return;
15912 
15913   // Get argument from std::move
15914   RHSExpr = CE->getArg(0);
15915 
15916   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15917   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15918 
15919   // Two DeclRefExpr's, check that the decls are the same.
15920   if (LHSDeclRef && RHSDeclRef) {
15921     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15922       return;
15923     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15924         RHSDeclRef->getDecl()->getCanonicalDecl())
15925       return;
15926 
15927     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15928                                         << LHSExpr->getSourceRange()
15929                                         << RHSExpr->getSourceRange();
15930     return;
15931   }
15932 
15933   // Member variables require a different approach to check for self moves.
15934   // MemberExpr's are the same if every nested MemberExpr refers to the same
15935   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15936   // the base Expr's are CXXThisExpr's.
15937   const Expr *LHSBase = LHSExpr;
15938   const Expr *RHSBase = RHSExpr;
15939   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15940   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15941   if (!LHSME || !RHSME)
15942     return;
15943 
15944   while (LHSME && RHSME) {
15945     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15946         RHSME->getMemberDecl()->getCanonicalDecl())
15947       return;
15948 
15949     LHSBase = LHSME->getBase();
15950     RHSBase = RHSME->getBase();
15951     LHSME = dyn_cast<MemberExpr>(LHSBase);
15952     RHSME = dyn_cast<MemberExpr>(RHSBase);
15953   }
15954 
15955   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15956   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15957   if (LHSDeclRef && RHSDeclRef) {
15958     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15959       return;
15960     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15961         RHSDeclRef->getDecl()->getCanonicalDecl())
15962       return;
15963 
15964     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15965                                         << LHSExpr->getSourceRange()
15966                                         << RHSExpr->getSourceRange();
15967     return;
15968   }
15969 
15970   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15971     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15972                                         << LHSExpr->getSourceRange()
15973                                         << RHSExpr->getSourceRange();
15974 }
15975 
15976 //===--- Layout compatibility ----------------------------------------------//
15977 
15978 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15979 
15980 /// Check if two enumeration types are layout-compatible.
15981 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15982   // C++11 [dcl.enum] p8:
15983   // Two enumeration types are layout-compatible if they have the same
15984   // underlying type.
15985   return ED1->isComplete() && ED2->isComplete() &&
15986          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15987 }
15988 
15989 /// Check if two fields are layout-compatible.
15990 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15991                                FieldDecl *Field2) {
15992   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15993     return false;
15994 
15995   if (Field1->isBitField() != Field2->isBitField())
15996     return false;
15997 
15998   if (Field1->isBitField()) {
15999     // Make sure that the bit-fields are the same length.
16000     unsigned Bits1 = Field1->getBitWidthValue(C);
16001     unsigned Bits2 = Field2->getBitWidthValue(C);
16002 
16003     if (Bits1 != Bits2)
16004       return false;
16005   }
16006 
16007   return true;
16008 }
16009 
16010 /// Check if two standard-layout structs are layout-compatible.
16011 /// (C++11 [class.mem] p17)
16012 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
16013                                      RecordDecl *RD2) {
16014   // If both records are C++ classes, check that base classes match.
16015   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
16016     // If one of records is a CXXRecordDecl we are in C++ mode,
16017     // thus the other one is a CXXRecordDecl, too.
16018     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
16019     // Check number of base classes.
16020     if (D1CXX->getNumBases() != D2CXX->getNumBases())
16021       return false;
16022 
16023     // Check the base classes.
16024     for (CXXRecordDecl::base_class_const_iterator
16025                Base1 = D1CXX->bases_begin(),
16026            BaseEnd1 = D1CXX->bases_end(),
16027               Base2 = D2CXX->bases_begin();
16028          Base1 != BaseEnd1;
16029          ++Base1, ++Base2) {
16030       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16031         return false;
16032     }
16033   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16034     // If only RD2 is a C++ class, it should have zero base classes.
16035     if (D2CXX->getNumBases() > 0)
16036       return false;
16037   }
16038 
16039   // Check the fields.
16040   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16041                              Field2End = RD2->field_end(),
16042                              Field1 = RD1->field_begin(),
16043                              Field1End = RD1->field_end();
16044   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16045     if (!isLayoutCompatible(C, *Field1, *Field2))
16046       return false;
16047   }
16048   if (Field1 != Field1End || Field2 != Field2End)
16049     return false;
16050 
16051   return true;
16052 }
16053 
16054 /// Check if two standard-layout unions are layout-compatible.
16055 /// (C++11 [class.mem] p18)
16056 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16057                                     RecordDecl *RD2) {
16058   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16059   for (auto *Field2 : RD2->fields())
16060     UnmatchedFields.insert(Field2);
16061 
16062   for (auto *Field1 : RD1->fields()) {
16063     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16064         I = UnmatchedFields.begin(),
16065         E = UnmatchedFields.end();
16066 
16067     for ( ; I != E; ++I) {
16068       if (isLayoutCompatible(C, Field1, *I)) {
16069         bool Result = UnmatchedFields.erase(*I);
16070         (void) Result;
16071         assert(Result);
16072         break;
16073       }
16074     }
16075     if (I == E)
16076       return false;
16077   }
16078 
16079   return UnmatchedFields.empty();
16080 }
16081 
16082 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16083                                RecordDecl *RD2) {
16084   if (RD1->isUnion() != RD2->isUnion())
16085     return false;
16086 
16087   if (RD1->isUnion())
16088     return isLayoutCompatibleUnion(C, RD1, RD2);
16089   else
16090     return isLayoutCompatibleStruct(C, RD1, RD2);
16091 }
16092 
16093 /// Check if two types are layout-compatible in C++11 sense.
16094 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16095   if (T1.isNull() || T2.isNull())
16096     return false;
16097 
16098   // C++11 [basic.types] p11:
16099   // If two types T1 and T2 are the same type, then T1 and T2 are
16100   // layout-compatible types.
16101   if (C.hasSameType(T1, T2))
16102     return true;
16103 
16104   T1 = T1.getCanonicalType().getUnqualifiedType();
16105   T2 = T2.getCanonicalType().getUnqualifiedType();
16106 
16107   const Type::TypeClass TC1 = T1->getTypeClass();
16108   const Type::TypeClass TC2 = T2->getTypeClass();
16109 
16110   if (TC1 != TC2)
16111     return false;
16112 
16113   if (TC1 == Type::Enum) {
16114     return isLayoutCompatible(C,
16115                               cast<EnumType>(T1)->getDecl(),
16116                               cast<EnumType>(T2)->getDecl());
16117   } else if (TC1 == Type::Record) {
16118     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16119       return false;
16120 
16121     return isLayoutCompatible(C,
16122                               cast<RecordType>(T1)->getDecl(),
16123                               cast<RecordType>(T2)->getDecl());
16124   }
16125 
16126   return false;
16127 }
16128 
16129 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16130 
16131 /// Given a type tag expression find the type tag itself.
16132 ///
16133 /// \param TypeExpr Type tag expression, as it appears in user's code.
16134 ///
16135 /// \param VD Declaration of an identifier that appears in a type tag.
16136 ///
16137 /// \param MagicValue Type tag magic value.
16138 ///
16139 /// \param isConstantEvaluated whether the evalaution should be performed in
16140 
16141 /// constant context.
16142 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16143                             const ValueDecl **VD, uint64_t *MagicValue,
16144                             bool isConstantEvaluated) {
16145   while(true) {
16146     if (!TypeExpr)
16147       return false;
16148 
16149     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16150 
16151     switch (TypeExpr->getStmtClass()) {
16152     case Stmt::UnaryOperatorClass: {
16153       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16154       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16155         TypeExpr = UO->getSubExpr();
16156         continue;
16157       }
16158       return false;
16159     }
16160 
16161     case Stmt::DeclRefExprClass: {
16162       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16163       *VD = DRE->getDecl();
16164       return true;
16165     }
16166 
16167     case Stmt::IntegerLiteralClass: {
16168       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16169       llvm::APInt MagicValueAPInt = IL->getValue();
16170       if (MagicValueAPInt.getActiveBits() <= 64) {
16171         *MagicValue = MagicValueAPInt.getZExtValue();
16172         return true;
16173       } else
16174         return false;
16175     }
16176 
16177     case Stmt::BinaryConditionalOperatorClass:
16178     case Stmt::ConditionalOperatorClass: {
16179       const AbstractConditionalOperator *ACO =
16180           cast<AbstractConditionalOperator>(TypeExpr);
16181       bool Result;
16182       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16183                                                      isConstantEvaluated)) {
16184         if (Result)
16185           TypeExpr = ACO->getTrueExpr();
16186         else
16187           TypeExpr = ACO->getFalseExpr();
16188         continue;
16189       }
16190       return false;
16191     }
16192 
16193     case Stmt::BinaryOperatorClass: {
16194       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16195       if (BO->getOpcode() == BO_Comma) {
16196         TypeExpr = BO->getRHS();
16197         continue;
16198       }
16199       return false;
16200     }
16201 
16202     default:
16203       return false;
16204     }
16205   }
16206 }
16207 
16208 /// Retrieve the C type corresponding to type tag TypeExpr.
16209 ///
16210 /// \param TypeExpr Expression that specifies a type tag.
16211 ///
16212 /// \param MagicValues Registered magic values.
16213 ///
16214 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16215 ///        kind.
16216 ///
16217 /// \param TypeInfo Information about the corresponding C type.
16218 ///
16219 /// \param isConstantEvaluated whether the evalaution should be performed in
16220 /// constant context.
16221 ///
16222 /// \returns true if the corresponding C type was found.
16223 static bool GetMatchingCType(
16224     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16225     const ASTContext &Ctx,
16226     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16227         *MagicValues,
16228     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16229     bool isConstantEvaluated) {
16230   FoundWrongKind = false;
16231 
16232   // Variable declaration that has type_tag_for_datatype attribute.
16233   const ValueDecl *VD = nullptr;
16234 
16235   uint64_t MagicValue;
16236 
16237   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16238     return false;
16239 
16240   if (VD) {
16241     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16242       if (I->getArgumentKind() != ArgumentKind) {
16243         FoundWrongKind = true;
16244         return false;
16245       }
16246       TypeInfo.Type = I->getMatchingCType();
16247       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16248       TypeInfo.MustBeNull = I->getMustBeNull();
16249       return true;
16250     }
16251     return false;
16252   }
16253 
16254   if (!MagicValues)
16255     return false;
16256 
16257   llvm::DenseMap<Sema::TypeTagMagicValue,
16258                  Sema::TypeTagData>::const_iterator I =
16259       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16260   if (I == MagicValues->end())
16261     return false;
16262 
16263   TypeInfo = I->second;
16264   return true;
16265 }
16266 
16267 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16268                                       uint64_t MagicValue, QualType Type,
16269                                       bool LayoutCompatible,
16270                                       bool MustBeNull) {
16271   if (!TypeTagForDatatypeMagicValues)
16272     TypeTagForDatatypeMagicValues.reset(
16273         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16274 
16275   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16276   (*TypeTagForDatatypeMagicValues)[Magic] =
16277       TypeTagData(Type, LayoutCompatible, MustBeNull);
16278 }
16279 
16280 static bool IsSameCharType(QualType T1, QualType T2) {
16281   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16282   if (!BT1)
16283     return false;
16284 
16285   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16286   if (!BT2)
16287     return false;
16288 
16289   BuiltinType::Kind T1Kind = BT1->getKind();
16290   BuiltinType::Kind T2Kind = BT2->getKind();
16291 
16292   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16293          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16294          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16295          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16296 }
16297 
16298 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16299                                     const ArrayRef<const Expr *> ExprArgs,
16300                                     SourceLocation CallSiteLoc) {
16301   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16302   bool IsPointerAttr = Attr->getIsPointer();
16303 
16304   // Retrieve the argument representing the 'type_tag'.
16305   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16306   if (TypeTagIdxAST >= ExprArgs.size()) {
16307     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16308         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16309     return;
16310   }
16311   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16312   bool FoundWrongKind;
16313   TypeTagData TypeInfo;
16314   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16315                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16316                         TypeInfo, isConstantEvaluated())) {
16317     if (FoundWrongKind)
16318       Diag(TypeTagExpr->getExprLoc(),
16319            diag::warn_type_tag_for_datatype_wrong_kind)
16320         << TypeTagExpr->getSourceRange();
16321     return;
16322   }
16323 
16324   // Retrieve the argument representing the 'arg_idx'.
16325   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16326   if (ArgumentIdxAST >= ExprArgs.size()) {
16327     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16328         << 1 << Attr->getArgumentIdx().getSourceIndex();
16329     return;
16330   }
16331   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16332   if (IsPointerAttr) {
16333     // Skip implicit cast of pointer to `void *' (as a function argument).
16334     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16335       if (ICE->getType()->isVoidPointerType() &&
16336           ICE->getCastKind() == CK_BitCast)
16337         ArgumentExpr = ICE->getSubExpr();
16338   }
16339   QualType ArgumentType = ArgumentExpr->getType();
16340 
16341   // Passing a `void*' pointer shouldn't trigger a warning.
16342   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16343     return;
16344 
16345   if (TypeInfo.MustBeNull) {
16346     // Type tag with matching void type requires a null pointer.
16347     if (!ArgumentExpr->isNullPointerConstant(Context,
16348                                              Expr::NPC_ValueDependentIsNotNull)) {
16349       Diag(ArgumentExpr->getExprLoc(),
16350            diag::warn_type_safety_null_pointer_required)
16351           << ArgumentKind->getName()
16352           << ArgumentExpr->getSourceRange()
16353           << TypeTagExpr->getSourceRange();
16354     }
16355     return;
16356   }
16357 
16358   QualType RequiredType = TypeInfo.Type;
16359   if (IsPointerAttr)
16360     RequiredType = Context.getPointerType(RequiredType);
16361 
16362   bool mismatch = false;
16363   if (!TypeInfo.LayoutCompatible) {
16364     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16365 
16366     // C++11 [basic.fundamental] p1:
16367     // Plain char, signed char, and unsigned char are three distinct types.
16368     //
16369     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16370     // char' depending on the current char signedness mode.
16371     if (mismatch)
16372       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16373                                            RequiredType->getPointeeType())) ||
16374           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16375         mismatch = false;
16376   } else
16377     if (IsPointerAttr)
16378       mismatch = !isLayoutCompatible(Context,
16379                                      ArgumentType->getPointeeType(),
16380                                      RequiredType->getPointeeType());
16381     else
16382       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16383 
16384   if (mismatch)
16385     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16386         << ArgumentType << ArgumentKind
16387         << TypeInfo.LayoutCompatible << RequiredType
16388         << ArgumentExpr->getSourceRange()
16389         << TypeTagExpr->getSourceRange();
16390 }
16391 
16392 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16393                                          CharUnits Alignment) {
16394   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16395 }
16396 
16397 void Sema::DiagnoseMisalignedMembers() {
16398   for (MisalignedMember &m : MisalignedMembers) {
16399     const NamedDecl *ND = m.RD;
16400     if (ND->getName().empty()) {
16401       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16402         ND = TD;
16403     }
16404     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16405         << m.MD << ND << m.E->getSourceRange();
16406   }
16407   MisalignedMembers.clear();
16408 }
16409 
16410 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16411   E = E->IgnoreParens();
16412   if (!T->isPointerType() && !T->isIntegerType())
16413     return;
16414   if (isa<UnaryOperator>(E) &&
16415       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16416     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16417     if (isa<MemberExpr>(Op)) {
16418       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16419       if (MA != MisalignedMembers.end() &&
16420           (T->isIntegerType() ||
16421            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16422                                    Context.getTypeAlignInChars(
16423                                        T->getPointeeType()) <= MA->Alignment))))
16424         MisalignedMembers.erase(MA);
16425     }
16426   }
16427 }
16428 
16429 void Sema::RefersToMemberWithReducedAlignment(
16430     Expr *E,
16431     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16432         Action) {
16433   const auto *ME = dyn_cast<MemberExpr>(E);
16434   if (!ME)
16435     return;
16436 
16437   // No need to check expressions with an __unaligned-qualified type.
16438   if (E->getType().getQualifiers().hasUnaligned())
16439     return;
16440 
16441   // For a chain of MemberExpr like "a.b.c.d" this list
16442   // will keep FieldDecl's like [d, c, b].
16443   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16444   const MemberExpr *TopME = nullptr;
16445   bool AnyIsPacked = false;
16446   do {
16447     QualType BaseType = ME->getBase()->getType();
16448     if (BaseType->isDependentType())
16449       return;
16450     if (ME->isArrow())
16451       BaseType = BaseType->getPointeeType();
16452     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16453     if (RD->isInvalidDecl())
16454       return;
16455 
16456     ValueDecl *MD = ME->getMemberDecl();
16457     auto *FD = dyn_cast<FieldDecl>(MD);
16458     // We do not care about non-data members.
16459     if (!FD || FD->isInvalidDecl())
16460       return;
16461 
16462     AnyIsPacked =
16463         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16464     ReverseMemberChain.push_back(FD);
16465 
16466     TopME = ME;
16467     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16468   } while (ME);
16469   assert(TopME && "We did not compute a topmost MemberExpr!");
16470 
16471   // Not the scope of this diagnostic.
16472   if (!AnyIsPacked)
16473     return;
16474 
16475   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16476   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16477   // TODO: The innermost base of the member expression may be too complicated.
16478   // For now, just disregard these cases. This is left for future
16479   // improvement.
16480   if (!DRE && !isa<CXXThisExpr>(TopBase))
16481       return;
16482 
16483   // Alignment expected by the whole expression.
16484   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16485 
16486   // No need to do anything else with this case.
16487   if (ExpectedAlignment.isOne())
16488     return;
16489 
16490   // Synthesize offset of the whole access.
16491   CharUnits Offset;
16492   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16493        I++) {
16494     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16495   }
16496 
16497   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16498   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16499       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16500 
16501   // The base expression of the innermost MemberExpr may give
16502   // stronger guarantees than the class containing the member.
16503   if (DRE && !TopME->isArrow()) {
16504     const ValueDecl *VD = DRE->getDecl();
16505     if (!VD->getType()->isReferenceType())
16506       CompleteObjectAlignment =
16507           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16508   }
16509 
16510   // Check if the synthesized offset fulfills the alignment.
16511   if (Offset % ExpectedAlignment != 0 ||
16512       // It may fulfill the offset it but the effective alignment may still be
16513       // lower than the expected expression alignment.
16514       CompleteObjectAlignment < ExpectedAlignment) {
16515     // If this happens, we want to determine a sensible culprit of this.
16516     // Intuitively, watching the chain of member expressions from right to
16517     // left, we start with the required alignment (as required by the field
16518     // type) but some packed attribute in that chain has reduced the alignment.
16519     // It may happen that another packed structure increases it again. But if
16520     // we are here such increase has not been enough. So pointing the first
16521     // FieldDecl that either is packed or else its RecordDecl is,
16522     // seems reasonable.
16523     FieldDecl *FD = nullptr;
16524     CharUnits Alignment;
16525     for (FieldDecl *FDI : ReverseMemberChain) {
16526       if (FDI->hasAttr<PackedAttr>() ||
16527           FDI->getParent()->hasAttr<PackedAttr>()) {
16528         FD = FDI;
16529         Alignment = std::min(
16530             Context.getTypeAlignInChars(FD->getType()),
16531             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16532         break;
16533       }
16534     }
16535     assert(FD && "We did not find a packed FieldDecl!");
16536     Action(E, FD->getParent(), FD, Alignment);
16537   }
16538 }
16539 
16540 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16541   using namespace std::placeholders;
16542 
16543   RefersToMemberWithReducedAlignment(
16544       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16545                      _2, _3, _4));
16546 }
16547 
16548 // Check if \p Ty is a valid type for the elementwise math builtins. If it is
16549 // not a valid type, emit an error message and return true. Otherwise return
16550 // false.
16551 static bool checkMathBuiltinElementType(Sema &S, SourceLocation Loc,
16552                                         QualType Ty) {
16553   if (!Ty->getAs<VectorType>() && !ConstantMatrixType::isValidElementType(Ty)) {
16554     S.Diag(Loc, diag::err_builtin_invalid_arg_type)
16555         << 1 << /* vector, integer or float ty*/ 0 << Ty;
16556     return true;
16557   }
16558   return false;
16559 }
16560 
16561 bool Sema::SemaBuiltinElementwiseMathOneArg(CallExpr *TheCall) {
16562   if (checkArgCount(*this, TheCall, 1))
16563     return true;
16564 
16565   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16566   SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16567   if (A.isInvalid())
16568     return true;
16569 
16570   TheCall->setArg(0, A.get());
16571   QualType TyA = A.get()->getType();
16572   if (checkMathBuiltinElementType(*this, ArgLoc, TyA))
16573     return true;
16574 
16575   QualType EltTy = TyA;
16576   if (auto *VecTy = EltTy->getAs<VectorType>())
16577     EltTy = VecTy->getElementType();
16578   if (EltTy->isUnsignedIntegerType())
16579     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16580            << 1 << /*signed integer or float ty*/ 3 << TyA;
16581 
16582   TheCall->setType(TyA);
16583   return false;
16584 }
16585 
16586 bool Sema::SemaBuiltinElementwiseMath(CallExpr *TheCall) {
16587   if (checkArgCount(*this, TheCall, 2))
16588     return true;
16589 
16590   ExprResult A = TheCall->getArg(0);
16591   ExprResult B = TheCall->getArg(1);
16592   // Do standard promotions between the two arguments, returning their common
16593   // type.
16594   QualType Res =
16595       UsualArithmeticConversions(A, B, TheCall->getExprLoc(), ACK_Comparison);
16596   if (A.isInvalid() || B.isInvalid())
16597     return true;
16598 
16599   QualType TyA = A.get()->getType();
16600   QualType TyB = B.get()->getType();
16601 
16602   if (Res.isNull() || TyA.getCanonicalType() != TyB.getCanonicalType())
16603     return Diag(A.get()->getBeginLoc(),
16604                 diag::err_typecheck_call_different_arg_types)
16605            << TyA << TyB;
16606 
16607   if (checkMathBuiltinElementType(*this, A.get()->getBeginLoc(), TyA))
16608     return true;
16609 
16610   TheCall->setArg(0, A.get());
16611   TheCall->setArg(1, B.get());
16612   TheCall->setType(Res);
16613   return false;
16614 }
16615 
16616 bool Sema::SemaBuiltinReduceMath(CallExpr *TheCall) {
16617   if (checkArgCount(*this, TheCall, 1))
16618     return true;
16619 
16620   ExprResult A = UsualUnaryConversions(TheCall->getArg(0));
16621   if (A.isInvalid())
16622     return true;
16623 
16624   TheCall->setArg(0, A.get());
16625   const VectorType *TyA = A.get()->getType()->getAs<VectorType>();
16626   if (!TyA) {
16627     SourceLocation ArgLoc = TheCall->getArg(0)->getBeginLoc();
16628     return Diag(ArgLoc, diag::err_builtin_invalid_arg_type)
16629            << 1 << /* vector ty*/ 4 << A.get()->getType();
16630   }
16631 
16632   TheCall->setType(TyA->getElementType());
16633   return false;
16634 }
16635 
16636 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16637                                             ExprResult CallResult) {
16638   if (checkArgCount(*this, TheCall, 1))
16639     return ExprError();
16640 
16641   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16642   if (MatrixArg.isInvalid())
16643     return MatrixArg;
16644   Expr *Matrix = MatrixArg.get();
16645 
16646   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16647   if (!MType) {
16648     Diag(Matrix->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16649         << 1 << /* matrix ty*/ 1 << Matrix->getType();
16650     return ExprError();
16651   }
16652 
16653   // Create returned matrix type by swapping rows and columns of the argument
16654   // matrix type.
16655   QualType ResultType = Context.getConstantMatrixType(
16656       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16657 
16658   // Change the return type to the type of the returned matrix.
16659   TheCall->setType(ResultType);
16660 
16661   // Update call argument to use the possibly converted matrix argument.
16662   TheCall->setArg(0, Matrix);
16663   return CallResult;
16664 }
16665 
16666 // Get and verify the matrix dimensions.
16667 static llvm::Optional<unsigned>
16668 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16669   SourceLocation ErrorPos;
16670   Optional<llvm::APSInt> Value =
16671       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16672   if (!Value) {
16673     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16674         << Name;
16675     return {};
16676   }
16677   uint64_t Dim = Value->getZExtValue();
16678   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16679     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16680         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16681     return {};
16682   }
16683   return Dim;
16684 }
16685 
16686 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16687                                                   ExprResult CallResult) {
16688   if (!getLangOpts().MatrixTypes) {
16689     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16690     return ExprError();
16691   }
16692 
16693   if (checkArgCount(*this, TheCall, 4))
16694     return ExprError();
16695 
16696   unsigned PtrArgIdx = 0;
16697   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16698   Expr *RowsExpr = TheCall->getArg(1);
16699   Expr *ColumnsExpr = TheCall->getArg(2);
16700   Expr *StrideExpr = TheCall->getArg(3);
16701 
16702   bool ArgError = false;
16703 
16704   // Check pointer argument.
16705   {
16706     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16707     if (PtrConv.isInvalid())
16708       return PtrConv;
16709     PtrExpr = PtrConv.get();
16710     TheCall->setArg(0, PtrExpr);
16711     if (PtrExpr->isTypeDependent()) {
16712       TheCall->setType(Context.DependentTy);
16713       return TheCall;
16714     }
16715   }
16716 
16717   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16718   QualType ElementTy;
16719   if (!PtrTy) {
16720     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16721         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16722     ArgError = true;
16723   } else {
16724     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16725 
16726     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16727       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16728           << PtrArgIdx + 1 << /* pointer to element ty*/ 2
16729           << PtrExpr->getType();
16730       ArgError = true;
16731     }
16732   }
16733 
16734   // Apply default Lvalue conversions and convert the expression to size_t.
16735   auto ApplyArgumentConversions = [this](Expr *E) {
16736     ExprResult Conv = DefaultLvalueConversion(E);
16737     if (Conv.isInvalid())
16738       return Conv;
16739 
16740     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16741   };
16742 
16743   // Apply conversion to row and column expressions.
16744   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16745   if (!RowsConv.isInvalid()) {
16746     RowsExpr = RowsConv.get();
16747     TheCall->setArg(1, RowsExpr);
16748   } else
16749     RowsExpr = nullptr;
16750 
16751   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16752   if (!ColumnsConv.isInvalid()) {
16753     ColumnsExpr = ColumnsConv.get();
16754     TheCall->setArg(2, ColumnsExpr);
16755   } else
16756     ColumnsExpr = nullptr;
16757 
16758   // If any any part of the result matrix type is still pending, just use
16759   // Context.DependentTy, until all parts are resolved.
16760   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16761       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16762     TheCall->setType(Context.DependentTy);
16763     return CallResult;
16764   }
16765 
16766   // Check row and column dimensions.
16767   llvm::Optional<unsigned> MaybeRows;
16768   if (RowsExpr)
16769     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16770 
16771   llvm::Optional<unsigned> MaybeColumns;
16772   if (ColumnsExpr)
16773     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16774 
16775   // Check stride argument.
16776   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16777   if (StrideConv.isInvalid())
16778     return ExprError();
16779   StrideExpr = StrideConv.get();
16780   TheCall->setArg(3, StrideExpr);
16781 
16782   if (MaybeRows) {
16783     if (Optional<llvm::APSInt> Value =
16784             StrideExpr->getIntegerConstantExpr(Context)) {
16785       uint64_t Stride = Value->getZExtValue();
16786       if (Stride < *MaybeRows) {
16787         Diag(StrideExpr->getBeginLoc(),
16788              diag::err_builtin_matrix_stride_too_small);
16789         ArgError = true;
16790       }
16791     }
16792   }
16793 
16794   if (ArgError || !MaybeRows || !MaybeColumns)
16795     return ExprError();
16796 
16797   TheCall->setType(
16798       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16799   return CallResult;
16800 }
16801 
16802 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16803                                                    ExprResult CallResult) {
16804   if (checkArgCount(*this, TheCall, 3))
16805     return ExprError();
16806 
16807   unsigned PtrArgIdx = 1;
16808   Expr *MatrixExpr = TheCall->getArg(0);
16809   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16810   Expr *StrideExpr = TheCall->getArg(2);
16811 
16812   bool ArgError = false;
16813 
16814   {
16815     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16816     if (MatrixConv.isInvalid())
16817       return MatrixConv;
16818     MatrixExpr = MatrixConv.get();
16819     TheCall->setArg(0, MatrixExpr);
16820   }
16821   if (MatrixExpr->isTypeDependent()) {
16822     TheCall->setType(Context.DependentTy);
16823     return TheCall;
16824   }
16825 
16826   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16827   if (!MatrixTy) {
16828     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16829         << 1 << /*matrix ty */ 1 << MatrixExpr->getType();
16830     ArgError = true;
16831   }
16832 
16833   {
16834     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16835     if (PtrConv.isInvalid())
16836       return PtrConv;
16837     PtrExpr = PtrConv.get();
16838     TheCall->setArg(1, PtrExpr);
16839     if (PtrExpr->isTypeDependent()) {
16840       TheCall->setType(Context.DependentTy);
16841       return TheCall;
16842     }
16843   }
16844 
16845   // Check pointer argument.
16846   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16847   if (!PtrTy) {
16848     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_invalid_arg_type)
16849         << PtrArgIdx + 1 << /*pointer to element ty*/ 2 << PtrExpr->getType();
16850     ArgError = true;
16851   } else {
16852     QualType ElementTy = PtrTy->getPointeeType();
16853     if (ElementTy.isConstQualified()) {
16854       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16855       ArgError = true;
16856     }
16857     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16858     if (MatrixTy &&
16859         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16860       Diag(PtrExpr->getBeginLoc(),
16861            diag::err_builtin_matrix_pointer_arg_mismatch)
16862           << ElementTy << MatrixTy->getElementType();
16863       ArgError = true;
16864     }
16865   }
16866 
16867   // Apply default Lvalue conversions and convert the stride expression to
16868   // size_t.
16869   {
16870     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16871     if (StrideConv.isInvalid())
16872       return StrideConv;
16873 
16874     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16875     if (StrideConv.isInvalid())
16876       return StrideConv;
16877     StrideExpr = StrideConv.get();
16878     TheCall->setArg(2, StrideExpr);
16879   }
16880 
16881   // Check stride argument.
16882   if (MatrixTy) {
16883     if (Optional<llvm::APSInt> Value =
16884             StrideExpr->getIntegerConstantExpr(Context)) {
16885       uint64_t Stride = Value->getZExtValue();
16886       if (Stride < MatrixTy->getNumRows()) {
16887         Diag(StrideExpr->getBeginLoc(),
16888              diag::err_builtin_matrix_stride_too_small);
16889         ArgError = true;
16890       }
16891     }
16892   }
16893 
16894   if (ArgError)
16895     return ExprError();
16896 
16897   return CallResult;
16898 }
16899 
16900 /// \brief Enforce the bounds of a TCB
16901 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16902 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16903 /// and enforce_tcb_leaf attributes.
16904 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16905                                const FunctionDecl *Callee) {
16906   const FunctionDecl *Caller = getCurFunctionDecl();
16907 
16908   // Calls to builtins are not enforced.
16909   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16910       Callee->getBuiltinID() != 0)
16911     return;
16912 
16913   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16914   // all TCBs the callee is a part of.
16915   llvm::StringSet<> CalleeTCBs;
16916   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16917            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16918   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16919            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16920 
16921   // Go through the TCBs the caller is a part of and emit warnings if Caller
16922   // is in a TCB that the Callee is not.
16923   for_each(
16924       Caller->specific_attrs<EnforceTCBAttr>(),
16925       [&](const auto *A) {
16926         StringRef CallerTCB = A->getTCBName();
16927         if (CalleeTCBs.count(CallerTCB) == 0) {
16928           this->Diag(TheCall->getExprLoc(),
16929                      diag::warn_tcb_enforcement_violation) << Callee
16930                                                            << CallerTCB;
16931         }
16932       });
16933 }
16934