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 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
592 /// __builtin_*_chk function, then use the object size argument specified in the
593 /// source. Otherwise, infer the object size using __builtin_object_size.
594 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
595                                                CallExpr *TheCall) {
596   // FIXME: There are some more useful checks we could be doing here:
597   //  - Evaluate strlen of strcpy arguments, use as object size.
598 
599   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
600       isConstantEvaluated())
601     return;
602 
603   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
604   if (!BuiltinID)
605     return;
606 
607   const TargetInfo &TI = getASTContext().getTargetInfo();
608   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
609 
610   unsigned DiagID = 0;
611   bool IsChkVariant = false;
612   Optional<llvm::APSInt> UsedSize;
613   unsigned SizeIndex, ObjectIndex;
614   switch (BuiltinID) {
615   default:
616     return;
617   case Builtin::BIsprintf:
618   case Builtin::BI__builtin___sprintf_chk: {
619     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
620     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
621 
622     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
623 
624       if (!Format->isAscii() && !Format->isUTF8())
625         return;
626 
627       StringRef FormatStrRef = Format->getString();
628       EstimateSizeFormatHandler H(FormatStrRef);
629       const char *FormatBytes = FormatStrRef.data();
630       const ConstantArrayType *T =
631           Context.getAsConstantArrayType(Format->getType());
632       assert(T && "String literal not of constant array type!");
633       size_t TypeSize = T->getSize().getZExtValue();
634 
635       // In case there's a null byte somewhere.
636       size_t StrLen =
637           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
638       if (!analyze_format_string::ParsePrintfString(
639               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
640               Context.getTargetInfo(), false)) {
641         DiagID = diag::warn_fortify_source_format_overflow;
642         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
643                        .extOrTrunc(SizeTypeWidth);
644         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
645           IsChkVariant = true;
646           ObjectIndex = 2;
647         } else {
648           IsChkVariant = false;
649           ObjectIndex = 0;
650         }
651         break;
652       }
653     }
654     return;
655   }
656   case Builtin::BI__builtin___memcpy_chk:
657   case Builtin::BI__builtin___memmove_chk:
658   case Builtin::BI__builtin___memset_chk:
659   case Builtin::BI__builtin___strlcat_chk:
660   case Builtin::BI__builtin___strlcpy_chk:
661   case Builtin::BI__builtin___strncat_chk:
662   case Builtin::BI__builtin___strncpy_chk:
663   case Builtin::BI__builtin___stpncpy_chk:
664   case Builtin::BI__builtin___memccpy_chk:
665   case Builtin::BI__builtin___mempcpy_chk: {
666     DiagID = diag::warn_builtin_chk_overflow;
667     IsChkVariant = true;
668     SizeIndex = TheCall->getNumArgs() - 2;
669     ObjectIndex = TheCall->getNumArgs() - 1;
670     break;
671   }
672 
673   case Builtin::BI__builtin___snprintf_chk:
674   case Builtin::BI__builtin___vsnprintf_chk: {
675     DiagID = diag::warn_builtin_chk_overflow;
676     IsChkVariant = true;
677     SizeIndex = 1;
678     ObjectIndex = 3;
679     break;
680   }
681 
682   case Builtin::BIstrncat:
683   case Builtin::BI__builtin_strncat:
684   case Builtin::BIstrncpy:
685   case Builtin::BI__builtin_strncpy:
686   case Builtin::BIstpncpy:
687   case Builtin::BI__builtin_stpncpy: {
688     // Whether these functions overflow depends on the runtime strlen of the
689     // string, not just the buffer size, so emitting the "always overflow"
690     // diagnostic isn't quite right. We should still diagnose passing a buffer
691     // size larger than the destination buffer though; this is a runtime abort
692     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
693     DiagID = diag::warn_fortify_source_size_mismatch;
694     SizeIndex = TheCall->getNumArgs() - 1;
695     ObjectIndex = 0;
696     break;
697   }
698 
699   case Builtin::BImemcpy:
700   case Builtin::BI__builtin_memcpy:
701   case Builtin::BImemmove:
702   case Builtin::BI__builtin_memmove:
703   case Builtin::BImemset:
704   case Builtin::BI__builtin_memset:
705   case Builtin::BImempcpy:
706   case Builtin::BI__builtin_mempcpy: {
707     DiagID = diag::warn_fortify_source_overflow;
708     SizeIndex = TheCall->getNumArgs() - 1;
709     ObjectIndex = 0;
710     break;
711   }
712   case Builtin::BIsnprintf:
713   case Builtin::BI__builtin_snprintf:
714   case Builtin::BIvsnprintf:
715   case Builtin::BI__builtin_vsnprintf: {
716     DiagID = diag::warn_fortify_source_size_mismatch;
717     SizeIndex = 1;
718     ObjectIndex = 0;
719     break;
720   }
721   }
722 
723   llvm::APSInt ObjectSize;
724   // For __builtin___*_chk, the object size is explicitly provided by the caller
725   // (usually using __builtin_object_size). Use that value to check this call.
726   if (IsChkVariant) {
727     Expr::EvalResult Result;
728     Expr *SizeArg = TheCall->getArg(ObjectIndex);
729     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
730       return;
731     ObjectSize = Result.Val.getInt();
732 
733   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
734   } else {
735     // If the parameter has a pass_object_size attribute, then we should use its
736     // (potentially) more strict checking mode. Otherwise, conservatively assume
737     // type 0.
738     int BOSType = 0;
739     if (const auto *POS =
740             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
741       BOSType = POS->getType();
742 
743     Expr *ObjArg = TheCall->getArg(ObjectIndex);
744     uint64_t Result;
745     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
746       return;
747     // Get the object size in the target's size_t width.
748     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
749   }
750 
751   // Evaluate the number of bytes of the object that this call will use.
752   if (!UsedSize) {
753     Expr::EvalResult Result;
754     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
755     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
756       return;
757     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
758   }
759 
760   if (UsedSize.getValue().ule(ObjectSize))
761     return;
762 
763   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
764   // Skim off the details of whichever builtin was called to produce a better
765   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
766   if (IsChkVariant) {
767     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
768     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
769   } else if (FunctionName.startswith("__builtin_")) {
770     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
771   }
772 
773   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
774                       PDiag(DiagID)
775                           << FunctionName << toString(ObjectSize, /*Radix=*/10)
776                           << toString(UsedSize.getValue(), /*Radix=*/10));
777 }
778 
779 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
780                                      Scope::ScopeFlags NeededScopeFlags,
781                                      unsigned DiagID) {
782   // Scopes aren't available during instantiation. Fortunately, builtin
783   // functions cannot be template args so they cannot be formed through template
784   // instantiation. Therefore checking once during the parse is sufficient.
785   if (SemaRef.inTemplateInstantiation())
786     return false;
787 
788   Scope *S = SemaRef.getCurScope();
789   while (S && !S->isSEHExceptScope())
790     S = S->getParent();
791   if (!S || !(S->getFlags() & NeededScopeFlags)) {
792     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
793     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
794         << DRE->getDecl()->getIdentifier();
795     return true;
796   }
797 
798   return false;
799 }
800 
801 static inline bool isBlockPointer(Expr *Arg) {
802   return Arg->getType()->isBlockPointerType();
803 }
804 
805 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
806 /// void*, which is a requirement of device side enqueue.
807 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
808   const BlockPointerType *BPT =
809       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
810   ArrayRef<QualType> Params =
811       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
812   unsigned ArgCounter = 0;
813   bool IllegalParams = false;
814   // Iterate through the block parameters until either one is found that is not
815   // a local void*, or the block is valid.
816   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
817        I != E; ++I, ++ArgCounter) {
818     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
819         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
820             LangAS::opencl_local) {
821       // Get the location of the error. If a block literal has been passed
822       // (BlockExpr) then we can point straight to the offending argument,
823       // else we just point to the variable reference.
824       SourceLocation ErrorLoc;
825       if (isa<BlockExpr>(BlockArg)) {
826         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
827         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
828       } else if (isa<DeclRefExpr>(BlockArg)) {
829         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
830       }
831       S.Diag(ErrorLoc,
832              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
833       IllegalParams = true;
834     }
835   }
836 
837   return IllegalParams;
838 }
839 
840 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
841   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
842     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
843         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
844     return true;
845   }
846   return false;
847 }
848 
849 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
850   if (checkArgCount(S, TheCall, 2))
851     return true;
852 
853   if (checkOpenCLSubgroupExt(S, TheCall))
854     return true;
855 
856   // First argument is an ndrange_t type.
857   Expr *NDRangeArg = TheCall->getArg(0);
858   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
859     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
860         << TheCall->getDirectCallee() << "'ndrange_t'";
861     return true;
862   }
863 
864   Expr *BlockArg = TheCall->getArg(1);
865   if (!isBlockPointer(BlockArg)) {
866     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
867         << TheCall->getDirectCallee() << "block";
868     return true;
869   }
870   return checkOpenCLBlockArgs(S, BlockArg);
871 }
872 
873 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
874 /// get_kernel_work_group_size
875 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
876 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
877   if (checkArgCount(S, TheCall, 1))
878     return true;
879 
880   Expr *BlockArg = TheCall->getArg(0);
881   if (!isBlockPointer(BlockArg)) {
882     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
883         << TheCall->getDirectCallee() << "block";
884     return true;
885   }
886   return checkOpenCLBlockArgs(S, BlockArg);
887 }
888 
889 /// Diagnose integer type and any valid implicit conversion to it.
890 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
891                                       const QualType &IntType);
892 
893 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
894                                             unsigned Start, unsigned End) {
895   bool IllegalParams = false;
896   for (unsigned I = Start; I <= End; ++I)
897     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
898                                               S.Context.getSizeType());
899   return IllegalParams;
900 }
901 
902 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
903 /// 'local void*' parameter of passed block.
904 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
905                                            Expr *BlockArg,
906                                            unsigned NumNonVarArgs) {
907   const BlockPointerType *BPT =
908       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
909   unsigned NumBlockParams =
910       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
911   unsigned TotalNumArgs = TheCall->getNumArgs();
912 
913   // For each argument passed to the block, a corresponding uint needs to
914   // be passed to describe the size of the local memory.
915   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
916     S.Diag(TheCall->getBeginLoc(),
917            diag::err_opencl_enqueue_kernel_local_size_args);
918     return true;
919   }
920 
921   // Check that the sizes of the local memory are specified by integers.
922   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
923                                          TotalNumArgs - 1);
924 }
925 
926 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
927 /// overload formats specified in Table 6.13.17.1.
928 /// int enqueue_kernel(queue_t queue,
929 ///                    kernel_enqueue_flags_t flags,
930 ///                    const ndrange_t ndrange,
931 ///                    void (^block)(void))
932 /// int enqueue_kernel(queue_t queue,
933 ///                    kernel_enqueue_flags_t flags,
934 ///                    const ndrange_t ndrange,
935 ///                    uint num_events_in_wait_list,
936 ///                    clk_event_t *event_wait_list,
937 ///                    clk_event_t *event_ret,
938 ///                    void (^block)(void))
939 /// int enqueue_kernel(queue_t queue,
940 ///                    kernel_enqueue_flags_t flags,
941 ///                    const ndrange_t ndrange,
942 ///                    void (^block)(local void*, ...),
943 ///                    uint size0, ...)
944 /// int enqueue_kernel(queue_t queue,
945 ///                    kernel_enqueue_flags_t flags,
946 ///                    const ndrange_t ndrange,
947 ///                    uint num_events_in_wait_list,
948 ///                    clk_event_t *event_wait_list,
949 ///                    clk_event_t *event_ret,
950 ///                    void (^block)(local void*, ...),
951 ///                    uint size0, ...)
952 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
953   unsigned NumArgs = TheCall->getNumArgs();
954 
955   if (NumArgs < 4) {
956     S.Diag(TheCall->getBeginLoc(),
957            diag::err_typecheck_call_too_few_args_at_least)
958         << 0 << 4 << NumArgs;
959     return true;
960   }
961 
962   Expr *Arg0 = TheCall->getArg(0);
963   Expr *Arg1 = TheCall->getArg(1);
964   Expr *Arg2 = TheCall->getArg(2);
965   Expr *Arg3 = TheCall->getArg(3);
966 
967   // First argument always needs to be a queue_t type.
968   if (!Arg0->getType()->isQueueT()) {
969     S.Diag(TheCall->getArg(0)->getBeginLoc(),
970            diag::err_opencl_builtin_expected_type)
971         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
972     return true;
973   }
974 
975   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
976   if (!Arg1->getType()->isIntegerType()) {
977     S.Diag(TheCall->getArg(1)->getBeginLoc(),
978            diag::err_opencl_builtin_expected_type)
979         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
980     return true;
981   }
982 
983   // Third argument is always an ndrange_t type.
984   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
985     S.Diag(TheCall->getArg(2)->getBeginLoc(),
986            diag::err_opencl_builtin_expected_type)
987         << TheCall->getDirectCallee() << "'ndrange_t'";
988     return true;
989   }
990 
991   // With four arguments, there is only one form that the function could be
992   // called in: no events and no variable arguments.
993   if (NumArgs == 4) {
994     // check that the last argument is the right block type.
995     if (!isBlockPointer(Arg3)) {
996       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
997           << TheCall->getDirectCallee() << "block";
998       return true;
999     }
1000     // we have a block type, check the prototype
1001     const BlockPointerType *BPT =
1002         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1003     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1004       S.Diag(Arg3->getBeginLoc(),
1005              diag::err_opencl_enqueue_kernel_blocks_no_args);
1006       return true;
1007     }
1008     return false;
1009   }
1010   // we can have block + varargs.
1011   if (isBlockPointer(Arg3))
1012     return (checkOpenCLBlockArgs(S, Arg3) ||
1013             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1014   // last two cases with either exactly 7 args or 7 args and varargs.
1015   if (NumArgs >= 7) {
1016     // check common block argument.
1017     Expr *Arg6 = TheCall->getArg(6);
1018     if (!isBlockPointer(Arg6)) {
1019       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1020           << TheCall->getDirectCallee() << "block";
1021       return true;
1022     }
1023     if (checkOpenCLBlockArgs(S, Arg6))
1024       return true;
1025 
1026     // Forth argument has to be any integer type.
1027     if (!Arg3->getType()->isIntegerType()) {
1028       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1029              diag::err_opencl_builtin_expected_type)
1030           << TheCall->getDirectCallee() << "integer";
1031       return true;
1032     }
1033     // check remaining common arguments.
1034     Expr *Arg4 = TheCall->getArg(4);
1035     Expr *Arg5 = TheCall->getArg(5);
1036 
1037     // Fifth argument is always passed as a pointer to clk_event_t.
1038     if (!Arg4->isNullPointerConstant(S.Context,
1039                                      Expr::NPC_ValueDependentIsNotNull) &&
1040         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1041       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1042              diag::err_opencl_builtin_expected_type)
1043           << TheCall->getDirectCallee()
1044           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1045       return true;
1046     }
1047 
1048     // Sixth argument is always passed as a pointer to clk_event_t.
1049     if (!Arg5->isNullPointerConstant(S.Context,
1050                                      Expr::NPC_ValueDependentIsNotNull) &&
1051         !(Arg5->getType()->isPointerType() &&
1052           Arg5->getType()->getPointeeType()->isClkEventT())) {
1053       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1054              diag::err_opencl_builtin_expected_type)
1055           << TheCall->getDirectCallee()
1056           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1057       return true;
1058     }
1059 
1060     if (NumArgs == 7)
1061       return false;
1062 
1063     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1064   }
1065 
1066   // None of the specific case has been detected, give generic error
1067   S.Diag(TheCall->getBeginLoc(),
1068          diag::err_opencl_enqueue_kernel_incorrect_args);
1069   return true;
1070 }
1071 
1072 /// Returns OpenCL access qual.
1073 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1074     return D->getAttr<OpenCLAccessAttr>();
1075 }
1076 
1077 /// Returns true if pipe element type is different from the pointer.
1078 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1079   const Expr *Arg0 = Call->getArg(0);
1080   // First argument type should always be pipe.
1081   if (!Arg0->getType()->isPipeType()) {
1082     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1083         << Call->getDirectCallee() << Arg0->getSourceRange();
1084     return true;
1085   }
1086   OpenCLAccessAttr *AccessQual =
1087       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1088   // Validates the access qualifier is compatible with the call.
1089   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1090   // read_only and write_only, and assumed to be read_only if no qualifier is
1091   // specified.
1092   switch (Call->getDirectCallee()->getBuiltinID()) {
1093   case Builtin::BIread_pipe:
1094   case Builtin::BIreserve_read_pipe:
1095   case Builtin::BIcommit_read_pipe:
1096   case Builtin::BIwork_group_reserve_read_pipe:
1097   case Builtin::BIsub_group_reserve_read_pipe:
1098   case Builtin::BIwork_group_commit_read_pipe:
1099   case Builtin::BIsub_group_commit_read_pipe:
1100     if (!(!AccessQual || AccessQual->isReadOnly())) {
1101       S.Diag(Arg0->getBeginLoc(),
1102              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1103           << "read_only" << Arg0->getSourceRange();
1104       return true;
1105     }
1106     break;
1107   case Builtin::BIwrite_pipe:
1108   case Builtin::BIreserve_write_pipe:
1109   case Builtin::BIcommit_write_pipe:
1110   case Builtin::BIwork_group_reserve_write_pipe:
1111   case Builtin::BIsub_group_reserve_write_pipe:
1112   case Builtin::BIwork_group_commit_write_pipe:
1113   case Builtin::BIsub_group_commit_write_pipe:
1114     if (!(AccessQual && AccessQual->isWriteOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "write_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   default:
1122     break;
1123   }
1124   return false;
1125 }
1126 
1127 /// Returns true if pipe element type is different from the pointer.
1128 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1129   const Expr *Arg0 = Call->getArg(0);
1130   const Expr *ArgIdx = Call->getArg(Idx);
1131   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1132   const QualType EltTy = PipeTy->getElementType();
1133   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1134   // The Idx argument should be a pointer and the type of the pointer and
1135   // the type of pipe element should also be the same.
1136   if (!ArgTy ||
1137       !S.Context.hasSameType(
1138           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1139     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1140         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1141         << ArgIdx->getType() << ArgIdx->getSourceRange();
1142     return true;
1143   }
1144   return false;
1145 }
1146 
1147 // Performs semantic analysis for the read/write_pipe call.
1148 // \param S Reference to the semantic analyzer.
1149 // \param Call A pointer to the builtin call.
1150 // \return True if a semantic error has been found, false otherwise.
1151 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1152   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1153   // functions have two forms.
1154   switch (Call->getNumArgs()) {
1155   case 2:
1156     if (checkOpenCLPipeArg(S, Call))
1157       return true;
1158     // The call with 2 arguments should be
1159     // read/write_pipe(pipe T, T*).
1160     // Check packet type T.
1161     if (checkOpenCLPipePacketType(S, Call, 1))
1162       return true;
1163     break;
1164 
1165   case 4: {
1166     if (checkOpenCLPipeArg(S, Call))
1167       return true;
1168     // The call with 4 arguments should be
1169     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1170     // Check reserve_id_t.
1171     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1172       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1173           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1174           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1175       return true;
1176     }
1177 
1178     // Check the index.
1179     const Expr *Arg2 = Call->getArg(2);
1180     if (!Arg2->getType()->isIntegerType() &&
1181         !Arg2->getType()->isUnsignedIntegerType()) {
1182       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1183           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1184           << Arg2->getType() << Arg2->getSourceRange();
1185       return true;
1186     }
1187 
1188     // Check packet type T.
1189     if (checkOpenCLPipePacketType(S, Call, 3))
1190       return true;
1191   } break;
1192   default:
1193     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1194         << Call->getDirectCallee() << Call->getSourceRange();
1195     return true;
1196   }
1197 
1198   return false;
1199 }
1200 
1201 // Performs a semantic analysis on the {work_group_/sub_group_
1202 //        /_}reserve_{read/write}_pipe
1203 // \param S Reference to the semantic analyzer.
1204 // \param Call The call to the builtin function to be analyzed.
1205 // \return True if a semantic error was found, false otherwise.
1206 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1207   if (checkArgCount(S, Call, 2))
1208     return true;
1209 
1210   if (checkOpenCLPipeArg(S, Call))
1211     return true;
1212 
1213   // Check the reserve size.
1214   if (!Call->getArg(1)->getType()->isIntegerType() &&
1215       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1216     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1217         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1218         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1219     return true;
1220   }
1221 
1222   // Since return type of reserve_read/write_pipe built-in function is
1223   // reserve_id_t, which is not defined in the builtin def file , we used int
1224   // as return type and need to override the return type of these functions.
1225   Call->setType(S.Context.OCLReserveIDTy);
1226 
1227   return false;
1228 }
1229 
1230 // Performs a semantic analysis on {work_group_/sub_group_
1231 //        /_}commit_{read/write}_pipe
1232 // \param S Reference to the semantic analyzer.
1233 // \param Call The call to the builtin function to be analyzed.
1234 // \return True if a semantic error was found, false otherwise.
1235 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1236   if (checkArgCount(S, Call, 2))
1237     return true;
1238 
1239   if (checkOpenCLPipeArg(S, Call))
1240     return true;
1241 
1242   // Check reserve_id_t.
1243   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1244     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1245         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1246         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1247     return true;
1248   }
1249 
1250   return false;
1251 }
1252 
1253 // Performs a semantic analysis on the call to built-in Pipe
1254 //        Query Functions.
1255 // \param S Reference to the semantic analyzer.
1256 // \param Call The call to the builtin function to be analyzed.
1257 // \return True if a semantic error was found, false otherwise.
1258 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1259   if (checkArgCount(S, Call, 1))
1260     return true;
1261 
1262   if (!Call->getArg(0)->getType()->isPipeType()) {
1263     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1264         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1265     return true;
1266   }
1267 
1268   return false;
1269 }
1270 
1271 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1272 // Performs semantic analysis for the to_global/local/private call.
1273 // \param S Reference to the semantic analyzer.
1274 // \param BuiltinID ID of the builtin function.
1275 // \param Call A pointer to the builtin call.
1276 // \return True if a semantic error has been found, false otherwise.
1277 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1278                                     CallExpr *Call) {
1279   if (checkArgCount(S, Call, 1))
1280     return true;
1281 
1282   auto RT = Call->getArg(0)->getType();
1283   if (!RT->isPointerType() || RT->getPointeeType()
1284       .getAddressSpace() == LangAS::opencl_constant) {
1285     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1286         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1287     return true;
1288   }
1289 
1290   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1291     S.Diag(Call->getArg(0)->getBeginLoc(),
1292            diag::warn_opencl_generic_address_space_arg)
1293         << Call->getDirectCallee()->getNameInfo().getAsString()
1294         << Call->getArg(0)->getSourceRange();
1295   }
1296 
1297   RT = RT->getPointeeType();
1298   auto Qual = RT.getQualifiers();
1299   switch (BuiltinID) {
1300   case Builtin::BIto_global:
1301     Qual.setAddressSpace(LangAS::opencl_global);
1302     break;
1303   case Builtin::BIto_local:
1304     Qual.setAddressSpace(LangAS::opencl_local);
1305     break;
1306   case Builtin::BIto_private:
1307     Qual.setAddressSpace(LangAS::opencl_private);
1308     break;
1309   default:
1310     llvm_unreachable("Invalid builtin function");
1311   }
1312   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1313       RT.getUnqualifiedType(), Qual)));
1314 
1315   return false;
1316 }
1317 
1318 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1319   if (checkArgCount(S, TheCall, 1))
1320     return ExprError();
1321 
1322   // Compute __builtin_launder's parameter type from the argument.
1323   // The parameter type is:
1324   //  * The type of the argument if it's not an array or function type,
1325   //  Otherwise,
1326   //  * The decayed argument type.
1327   QualType ParamTy = [&]() {
1328     QualType ArgTy = TheCall->getArg(0)->getType();
1329     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1330       return S.Context.getPointerType(Ty->getElementType());
1331     if (ArgTy->isFunctionType()) {
1332       return S.Context.getPointerType(ArgTy);
1333     }
1334     return ArgTy;
1335   }();
1336 
1337   TheCall->setType(ParamTy);
1338 
1339   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1340     if (!ParamTy->isPointerType())
1341       return 0;
1342     if (ParamTy->isFunctionPointerType())
1343       return 1;
1344     if (ParamTy->isVoidPointerType())
1345       return 2;
1346     return llvm::Optional<unsigned>{};
1347   }();
1348   if (DiagSelect.hasValue()) {
1349     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1350         << DiagSelect.getValue() << TheCall->getSourceRange();
1351     return ExprError();
1352   }
1353 
1354   // We either have an incomplete class type, or we have a class template
1355   // whose instantiation has not been forced. Example:
1356   //
1357   //   template <class T> struct Foo { T value; };
1358   //   Foo<int> *p = nullptr;
1359   //   auto *d = __builtin_launder(p);
1360   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1361                             diag::err_incomplete_type))
1362     return ExprError();
1363 
1364   assert(ParamTy->getPointeeType()->isObjectType() &&
1365          "Unhandled non-object pointer case");
1366 
1367   InitializedEntity Entity =
1368       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1369   ExprResult Arg =
1370       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1371   if (Arg.isInvalid())
1372     return ExprError();
1373   TheCall->setArg(0, Arg.get());
1374 
1375   return TheCall;
1376 }
1377 
1378 // Emit an error and return true if the current architecture is not in the list
1379 // of supported architectures.
1380 static bool
1381 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1382                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1383   llvm::Triple::ArchType CurArch =
1384       S.getASTContext().getTargetInfo().getTriple().getArch();
1385   if (llvm::is_contained(SupportedArchs, CurArch))
1386     return false;
1387   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1388       << TheCall->getSourceRange();
1389   return true;
1390 }
1391 
1392 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1393                                  SourceLocation CallSiteLoc);
1394 
1395 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1396                                       CallExpr *TheCall) {
1397   switch (TI.getTriple().getArch()) {
1398   default:
1399     // Some builtins don't require additional checking, so just consider these
1400     // acceptable.
1401     return false;
1402   case llvm::Triple::arm:
1403   case llvm::Triple::armeb:
1404   case llvm::Triple::thumb:
1405   case llvm::Triple::thumbeb:
1406     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1407   case llvm::Triple::aarch64:
1408   case llvm::Triple::aarch64_32:
1409   case llvm::Triple::aarch64_be:
1410     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1411   case llvm::Triple::bpfeb:
1412   case llvm::Triple::bpfel:
1413     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::hexagon:
1415     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1416   case llvm::Triple::mips:
1417   case llvm::Triple::mipsel:
1418   case llvm::Triple::mips64:
1419   case llvm::Triple::mips64el:
1420     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::systemz:
1422     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1423   case llvm::Triple::x86:
1424   case llvm::Triple::x86_64:
1425     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1426   case llvm::Triple::ppc:
1427   case llvm::Triple::ppcle:
1428   case llvm::Triple::ppc64:
1429   case llvm::Triple::ppc64le:
1430     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1431   case llvm::Triple::amdgcn:
1432     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1433   case llvm::Triple::riscv32:
1434   case llvm::Triple::riscv64:
1435     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1436   }
1437 }
1438 
1439 ExprResult
1440 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1441                                CallExpr *TheCall) {
1442   ExprResult TheCallResult(TheCall);
1443 
1444   // Find out if any arguments are required to be integer constant expressions.
1445   unsigned ICEArguments = 0;
1446   ASTContext::GetBuiltinTypeError Error;
1447   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1448   if (Error != ASTContext::GE_None)
1449     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1450 
1451   // If any arguments are required to be ICE's, check and diagnose.
1452   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1453     // Skip arguments not required to be ICE's.
1454     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1455 
1456     llvm::APSInt Result;
1457     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1458       return true;
1459     ICEArguments &= ~(1 << ArgNo);
1460   }
1461 
1462   switch (BuiltinID) {
1463   case Builtin::BI__builtin___CFStringMakeConstantString:
1464     assert(TheCall->getNumArgs() == 1 &&
1465            "Wrong # arguments to builtin CFStringMakeConstantString");
1466     if (CheckObjCString(TheCall->getArg(0)))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__builtin_ms_va_start:
1470   case Builtin::BI__builtin_stdarg_start:
1471   case Builtin::BI__builtin_va_start:
1472     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1473       return ExprError();
1474     break;
1475   case Builtin::BI__va_start: {
1476     switch (Context.getTargetInfo().getTriple().getArch()) {
1477     case llvm::Triple::aarch64:
1478     case llvm::Triple::arm:
1479     case llvm::Triple::thumb:
1480       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1481         return ExprError();
1482       break;
1483     default:
1484       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1485         return ExprError();
1486       break;
1487     }
1488     break;
1489   }
1490 
1491   // The acquire, release, and no fence variants are ARM and AArch64 only.
1492   case Builtin::BI_interlockedbittestandset_acq:
1493   case Builtin::BI_interlockedbittestandset_rel:
1494   case Builtin::BI_interlockedbittestandset_nf:
1495   case Builtin::BI_interlockedbittestandreset_acq:
1496   case Builtin::BI_interlockedbittestandreset_rel:
1497   case Builtin::BI_interlockedbittestandreset_nf:
1498     if (CheckBuiltinTargetSupport(
1499             *this, BuiltinID, TheCall,
1500             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1501       return ExprError();
1502     break;
1503 
1504   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1505   case Builtin::BI_bittest64:
1506   case Builtin::BI_bittestandcomplement64:
1507   case Builtin::BI_bittestandreset64:
1508   case Builtin::BI_bittestandset64:
1509   case Builtin::BI_interlockedbittestandreset64:
1510   case Builtin::BI_interlockedbittestandset64:
1511     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1512                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1513                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1514       return ExprError();
1515     break;
1516 
1517   case Builtin::BI__builtin_isgreater:
1518   case Builtin::BI__builtin_isgreaterequal:
1519   case Builtin::BI__builtin_isless:
1520   case Builtin::BI__builtin_islessequal:
1521   case Builtin::BI__builtin_islessgreater:
1522   case Builtin::BI__builtin_isunordered:
1523     if (SemaBuiltinUnorderedCompare(TheCall))
1524       return ExprError();
1525     break;
1526   case Builtin::BI__builtin_fpclassify:
1527     if (SemaBuiltinFPClassification(TheCall, 6))
1528       return ExprError();
1529     break;
1530   case Builtin::BI__builtin_isfinite:
1531   case Builtin::BI__builtin_isinf:
1532   case Builtin::BI__builtin_isinf_sign:
1533   case Builtin::BI__builtin_isnan:
1534   case Builtin::BI__builtin_isnormal:
1535   case Builtin::BI__builtin_signbit:
1536   case Builtin::BI__builtin_signbitf:
1537   case Builtin::BI__builtin_signbitl:
1538     if (SemaBuiltinFPClassification(TheCall, 1))
1539       return ExprError();
1540     break;
1541   case Builtin::BI__builtin_shufflevector:
1542     return SemaBuiltinShuffleVector(TheCall);
1543     // TheCall will be freed by the smart pointer here, but that's fine, since
1544     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1545   case Builtin::BI__builtin_prefetch:
1546     if (SemaBuiltinPrefetch(TheCall))
1547       return ExprError();
1548     break;
1549   case Builtin::BI__builtin_alloca_with_align:
1550     if (SemaBuiltinAllocaWithAlign(TheCall))
1551       return ExprError();
1552     LLVM_FALLTHROUGH;
1553   case Builtin::BI__builtin_alloca:
1554     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1555         << TheCall->getDirectCallee();
1556     break;
1557   case Builtin::BI__arithmetic_fence:
1558     if (SemaBuiltinArithmeticFence(TheCall))
1559       return ExprError();
1560     break;
1561   case Builtin::BI__assume:
1562   case Builtin::BI__builtin_assume:
1563     if (SemaBuiltinAssume(TheCall))
1564       return ExprError();
1565     break;
1566   case Builtin::BI__builtin_assume_aligned:
1567     if (SemaBuiltinAssumeAligned(TheCall))
1568       return ExprError();
1569     break;
1570   case Builtin::BI__builtin_dynamic_object_size:
1571   case Builtin::BI__builtin_object_size:
1572     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__builtin_longjmp:
1576     if (SemaBuiltinLongjmp(TheCall))
1577       return ExprError();
1578     break;
1579   case Builtin::BI__builtin_setjmp:
1580     if (SemaBuiltinSetjmp(TheCall))
1581       return ExprError();
1582     break;
1583   case Builtin::BI__builtin_classify_type:
1584     if (checkArgCount(*this, TheCall, 1)) return true;
1585     TheCall->setType(Context.IntTy);
1586     break;
1587   case Builtin::BI__builtin_complex:
1588     if (SemaBuiltinComplex(TheCall))
1589       return ExprError();
1590     break;
1591   case Builtin::BI__builtin_constant_p: {
1592     if (checkArgCount(*this, TheCall, 1)) return true;
1593     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1594     if (Arg.isInvalid()) return true;
1595     TheCall->setArg(0, Arg.get());
1596     TheCall->setType(Context.IntTy);
1597     break;
1598   }
1599   case Builtin::BI__builtin_launder:
1600     return SemaBuiltinLaunder(*this, TheCall);
1601   case Builtin::BI__sync_fetch_and_add:
1602   case Builtin::BI__sync_fetch_and_add_1:
1603   case Builtin::BI__sync_fetch_and_add_2:
1604   case Builtin::BI__sync_fetch_and_add_4:
1605   case Builtin::BI__sync_fetch_and_add_8:
1606   case Builtin::BI__sync_fetch_and_add_16:
1607   case Builtin::BI__sync_fetch_and_sub:
1608   case Builtin::BI__sync_fetch_and_sub_1:
1609   case Builtin::BI__sync_fetch_and_sub_2:
1610   case Builtin::BI__sync_fetch_and_sub_4:
1611   case Builtin::BI__sync_fetch_and_sub_8:
1612   case Builtin::BI__sync_fetch_and_sub_16:
1613   case Builtin::BI__sync_fetch_and_or:
1614   case Builtin::BI__sync_fetch_and_or_1:
1615   case Builtin::BI__sync_fetch_and_or_2:
1616   case Builtin::BI__sync_fetch_and_or_4:
1617   case Builtin::BI__sync_fetch_and_or_8:
1618   case Builtin::BI__sync_fetch_and_or_16:
1619   case Builtin::BI__sync_fetch_and_and:
1620   case Builtin::BI__sync_fetch_and_and_1:
1621   case Builtin::BI__sync_fetch_and_and_2:
1622   case Builtin::BI__sync_fetch_and_and_4:
1623   case Builtin::BI__sync_fetch_and_and_8:
1624   case Builtin::BI__sync_fetch_and_and_16:
1625   case Builtin::BI__sync_fetch_and_xor:
1626   case Builtin::BI__sync_fetch_and_xor_1:
1627   case Builtin::BI__sync_fetch_and_xor_2:
1628   case Builtin::BI__sync_fetch_and_xor_4:
1629   case Builtin::BI__sync_fetch_and_xor_8:
1630   case Builtin::BI__sync_fetch_and_xor_16:
1631   case Builtin::BI__sync_fetch_and_nand:
1632   case Builtin::BI__sync_fetch_and_nand_1:
1633   case Builtin::BI__sync_fetch_and_nand_2:
1634   case Builtin::BI__sync_fetch_and_nand_4:
1635   case Builtin::BI__sync_fetch_and_nand_8:
1636   case Builtin::BI__sync_fetch_and_nand_16:
1637   case Builtin::BI__sync_add_and_fetch:
1638   case Builtin::BI__sync_add_and_fetch_1:
1639   case Builtin::BI__sync_add_and_fetch_2:
1640   case Builtin::BI__sync_add_and_fetch_4:
1641   case Builtin::BI__sync_add_and_fetch_8:
1642   case Builtin::BI__sync_add_and_fetch_16:
1643   case Builtin::BI__sync_sub_and_fetch:
1644   case Builtin::BI__sync_sub_and_fetch_1:
1645   case Builtin::BI__sync_sub_and_fetch_2:
1646   case Builtin::BI__sync_sub_and_fetch_4:
1647   case Builtin::BI__sync_sub_and_fetch_8:
1648   case Builtin::BI__sync_sub_and_fetch_16:
1649   case Builtin::BI__sync_and_and_fetch:
1650   case Builtin::BI__sync_and_and_fetch_1:
1651   case Builtin::BI__sync_and_and_fetch_2:
1652   case Builtin::BI__sync_and_and_fetch_4:
1653   case Builtin::BI__sync_and_and_fetch_8:
1654   case Builtin::BI__sync_and_and_fetch_16:
1655   case Builtin::BI__sync_or_and_fetch:
1656   case Builtin::BI__sync_or_and_fetch_1:
1657   case Builtin::BI__sync_or_and_fetch_2:
1658   case Builtin::BI__sync_or_and_fetch_4:
1659   case Builtin::BI__sync_or_and_fetch_8:
1660   case Builtin::BI__sync_or_and_fetch_16:
1661   case Builtin::BI__sync_xor_and_fetch:
1662   case Builtin::BI__sync_xor_and_fetch_1:
1663   case Builtin::BI__sync_xor_and_fetch_2:
1664   case Builtin::BI__sync_xor_and_fetch_4:
1665   case Builtin::BI__sync_xor_and_fetch_8:
1666   case Builtin::BI__sync_xor_and_fetch_16:
1667   case Builtin::BI__sync_nand_and_fetch:
1668   case Builtin::BI__sync_nand_and_fetch_1:
1669   case Builtin::BI__sync_nand_and_fetch_2:
1670   case Builtin::BI__sync_nand_and_fetch_4:
1671   case Builtin::BI__sync_nand_and_fetch_8:
1672   case Builtin::BI__sync_nand_and_fetch_16:
1673   case Builtin::BI__sync_val_compare_and_swap:
1674   case Builtin::BI__sync_val_compare_and_swap_1:
1675   case Builtin::BI__sync_val_compare_and_swap_2:
1676   case Builtin::BI__sync_val_compare_and_swap_4:
1677   case Builtin::BI__sync_val_compare_and_swap_8:
1678   case Builtin::BI__sync_val_compare_and_swap_16:
1679   case Builtin::BI__sync_bool_compare_and_swap:
1680   case Builtin::BI__sync_bool_compare_and_swap_1:
1681   case Builtin::BI__sync_bool_compare_and_swap_2:
1682   case Builtin::BI__sync_bool_compare_and_swap_4:
1683   case Builtin::BI__sync_bool_compare_and_swap_8:
1684   case Builtin::BI__sync_bool_compare_and_swap_16:
1685   case Builtin::BI__sync_lock_test_and_set:
1686   case Builtin::BI__sync_lock_test_and_set_1:
1687   case Builtin::BI__sync_lock_test_and_set_2:
1688   case Builtin::BI__sync_lock_test_and_set_4:
1689   case Builtin::BI__sync_lock_test_and_set_8:
1690   case Builtin::BI__sync_lock_test_and_set_16:
1691   case Builtin::BI__sync_lock_release:
1692   case Builtin::BI__sync_lock_release_1:
1693   case Builtin::BI__sync_lock_release_2:
1694   case Builtin::BI__sync_lock_release_4:
1695   case Builtin::BI__sync_lock_release_8:
1696   case Builtin::BI__sync_lock_release_16:
1697   case Builtin::BI__sync_swap:
1698   case Builtin::BI__sync_swap_1:
1699   case Builtin::BI__sync_swap_2:
1700   case Builtin::BI__sync_swap_4:
1701   case Builtin::BI__sync_swap_8:
1702   case Builtin::BI__sync_swap_16:
1703     return SemaBuiltinAtomicOverloaded(TheCallResult);
1704   case Builtin::BI__sync_synchronize:
1705     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1706         << TheCall->getCallee()->getSourceRange();
1707     break;
1708   case Builtin::BI__builtin_nontemporal_load:
1709   case Builtin::BI__builtin_nontemporal_store:
1710     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1711   case Builtin::BI__builtin_memcpy_inline: {
1712     clang::Expr *SizeOp = TheCall->getArg(2);
1713     // We warn about copying to or from `nullptr` pointers when `size` is
1714     // greater than 0. When `size` is value dependent we cannot evaluate its
1715     // value so we bail out.
1716     if (SizeOp->isValueDependent())
1717       break;
1718     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1719       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1720       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1721     }
1722     break;
1723   }
1724 #define BUILTIN(ID, TYPE, ATTRS)
1725 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1726   case Builtin::BI##ID: \
1727     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1728 #include "clang/Basic/Builtins.def"
1729   case Builtin::BI__annotation:
1730     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1731       return ExprError();
1732     break;
1733   case Builtin::BI__builtin_annotation:
1734     if (SemaBuiltinAnnotation(*this, TheCall))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_addressof:
1738     if (SemaBuiltinAddressof(*this, TheCall))
1739       return ExprError();
1740     break;
1741   case Builtin::BI__builtin_is_aligned:
1742   case Builtin::BI__builtin_align_up:
1743   case Builtin::BI__builtin_align_down:
1744     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_add_overflow:
1748   case Builtin::BI__builtin_sub_overflow:
1749   case Builtin::BI__builtin_mul_overflow:
1750     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1751       return ExprError();
1752     break;
1753   case Builtin::BI__builtin_operator_new:
1754   case Builtin::BI__builtin_operator_delete: {
1755     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1756     ExprResult Res =
1757         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1758     if (Res.isInvalid())
1759       CorrectDelayedTyposInExpr(TheCallResult.get());
1760     return Res;
1761   }
1762   case Builtin::BI__builtin_dump_struct: {
1763     // We first want to ensure we are called with 2 arguments
1764     if (checkArgCount(*this, TheCall, 2))
1765       return ExprError();
1766     // Ensure that the first argument is of type 'struct XX *'
1767     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1768     const QualType PtrArgType = PtrArg->getType();
1769     if (!PtrArgType->isPointerType() ||
1770         !PtrArgType->getPointeeType()->isRecordType()) {
1771       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1773           << "structure pointer";
1774       return ExprError();
1775     }
1776 
1777     // Ensure that the second argument is of type 'FunctionType'
1778     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1779     const QualType FnPtrArgType = FnPtrArg->getType();
1780     if (!FnPtrArgType->isPointerType()) {
1781       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1782           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1783           << FnPtrArgType << "'int (*)(const char *, ...)'";
1784       return ExprError();
1785     }
1786 
1787     const auto *FuncType =
1788         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1789 
1790     if (!FuncType) {
1791       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1792           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1793           << FnPtrArgType << "'int (*)(const char *, ...)'";
1794       return ExprError();
1795     }
1796 
1797     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1798       if (!FT->getNumParams()) {
1799         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1800             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1801             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1802         return ExprError();
1803       }
1804       QualType PT = FT->getParamType(0);
1805       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1806           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1807           !PT->getPointeeType().isConstQualified()) {
1808         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1809             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1810             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1811         return ExprError();
1812       }
1813     }
1814 
1815     TheCall->setType(Context.IntTy);
1816     break;
1817   }
1818   case Builtin::BI__builtin_expect_with_probability: {
1819     // We first want to ensure we are called with 3 arguments
1820     if (checkArgCount(*this, TheCall, 3))
1821       return ExprError();
1822     // then check probability is constant float in range [0.0, 1.0]
1823     const Expr *ProbArg = TheCall->getArg(2);
1824     SmallVector<PartialDiagnosticAt, 8> Notes;
1825     Expr::EvalResult Eval;
1826     Eval.Diag = &Notes;
1827     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1828         !Eval.Val.isFloat()) {
1829       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1830           << ProbArg->getSourceRange();
1831       for (const PartialDiagnosticAt &PDiag : Notes)
1832         Diag(PDiag.first, PDiag.second);
1833       return ExprError();
1834     }
1835     llvm::APFloat Probability = Eval.Val.getFloat();
1836     bool LoseInfo = false;
1837     Probability.convert(llvm::APFloat::IEEEdouble(),
1838                         llvm::RoundingMode::Dynamic, &LoseInfo);
1839     if (!(Probability >= llvm::APFloat(0.0) &&
1840           Probability <= llvm::APFloat(1.0))) {
1841       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1842           << ProbArg->getSourceRange();
1843       return ExprError();
1844     }
1845     break;
1846   }
1847   case Builtin::BI__builtin_preserve_access_index:
1848     if (SemaBuiltinPreserveAI(*this, TheCall))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__builtin_call_with_static_chain:
1852     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1853       return ExprError();
1854     break;
1855   case Builtin::BI__exception_code:
1856   case Builtin::BI_exception_code:
1857     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1858                                  diag::err_seh___except_block))
1859       return ExprError();
1860     break;
1861   case Builtin::BI__exception_info:
1862   case Builtin::BI_exception_info:
1863     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1864                                  diag::err_seh___except_filter))
1865       return ExprError();
1866     break;
1867   case Builtin::BI__GetExceptionInfo:
1868     if (checkArgCount(*this, TheCall, 1))
1869       return ExprError();
1870 
1871     if (CheckCXXThrowOperand(
1872             TheCall->getBeginLoc(),
1873             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1874             TheCall))
1875       return ExprError();
1876 
1877     TheCall->setType(Context.VoidPtrTy);
1878     break;
1879   // OpenCL v2.0, s6.13.16 - Pipe functions
1880   case Builtin::BIread_pipe:
1881   case Builtin::BIwrite_pipe:
1882     // Since those two functions are declared with var args, we need a semantic
1883     // check for the argument.
1884     if (SemaBuiltinRWPipe(*this, TheCall))
1885       return ExprError();
1886     break;
1887   case Builtin::BIreserve_read_pipe:
1888   case Builtin::BIreserve_write_pipe:
1889   case Builtin::BIwork_group_reserve_read_pipe:
1890   case Builtin::BIwork_group_reserve_write_pipe:
1891     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1892       return ExprError();
1893     break;
1894   case Builtin::BIsub_group_reserve_read_pipe:
1895   case Builtin::BIsub_group_reserve_write_pipe:
1896     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1897         SemaBuiltinReserveRWPipe(*this, TheCall))
1898       return ExprError();
1899     break;
1900   case Builtin::BIcommit_read_pipe:
1901   case Builtin::BIcommit_write_pipe:
1902   case Builtin::BIwork_group_commit_read_pipe:
1903   case Builtin::BIwork_group_commit_write_pipe:
1904     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1905       return ExprError();
1906     break;
1907   case Builtin::BIsub_group_commit_read_pipe:
1908   case Builtin::BIsub_group_commit_write_pipe:
1909     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1910         SemaBuiltinCommitRWPipe(*this, TheCall))
1911       return ExprError();
1912     break;
1913   case Builtin::BIget_pipe_num_packets:
1914   case Builtin::BIget_pipe_max_packets:
1915     if (SemaBuiltinPipePackets(*this, TheCall))
1916       return ExprError();
1917     break;
1918   case Builtin::BIto_global:
1919   case Builtin::BIto_local:
1920   case Builtin::BIto_private:
1921     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1922       return ExprError();
1923     break;
1924   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1925   case Builtin::BIenqueue_kernel:
1926     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BIget_kernel_work_group_size:
1930   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1931     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1932       return ExprError();
1933     break;
1934   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1935   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1936     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1937       return ExprError();
1938     break;
1939   case Builtin::BI__builtin_os_log_format:
1940     Cleanup.setExprNeedsCleanups(true);
1941     LLVM_FALLTHROUGH;
1942   case Builtin::BI__builtin_os_log_format_buffer_size:
1943     if (SemaBuiltinOSLogFormat(TheCall))
1944       return ExprError();
1945     break;
1946   case Builtin::BI__builtin_frame_address:
1947   case Builtin::BI__builtin_return_address: {
1948     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1949       return ExprError();
1950 
1951     // -Wframe-address warning if non-zero passed to builtin
1952     // return/frame address.
1953     Expr::EvalResult Result;
1954     if (!TheCall->getArg(0)->isValueDependent() &&
1955         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1956         Result.Val.getInt() != 0)
1957       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1958           << ((BuiltinID == Builtin::BI__builtin_return_address)
1959                   ? "__builtin_return_address"
1960                   : "__builtin_frame_address")
1961           << TheCall->getSourceRange();
1962     break;
1963   }
1964 
1965   case Builtin::BI__builtin_matrix_transpose:
1966     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1967 
1968   case Builtin::BI__builtin_matrix_column_major_load:
1969     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1970 
1971   case Builtin::BI__builtin_matrix_column_major_store:
1972     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1973 
1974   case Builtin::BI__builtin_get_device_side_mangled_name: {
1975     auto Check = [](CallExpr *TheCall) {
1976       if (TheCall->getNumArgs() != 1)
1977         return false;
1978       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1979       if (!DRE)
1980         return false;
1981       auto *D = DRE->getDecl();
1982       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1983         return false;
1984       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1985              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
1986     };
1987     if (!Check(TheCall)) {
1988       Diag(TheCall->getBeginLoc(),
1989            diag::err_hip_invalid_args_builtin_mangled_name);
1990       return ExprError();
1991     }
1992   }
1993   }
1994 
1995   // Since the target specific builtins for each arch overlap, only check those
1996   // of the arch we are compiling for.
1997   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1998     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1999       assert(Context.getAuxTargetInfo() &&
2000              "Aux Target Builtin, but not an aux target?");
2001 
2002       if (CheckTSBuiltinFunctionCall(
2003               *Context.getAuxTargetInfo(),
2004               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2005         return ExprError();
2006     } else {
2007       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2008                                      TheCall))
2009         return ExprError();
2010     }
2011   }
2012 
2013   return TheCallResult;
2014 }
2015 
2016 // Get the valid immediate range for the specified NEON type code.
2017 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2018   NeonTypeFlags Type(t);
2019   int IsQuad = ForceQuad ? true : Type.isQuad();
2020   switch (Type.getEltType()) {
2021   case NeonTypeFlags::Int8:
2022   case NeonTypeFlags::Poly8:
2023     return shift ? 7 : (8 << IsQuad) - 1;
2024   case NeonTypeFlags::Int16:
2025   case NeonTypeFlags::Poly16:
2026     return shift ? 15 : (4 << IsQuad) - 1;
2027   case NeonTypeFlags::Int32:
2028     return shift ? 31 : (2 << IsQuad) - 1;
2029   case NeonTypeFlags::Int64:
2030   case NeonTypeFlags::Poly64:
2031     return shift ? 63 : (1 << IsQuad) - 1;
2032   case NeonTypeFlags::Poly128:
2033     return shift ? 127 : (1 << IsQuad) - 1;
2034   case NeonTypeFlags::Float16:
2035     assert(!shift && "cannot shift float types!");
2036     return (4 << IsQuad) - 1;
2037   case NeonTypeFlags::Float32:
2038     assert(!shift && "cannot shift float types!");
2039     return (2 << IsQuad) - 1;
2040   case NeonTypeFlags::Float64:
2041     assert(!shift && "cannot shift float types!");
2042     return (1 << IsQuad) - 1;
2043   case NeonTypeFlags::BFloat16:
2044     assert(!shift && "cannot shift float types!");
2045     return (4 << IsQuad) - 1;
2046   }
2047   llvm_unreachable("Invalid NeonTypeFlag!");
2048 }
2049 
2050 /// getNeonEltType - Return the QualType corresponding to the elements of
2051 /// the vector type specified by the NeonTypeFlags.  This is used to check
2052 /// the pointer arguments for Neon load/store intrinsics.
2053 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2054                                bool IsPolyUnsigned, bool IsInt64Long) {
2055   switch (Flags.getEltType()) {
2056   case NeonTypeFlags::Int8:
2057     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2058   case NeonTypeFlags::Int16:
2059     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2060   case NeonTypeFlags::Int32:
2061     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2062   case NeonTypeFlags::Int64:
2063     if (IsInt64Long)
2064       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2065     else
2066       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2067                                 : Context.LongLongTy;
2068   case NeonTypeFlags::Poly8:
2069     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2070   case NeonTypeFlags::Poly16:
2071     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2072   case NeonTypeFlags::Poly64:
2073     if (IsInt64Long)
2074       return Context.UnsignedLongTy;
2075     else
2076       return Context.UnsignedLongLongTy;
2077   case NeonTypeFlags::Poly128:
2078     break;
2079   case NeonTypeFlags::Float16:
2080     return Context.HalfTy;
2081   case NeonTypeFlags::Float32:
2082     return Context.FloatTy;
2083   case NeonTypeFlags::Float64:
2084     return Context.DoubleTy;
2085   case NeonTypeFlags::BFloat16:
2086     return Context.BFloat16Ty;
2087   }
2088   llvm_unreachable("Invalid NeonTypeFlag!");
2089 }
2090 
2091 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2092   // Range check SVE intrinsics that take immediate values.
2093   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2094 
2095   switch (BuiltinID) {
2096   default:
2097     return false;
2098 #define GET_SVE_IMMEDIATE_CHECK
2099 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2100 #undef GET_SVE_IMMEDIATE_CHECK
2101   }
2102 
2103   // Perform all the immediate checks for this builtin call.
2104   bool HasError = false;
2105   for (auto &I : ImmChecks) {
2106     int ArgNum, CheckTy, ElementSizeInBits;
2107     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2108 
2109     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2110 
2111     // Function that checks whether the operand (ArgNum) is an immediate
2112     // that is one of the predefined values.
2113     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2114                                    int ErrDiag) -> bool {
2115       // We can't check the value of a dependent argument.
2116       Expr *Arg = TheCall->getArg(ArgNum);
2117       if (Arg->isTypeDependent() || Arg->isValueDependent())
2118         return false;
2119 
2120       // Check constant-ness first.
2121       llvm::APSInt Imm;
2122       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2123         return true;
2124 
2125       if (!CheckImm(Imm.getSExtValue()))
2126         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2127       return false;
2128     };
2129 
2130     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2131     case SVETypeFlags::ImmCheck0_31:
2132       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheck0_13:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2137         HasError = true;
2138       break;
2139     case SVETypeFlags::ImmCheck1_16:
2140       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2141         HasError = true;
2142       break;
2143     case SVETypeFlags::ImmCheck0_7:
2144       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2145         HasError = true;
2146       break;
2147     case SVETypeFlags::ImmCheckExtract:
2148       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2149                                       (2048 / ElementSizeInBits) - 1))
2150         HasError = true;
2151       break;
2152     case SVETypeFlags::ImmCheckShiftRight:
2153       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2154         HasError = true;
2155       break;
2156     case SVETypeFlags::ImmCheckShiftRightNarrow:
2157       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2158                                       ElementSizeInBits / 2))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckShiftLeft:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       ElementSizeInBits - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckLaneIndex:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2168                                       (128 / (1 * ElementSizeInBits)) - 1))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2173                                       (128 / (2 * ElementSizeInBits)) - 1))
2174         HasError = true;
2175       break;
2176     case SVETypeFlags::ImmCheckLaneIndexDot:
2177       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2178                                       (128 / (4 * ElementSizeInBits)) - 1))
2179         HasError = true;
2180       break;
2181     case SVETypeFlags::ImmCheckComplexRot90_270:
2182       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2183                               diag::err_rotation_argument_to_cadd))
2184         HasError = true;
2185       break;
2186     case SVETypeFlags::ImmCheckComplexRotAll90:
2187       if (CheckImmediateInSet(
2188               [](int64_t V) {
2189                 return V == 0 || V == 90 || V == 180 || V == 270;
2190               },
2191               diag::err_rotation_argument_to_cmla))
2192         HasError = true;
2193       break;
2194     case SVETypeFlags::ImmCheck0_1:
2195       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2196         HasError = true;
2197       break;
2198     case SVETypeFlags::ImmCheck0_2:
2199       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2200         HasError = true;
2201       break;
2202     case SVETypeFlags::ImmCheck0_3:
2203       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2204         HasError = true;
2205       break;
2206     }
2207   }
2208 
2209   return HasError;
2210 }
2211 
2212 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2213                                         unsigned BuiltinID, CallExpr *TheCall) {
2214   llvm::APSInt Result;
2215   uint64_t mask = 0;
2216   unsigned TV = 0;
2217   int PtrArgNum = -1;
2218   bool HasConstPtr = false;
2219   switch (BuiltinID) {
2220 #define GET_NEON_OVERLOAD_CHECK
2221 #include "clang/Basic/arm_neon.inc"
2222 #include "clang/Basic/arm_fp16.inc"
2223 #undef GET_NEON_OVERLOAD_CHECK
2224   }
2225 
2226   // For NEON intrinsics which are overloaded on vector element type, validate
2227   // the immediate which specifies which variant to emit.
2228   unsigned ImmArg = TheCall->getNumArgs()-1;
2229   if (mask) {
2230     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2231       return true;
2232 
2233     TV = Result.getLimitedValue(64);
2234     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2235       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2236              << TheCall->getArg(ImmArg)->getSourceRange();
2237   }
2238 
2239   if (PtrArgNum >= 0) {
2240     // Check that pointer arguments have the specified type.
2241     Expr *Arg = TheCall->getArg(PtrArgNum);
2242     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2243       Arg = ICE->getSubExpr();
2244     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2245     QualType RHSTy = RHS.get()->getType();
2246 
2247     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2248     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2249                           Arch == llvm::Triple::aarch64_32 ||
2250                           Arch == llvm::Triple::aarch64_be;
2251     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2252     QualType EltTy =
2253         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2254     if (HasConstPtr)
2255       EltTy = EltTy.withConst();
2256     QualType LHSTy = Context.getPointerType(EltTy);
2257     AssignConvertType ConvTy;
2258     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2259     if (RHS.isInvalid())
2260       return true;
2261     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2262                                  RHS.get(), AA_Assigning))
2263       return true;
2264   }
2265 
2266   // For NEON intrinsics which take an immediate value as part of the
2267   // instruction, range check them here.
2268   unsigned i = 0, l = 0, u = 0;
2269   switch (BuiltinID) {
2270   default:
2271     return false;
2272   #define GET_NEON_IMMEDIATE_CHECK
2273   #include "clang/Basic/arm_neon.inc"
2274   #include "clang/Basic/arm_fp16.inc"
2275   #undef GET_NEON_IMMEDIATE_CHECK
2276   }
2277 
2278   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2279 }
2280 
2281 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2282   switch (BuiltinID) {
2283   default:
2284     return false;
2285   #include "clang/Basic/arm_mve_builtin_sema.inc"
2286   }
2287 }
2288 
2289 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2290                                        CallExpr *TheCall) {
2291   bool Err = false;
2292   switch (BuiltinID) {
2293   default:
2294     return false;
2295 #include "clang/Basic/arm_cde_builtin_sema.inc"
2296   }
2297 
2298   if (Err)
2299     return true;
2300 
2301   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2302 }
2303 
2304 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2305                                         const Expr *CoprocArg, bool WantCDE) {
2306   if (isConstantEvaluated())
2307     return false;
2308 
2309   // We can't check the value of a dependent argument.
2310   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2311     return false;
2312 
2313   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2314   int64_t CoprocNo = CoprocNoAP.getExtValue();
2315   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2316 
2317   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2318   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2319 
2320   if (IsCDECoproc != WantCDE)
2321     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2322            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2323 
2324   return false;
2325 }
2326 
2327 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2328                                         unsigned MaxWidth) {
2329   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2330           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2331           BuiltinID == ARM::BI__builtin_arm_strex ||
2332           BuiltinID == ARM::BI__builtin_arm_stlex ||
2333           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2334           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2335           BuiltinID == AArch64::BI__builtin_arm_strex ||
2336           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2337          "unexpected ARM builtin");
2338   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2339                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2340                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2341                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2342 
2343   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2344 
2345   // Ensure that we have the proper number of arguments.
2346   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2347     return true;
2348 
2349   // Inspect the pointer argument of the atomic builtin.  This should always be
2350   // a pointer type, whose element is an integral scalar or pointer type.
2351   // Because it is a pointer type, we don't have to worry about any implicit
2352   // casts here.
2353   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2354   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2355   if (PointerArgRes.isInvalid())
2356     return true;
2357   PointerArg = PointerArgRes.get();
2358 
2359   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2360   if (!pointerType) {
2361     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2362         << PointerArg->getType() << PointerArg->getSourceRange();
2363     return true;
2364   }
2365 
2366   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2367   // task is to insert the appropriate casts into the AST. First work out just
2368   // what the appropriate type is.
2369   QualType ValType = pointerType->getPointeeType();
2370   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2371   if (IsLdrex)
2372     AddrType.addConst();
2373 
2374   // Issue a warning if the cast is dodgy.
2375   CastKind CastNeeded = CK_NoOp;
2376   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2377     CastNeeded = CK_BitCast;
2378     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2379         << PointerArg->getType() << Context.getPointerType(AddrType)
2380         << AA_Passing << PointerArg->getSourceRange();
2381   }
2382 
2383   // Finally, do the cast and replace the argument with the corrected version.
2384   AddrType = Context.getPointerType(AddrType);
2385   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2386   if (PointerArgRes.isInvalid())
2387     return true;
2388   PointerArg = PointerArgRes.get();
2389 
2390   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2391 
2392   // In general, we allow ints, floats and pointers to be loaded and stored.
2393   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2394       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2395     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2396         << PointerArg->getType() << PointerArg->getSourceRange();
2397     return true;
2398   }
2399 
2400   // But ARM doesn't have instructions to deal with 128-bit versions.
2401   if (Context.getTypeSize(ValType) > MaxWidth) {
2402     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2403     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2404         << PointerArg->getType() << PointerArg->getSourceRange();
2405     return true;
2406   }
2407 
2408   switch (ValType.getObjCLifetime()) {
2409   case Qualifiers::OCL_None:
2410   case Qualifiers::OCL_ExplicitNone:
2411     // okay
2412     break;
2413 
2414   case Qualifiers::OCL_Weak:
2415   case Qualifiers::OCL_Strong:
2416   case Qualifiers::OCL_Autoreleasing:
2417     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2418         << ValType << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   if (IsLdrex) {
2423     TheCall->setType(ValType);
2424     return false;
2425   }
2426 
2427   // Initialize the argument to be stored.
2428   ExprResult ValArg = TheCall->getArg(0);
2429   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2430       Context, ValType, /*consume*/ false);
2431   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2432   if (ValArg.isInvalid())
2433     return true;
2434   TheCall->setArg(0, ValArg.get());
2435 
2436   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2437   // but the custom checker bypasses all default analysis.
2438   TheCall->setType(Context.IntTy);
2439   return false;
2440 }
2441 
2442 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2443                                        CallExpr *TheCall) {
2444   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2445       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2446       BuiltinID == ARM::BI__builtin_arm_strex ||
2447       BuiltinID == ARM::BI__builtin_arm_stlex) {
2448     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2449   }
2450 
2451   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2452     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2453       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2454   }
2455 
2456   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2457       BuiltinID == ARM::BI__builtin_arm_wsr64)
2458     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2459 
2460   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2461       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2462       BuiltinID == ARM::BI__builtin_arm_wsr ||
2463       BuiltinID == ARM::BI__builtin_arm_wsrp)
2464     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2465 
2466   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2467     return true;
2468   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2469     return true;
2470   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2471     return true;
2472 
2473   // For intrinsics which take an immediate value as part of the instruction,
2474   // range check them here.
2475   // FIXME: VFP Intrinsics should error if VFP not present.
2476   switch (BuiltinID) {
2477   default: return false;
2478   case ARM::BI__builtin_arm_ssat:
2479     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2480   case ARM::BI__builtin_arm_usat:
2481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2482   case ARM::BI__builtin_arm_ssat16:
2483     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2484   case ARM::BI__builtin_arm_usat16:
2485     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2486   case ARM::BI__builtin_arm_vcvtr_f:
2487   case ARM::BI__builtin_arm_vcvtr_d:
2488     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2489   case ARM::BI__builtin_arm_dmb:
2490   case ARM::BI__builtin_arm_dsb:
2491   case ARM::BI__builtin_arm_isb:
2492   case ARM::BI__builtin_arm_dbg:
2493     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2494   case ARM::BI__builtin_arm_cdp:
2495   case ARM::BI__builtin_arm_cdp2:
2496   case ARM::BI__builtin_arm_mcr:
2497   case ARM::BI__builtin_arm_mcr2:
2498   case ARM::BI__builtin_arm_mrc:
2499   case ARM::BI__builtin_arm_mrc2:
2500   case ARM::BI__builtin_arm_mcrr:
2501   case ARM::BI__builtin_arm_mcrr2:
2502   case ARM::BI__builtin_arm_mrrc:
2503   case ARM::BI__builtin_arm_mrrc2:
2504   case ARM::BI__builtin_arm_ldc:
2505   case ARM::BI__builtin_arm_ldcl:
2506   case ARM::BI__builtin_arm_ldc2:
2507   case ARM::BI__builtin_arm_ldc2l:
2508   case ARM::BI__builtin_arm_stc:
2509   case ARM::BI__builtin_arm_stcl:
2510   case ARM::BI__builtin_arm_stc2:
2511   case ARM::BI__builtin_arm_stc2l:
2512     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2513            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2514                                         /*WantCDE*/ false);
2515   }
2516 }
2517 
2518 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2519                                            unsigned BuiltinID,
2520                                            CallExpr *TheCall) {
2521   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2522       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2523       BuiltinID == AArch64::BI__builtin_arm_strex ||
2524       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2525     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2526   }
2527 
2528   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2529     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2530       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2531       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2532       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2533   }
2534 
2535   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2536       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2537     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2538 
2539   // Memory Tagging Extensions (MTE) Intrinsics
2540   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2541       BuiltinID == AArch64::BI__builtin_arm_addg ||
2542       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2543       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2544       BuiltinID == AArch64::BI__builtin_arm_stg ||
2545       BuiltinID == AArch64::BI__builtin_arm_subp) {
2546     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2550       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2551       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2552       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2553     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2554 
2555   // Only check the valid encoding range. Any constant in this range would be
2556   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2557   // an exception for incorrect registers. This matches MSVC behavior.
2558   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2559       BuiltinID == AArch64::BI_WriteStatusReg)
2560     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2561 
2562   if (BuiltinID == AArch64::BI__getReg)
2563     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2564 
2565   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2566     return true;
2567 
2568   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2569     return true;
2570 
2571   // For intrinsics which take an immediate value as part of the instruction,
2572   // range check them here.
2573   unsigned i = 0, l = 0, u = 0;
2574   switch (BuiltinID) {
2575   default: return false;
2576   case AArch64::BI__builtin_arm_dmb:
2577   case AArch64::BI__builtin_arm_dsb:
2578   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2579   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2580   }
2581 
2582   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2583 }
2584 
2585 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2586   if (Arg->getType()->getAsPlaceholderType())
2587     return false;
2588 
2589   // The first argument needs to be a record field access.
2590   // If it is an array element access, we delay decision
2591   // to BPF backend to check whether the access is a
2592   // field access or not.
2593   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2594           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2595           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2596 }
2597 
2598 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2599                             QualType VectorTy, QualType EltTy) {
2600   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2601   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2602     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2603         << Call->getSourceRange() << VectorEltTy << EltTy;
2604     return false;
2605   }
2606   return true;
2607 }
2608 
2609 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2610   QualType ArgType = Arg->getType();
2611   if (ArgType->getAsPlaceholderType())
2612     return false;
2613 
2614   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2615   // format:
2616   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2617   //   2. <type> var;
2618   //      __builtin_preserve_type_info(var, flag);
2619   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2620       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2621     return false;
2622 
2623   // Typedef type.
2624   if (ArgType->getAs<TypedefType>())
2625     return true;
2626 
2627   // Record type or Enum type.
2628   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2629   if (const auto *RT = Ty->getAs<RecordType>()) {
2630     if (!RT->getDecl()->getDeclName().isEmpty())
2631       return true;
2632   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2633     if (!ET->getDecl()->getDeclName().isEmpty())
2634       return true;
2635   }
2636 
2637   return false;
2638 }
2639 
2640 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2641   QualType ArgType = Arg->getType();
2642   if (ArgType->getAsPlaceholderType())
2643     return false;
2644 
2645   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2646   // format:
2647   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2648   //                                 flag);
2649   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2650   if (!UO)
2651     return false;
2652 
2653   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2654   if (!CE)
2655     return false;
2656   if (CE->getCastKind() != CK_IntegralToPointer &&
2657       CE->getCastKind() != CK_NullToPointer)
2658     return false;
2659 
2660   // The integer must be from an EnumConstantDecl.
2661   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2662   if (!DR)
2663     return false;
2664 
2665   const EnumConstantDecl *Enumerator =
2666       dyn_cast<EnumConstantDecl>(DR->getDecl());
2667   if (!Enumerator)
2668     return false;
2669 
2670   // The type must be EnumType.
2671   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2672   const auto *ET = Ty->getAs<EnumType>();
2673   if (!ET)
2674     return false;
2675 
2676   // The enum value must be supported.
2677   for (auto *EDI : ET->getDecl()->enumerators()) {
2678     if (EDI == Enumerator)
2679       return true;
2680   }
2681 
2682   return false;
2683 }
2684 
2685 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2686                                        CallExpr *TheCall) {
2687   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2688           BuiltinID == BPF::BI__builtin_btf_type_id ||
2689           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2690           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2691          "unexpected BPF builtin");
2692 
2693   if (checkArgCount(*this, TheCall, 2))
2694     return true;
2695 
2696   // The second argument needs to be a constant int
2697   Expr *Arg = TheCall->getArg(1);
2698   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2699   diag::kind kind;
2700   if (!Value) {
2701     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2702       kind = diag::err_preserve_field_info_not_const;
2703     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2704       kind = diag::err_btf_type_id_not_const;
2705     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2706       kind = diag::err_preserve_type_info_not_const;
2707     else
2708       kind = diag::err_preserve_enum_value_not_const;
2709     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2710     return true;
2711   }
2712 
2713   // The first argument
2714   Arg = TheCall->getArg(0);
2715   bool InvalidArg = false;
2716   bool ReturnUnsignedInt = true;
2717   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2718     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2719       InvalidArg = true;
2720       kind = diag::err_preserve_field_info_not_field;
2721     }
2722   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2723     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2724       InvalidArg = true;
2725       kind = diag::err_preserve_type_info_invalid;
2726     }
2727   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2728     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2729       InvalidArg = true;
2730       kind = diag::err_preserve_enum_value_invalid;
2731     }
2732     ReturnUnsignedInt = false;
2733   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2734     ReturnUnsignedInt = false;
2735   }
2736 
2737   if (InvalidArg) {
2738     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2739     return true;
2740   }
2741 
2742   if (ReturnUnsignedInt)
2743     TheCall->setType(Context.UnsignedIntTy);
2744   else
2745     TheCall->setType(Context.UnsignedLongTy);
2746   return false;
2747 }
2748 
2749 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2750   struct ArgInfo {
2751     uint8_t OpNum;
2752     bool IsSigned;
2753     uint8_t BitWidth;
2754     uint8_t Align;
2755   };
2756   struct BuiltinInfo {
2757     unsigned BuiltinID;
2758     ArgInfo Infos[2];
2759   };
2760 
2761   static BuiltinInfo Infos[] = {
2762     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2763     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2764     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2765     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2766     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2767     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2768     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2769     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2770     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2771     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2772     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2773 
2774     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2777     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2778     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2779     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2785 
2786     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2838                                                       {{ 1, false, 6,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2846                                                       {{ 1, false, 5,  0 }} },
2847     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2853                                                        { 2, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2855                                                        { 2, false, 6,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2857                                                        { 3, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2859                                                        { 3, false, 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2862     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2864     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2876                                                       {{ 2, false, 4,  0 },
2877                                                        { 3, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2879                                                       {{ 2, false, 4,  0 },
2880                                                        { 3, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2882                                                       {{ 2, false, 4,  0 },
2883                                                        { 3, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2885                                                       {{ 2, false, 4,  0 },
2886                                                        { 3, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2898                                                        { 2, false, 5,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2900                                                        { 2, false, 6,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2909     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2910                                                       {{ 1, false, 4,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2913                                                       {{ 1, false, 4,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2919     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2922     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2934                                                       {{ 3, false, 1,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2939                                                       {{ 3, false, 1,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2943     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2944                                                       {{ 3, false, 1,  0 }} },
2945   };
2946 
2947   // Use a dynamically initialized static to sort the table exactly once on
2948   // first run.
2949   static const bool SortOnce =
2950       (llvm::sort(Infos,
2951                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2952                    return LHS.BuiltinID < RHS.BuiltinID;
2953                  }),
2954        true);
2955   (void)SortOnce;
2956 
2957   const BuiltinInfo *F = llvm::partition_point(
2958       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2959   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2960     return false;
2961 
2962   bool Error = false;
2963 
2964   for (const ArgInfo &A : F->Infos) {
2965     // Ignore empty ArgInfo elements.
2966     if (A.BitWidth == 0)
2967       continue;
2968 
2969     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2970     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2971     if (!A.Align) {
2972       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2973     } else {
2974       unsigned M = 1 << A.Align;
2975       Min *= M;
2976       Max *= M;
2977       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2978                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2979     }
2980   }
2981   return Error;
2982 }
2983 
2984 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2985                                            CallExpr *TheCall) {
2986   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2987 }
2988 
2989 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2990                                         unsigned BuiltinID, CallExpr *TheCall) {
2991   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2992          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2993 }
2994 
2995 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2996                                CallExpr *TheCall) {
2997 
2998   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2999       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3000     if (!TI.hasFeature("dsp"))
3001       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3002   }
3003 
3004   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3005       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3006     if (!TI.hasFeature("dspr2"))
3007       return Diag(TheCall->getBeginLoc(),
3008                   diag::err_mips_builtin_requires_dspr2);
3009   }
3010 
3011   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3012       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3013     if (!TI.hasFeature("msa"))
3014       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3015   }
3016 
3017   return false;
3018 }
3019 
3020 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3021 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3022 // ordering for DSP is unspecified. MSA is ordered by the data format used
3023 // by the underlying instruction i.e., df/m, df/n and then by size.
3024 //
3025 // FIXME: The size tests here should instead be tablegen'd along with the
3026 //        definitions from include/clang/Basic/BuiltinsMips.def.
3027 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3028 //        be too.
3029 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3030   unsigned i = 0, l = 0, u = 0, m = 0;
3031   switch (BuiltinID) {
3032   default: return false;
3033   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3034   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3035   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3036   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3037   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3038   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3039   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3040   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3041   // df/m field.
3042   // These intrinsics take an unsigned 3 bit immediate.
3043   case Mips::BI__builtin_msa_bclri_b:
3044   case Mips::BI__builtin_msa_bnegi_b:
3045   case Mips::BI__builtin_msa_bseti_b:
3046   case Mips::BI__builtin_msa_sat_s_b:
3047   case Mips::BI__builtin_msa_sat_u_b:
3048   case Mips::BI__builtin_msa_slli_b:
3049   case Mips::BI__builtin_msa_srai_b:
3050   case Mips::BI__builtin_msa_srari_b:
3051   case Mips::BI__builtin_msa_srli_b:
3052   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3053   case Mips::BI__builtin_msa_binsli_b:
3054   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3055   // These intrinsics take an unsigned 4 bit immediate.
3056   case Mips::BI__builtin_msa_bclri_h:
3057   case Mips::BI__builtin_msa_bnegi_h:
3058   case Mips::BI__builtin_msa_bseti_h:
3059   case Mips::BI__builtin_msa_sat_s_h:
3060   case Mips::BI__builtin_msa_sat_u_h:
3061   case Mips::BI__builtin_msa_slli_h:
3062   case Mips::BI__builtin_msa_srai_h:
3063   case Mips::BI__builtin_msa_srari_h:
3064   case Mips::BI__builtin_msa_srli_h:
3065   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3066   case Mips::BI__builtin_msa_binsli_h:
3067   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3068   // These intrinsics take an unsigned 5 bit immediate.
3069   // The first block of intrinsics actually have an unsigned 5 bit field,
3070   // not a df/n field.
3071   case Mips::BI__builtin_msa_cfcmsa:
3072   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3073   case Mips::BI__builtin_msa_clei_u_b:
3074   case Mips::BI__builtin_msa_clei_u_h:
3075   case Mips::BI__builtin_msa_clei_u_w:
3076   case Mips::BI__builtin_msa_clei_u_d:
3077   case Mips::BI__builtin_msa_clti_u_b:
3078   case Mips::BI__builtin_msa_clti_u_h:
3079   case Mips::BI__builtin_msa_clti_u_w:
3080   case Mips::BI__builtin_msa_clti_u_d:
3081   case Mips::BI__builtin_msa_maxi_u_b:
3082   case Mips::BI__builtin_msa_maxi_u_h:
3083   case Mips::BI__builtin_msa_maxi_u_w:
3084   case Mips::BI__builtin_msa_maxi_u_d:
3085   case Mips::BI__builtin_msa_mini_u_b:
3086   case Mips::BI__builtin_msa_mini_u_h:
3087   case Mips::BI__builtin_msa_mini_u_w:
3088   case Mips::BI__builtin_msa_mini_u_d:
3089   case Mips::BI__builtin_msa_addvi_b:
3090   case Mips::BI__builtin_msa_addvi_h:
3091   case Mips::BI__builtin_msa_addvi_w:
3092   case Mips::BI__builtin_msa_addvi_d:
3093   case Mips::BI__builtin_msa_bclri_w:
3094   case Mips::BI__builtin_msa_bnegi_w:
3095   case Mips::BI__builtin_msa_bseti_w:
3096   case Mips::BI__builtin_msa_sat_s_w:
3097   case Mips::BI__builtin_msa_sat_u_w:
3098   case Mips::BI__builtin_msa_slli_w:
3099   case Mips::BI__builtin_msa_srai_w:
3100   case Mips::BI__builtin_msa_srari_w:
3101   case Mips::BI__builtin_msa_srli_w:
3102   case Mips::BI__builtin_msa_srlri_w:
3103   case Mips::BI__builtin_msa_subvi_b:
3104   case Mips::BI__builtin_msa_subvi_h:
3105   case Mips::BI__builtin_msa_subvi_w:
3106   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3107   case Mips::BI__builtin_msa_binsli_w:
3108   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3109   // These intrinsics take an unsigned 6 bit immediate.
3110   case Mips::BI__builtin_msa_bclri_d:
3111   case Mips::BI__builtin_msa_bnegi_d:
3112   case Mips::BI__builtin_msa_bseti_d:
3113   case Mips::BI__builtin_msa_sat_s_d:
3114   case Mips::BI__builtin_msa_sat_u_d:
3115   case Mips::BI__builtin_msa_slli_d:
3116   case Mips::BI__builtin_msa_srai_d:
3117   case Mips::BI__builtin_msa_srari_d:
3118   case Mips::BI__builtin_msa_srli_d:
3119   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3120   case Mips::BI__builtin_msa_binsli_d:
3121   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3122   // These intrinsics take a signed 5 bit immediate.
3123   case Mips::BI__builtin_msa_ceqi_b:
3124   case Mips::BI__builtin_msa_ceqi_h:
3125   case Mips::BI__builtin_msa_ceqi_w:
3126   case Mips::BI__builtin_msa_ceqi_d:
3127   case Mips::BI__builtin_msa_clti_s_b:
3128   case Mips::BI__builtin_msa_clti_s_h:
3129   case Mips::BI__builtin_msa_clti_s_w:
3130   case Mips::BI__builtin_msa_clti_s_d:
3131   case Mips::BI__builtin_msa_clei_s_b:
3132   case Mips::BI__builtin_msa_clei_s_h:
3133   case Mips::BI__builtin_msa_clei_s_w:
3134   case Mips::BI__builtin_msa_clei_s_d:
3135   case Mips::BI__builtin_msa_maxi_s_b:
3136   case Mips::BI__builtin_msa_maxi_s_h:
3137   case Mips::BI__builtin_msa_maxi_s_w:
3138   case Mips::BI__builtin_msa_maxi_s_d:
3139   case Mips::BI__builtin_msa_mini_s_b:
3140   case Mips::BI__builtin_msa_mini_s_h:
3141   case Mips::BI__builtin_msa_mini_s_w:
3142   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3143   // These intrinsics take an unsigned 8 bit immediate.
3144   case Mips::BI__builtin_msa_andi_b:
3145   case Mips::BI__builtin_msa_nori_b:
3146   case Mips::BI__builtin_msa_ori_b:
3147   case Mips::BI__builtin_msa_shf_b:
3148   case Mips::BI__builtin_msa_shf_h:
3149   case Mips::BI__builtin_msa_shf_w:
3150   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3151   case Mips::BI__builtin_msa_bseli_b:
3152   case Mips::BI__builtin_msa_bmnzi_b:
3153   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3154   // df/n format
3155   // These intrinsics take an unsigned 4 bit immediate.
3156   case Mips::BI__builtin_msa_copy_s_b:
3157   case Mips::BI__builtin_msa_copy_u_b:
3158   case Mips::BI__builtin_msa_insve_b:
3159   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3160   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3161   // These intrinsics take an unsigned 3 bit immediate.
3162   case Mips::BI__builtin_msa_copy_s_h:
3163   case Mips::BI__builtin_msa_copy_u_h:
3164   case Mips::BI__builtin_msa_insve_h:
3165   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3166   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3167   // These intrinsics take an unsigned 2 bit immediate.
3168   case Mips::BI__builtin_msa_copy_s_w:
3169   case Mips::BI__builtin_msa_copy_u_w:
3170   case Mips::BI__builtin_msa_insve_w:
3171   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3172   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3173   // These intrinsics take an unsigned 1 bit immediate.
3174   case Mips::BI__builtin_msa_copy_s_d:
3175   case Mips::BI__builtin_msa_copy_u_d:
3176   case Mips::BI__builtin_msa_insve_d:
3177   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3178   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3179   // Memory offsets and immediate loads.
3180   // These intrinsics take a signed 10 bit immediate.
3181   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3182   case Mips::BI__builtin_msa_ldi_h:
3183   case Mips::BI__builtin_msa_ldi_w:
3184   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3185   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3186   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3187   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3188   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3189   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3190   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3191   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3192   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3193   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3194   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3195   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3196   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3197   }
3198 
3199   if (!m)
3200     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3201 
3202   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3203          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3204 }
3205 
3206 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3207 /// advancing the pointer over the consumed characters. The decoded type is
3208 /// returned. If the decoded type represents a constant integer with a
3209 /// constraint on its value then Mask is set to that value. The type descriptors
3210 /// used in Str are specific to PPC MMA builtins and are documented in the file
3211 /// defining the PPC builtins.
3212 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3213                                         unsigned &Mask) {
3214   bool RequireICE = false;
3215   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3216   switch (*Str++) {
3217   case 'V':
3218     return Context.getVectorType(Context.UnsignedCharTy, 16,
3219                                  VectorType::VectorKind::AltiVecVector);
3220   case 'i': {
3221     char *End;
3222     unsigned size = strtoul(Str, &End, 10);
3223     assert(End != Str && "Missing constant parameter constraint");
3224     Str = End;
3225     Mask = size;
3226     return Context.IntTy;
3227   }
3228   case 'W': {
3229     char *End;
3230     unsigned size = strtoul(Str, &End, 10);
3231     assert(End != Str && "Missing PowerPC MMA type size");
3232     Str = End;
3233     QualType Type;
3234     switch (size) {
3235   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3236     case size: Type = Context.Id##Ty; break;
3237   #include "clang/Basic/PPCTypes.def"
3238     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3239     }
3240     bool CheckVectorArgs = false;
3241     while (!CheckVectorArgs) {
3242       switch (*Str++) {
3243       case '*':
3244         Type = Context.getPointerType(Type);
3245         break;
3246       case 'C':
3247         Type = Type.withConst();
3248         break;
3249       default:
3250         CheckVectorArgs = true;
3251         --Str;
3252         break;
3253       }
3254     }
3255     return Type;
3256   }
3257   default:
3258     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3259   }
3260 }
3261 
3262 static bool isPPC_64Builtin(unsigned BuiltinID) {
3263   // These builtins only work on PPC 64bit targets.
3264   switch (BuiltinID) {
3265   case PPC::BI__builtin_divde:
3266   case PPC::BI__builtin_divdeu:
3267   case PPC::BI__builtin_bpermd:
3268   case PPC::BI__builtin_ppc_ldarx:
3269   case PPC::BI__builtin_ppc_stdcx:
3270   case PPC::BI__builtin_ppc_tdw:
3271   case PPC::BI__builtin_ppc_trapd:
3272   case PPC::BI__builtin_ppc_cmpeqb:
3273   case PPC::BI__builtin_ppc_setb:
3274   case PPC::BI__builtin_ppc_mulhd:
3275   case PPC::BI__builtin_ppc_mulhdu:
3276   case PPC::BI__builtin_ppc_maddhd:
3277   case PPC::BI__builtin_ppc_maddhdu:
3278   case PPC::BI__builtin_ppc_maddld:
3279   case PPC::BI__builtin_ppc_load8r:
3280   case PPC::BI__builtin_ppc_store8r:
3281   case PPC::BI__builtin_ppc_insert_exp:
3282   case PPC::BI__builtin_ppc_extract_sig:
3283     return true;
3284   }
3285   return false;
3286 }
3287 
3288 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3289                              StringRef FeatureToCheck, unsigned DiagID,
3290                              StringRef DiagArg = "") {
3291   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3292     return false;
3293 
3294   if (DiagArg.empty())
3295     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3296   else
3297     S.Diag(TheCall->getBeginLoc(), DiagID)
3298         << DiagArg << TheCall->getSourceRange();
3299 
3300   return true;
3301 }
3302 
3303 /// Returns true if the argument consists of one contiguous run of 1s with any
3304 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3305 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3306 /// since all 1s are not contiguous.
3307 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3308   llvm::APSInt Result;
3309   // We can't check the value of a dependent argument.
3310   Expr *Arg = TheCall->getArg(ArgNum);
3311   if (Arg->isTypeDependent() || Arg->isValueDependent())
3312     return false;
3313 
3314   // Check constant-ness first.
3315   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3316     return true;
3317 
3318   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3319   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3320     return false;
3321 
3322   return Diag(TheCall->getBeginLoc(),
3323               diag::err_argument_not_contiguous_bit_field)
3324          << ArgNum << Arg->getSourceRange();
3325 }
3326 
3327 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3328                                        CallExpr *TheCall) {
3329   unsigned i = 0, l = 0, u = 0;
3330   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3331   llvm::APSInt Result;
3332 
3333   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3334     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3335            << TheCall->getSourceRange();
3336 
3337   switch (BuiltinID) {
3338   default: return false;
3339   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3340   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3341     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3342            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3343   case PPC::BI__builtin_altivec_dss:
3344     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3345   case PPC::BI__builtin_tbegin:
3346   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3347   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3348   case PPC::BI__builtin_tabortwc:
3349   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3350   case PPC::BI__builtin_tabortwci:
3351   case PPC::BI__builtin_tabortdci:
3352     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3353            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3354   case PPC::BI__builtin_altivec_dst:
3355   case PPC::BI__builtin_altivec_dstt:
3356   case PPC::BI__builtin_altivec_dstst:
3357   case PPC::BI__builtin_altivec_dststt:
3358     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3359   case PPC::BI__builtin_vsx_xxpermdi:
3360   case PPC::BI__builtin_vsx_xxsldwi:
3361     return SemaBuiltinVSX(TheCall);
3362   case PPC::BI__builtin_divwe:
3363   case PPC::BI__builtin_divweu:
3364   case PPC::BI__builtin_divde:
3365   case PPC::BI__builtin_divdeu:
3366     return SemaFeatureCheck(*this, TheCall, "extdiv",
3367                             diag::err_ppc_builtin_only_on_arch, "7");
3368   case PPC::BI__builtin_bpermd:
3369     return SemaFeatureCheck(*this, TheCall, "bpermd",
3370                             diag::err_ppc_builtin_only_on_arch, "7");
3371   case PPC::BI__builtin_unpack_vector_int128:
3372     return SemaFeatureCheck(*this, TheCall, "vsx",
3373                             diag::err_ppc_builtin_only_on_arch, "7") ||
3374            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3375   case PPC::BI__builtin_pack_vector_int128:
3376     return SemaFeatureCheck(*this, TheCall, "vsx",
3377                             diag::err_ppc_builtin_only_on_arch, "7");
3378   case PPC::BI__builtin_altivec_vgnb:
3379      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3380   case PPC::BI__builtin_altivec_vec_replace_elt:
3381   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3382     QualType VecTy = TheCall->getArg(0)->getType();
3383     QualType EltTy = TheCall->getArg(1)->getType();
3384     unsigned Width = Context.getIntWidth(EltTy);
3385     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3386            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3387   }
3388   case PPC::BI__builtin_vsx_xxeval:
3389      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3390   case PPC::BI__builtin_altivec_vsldbi:
3391      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3392   case PPC::BI__builtin_altivec_vsrdbi:
3393      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3394   case PPC::BI__builtin_vsx_xxpermx:
3395      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3396   case PPC::BI__builtin_ppc_tw:
3397   case PPC::BI__builtin_ppc_tdw:
3398     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3399   case PPC::BI__builtin_ppc_cmpeqb:
3400   case PPC::BI__builtin_ppc_setb:
3401   case PPC::BI__builtin_ppc_maddhd:
3402   case PPC::BI__builtin_ppc_maddhdu:
3403   case PPC::BI__builtin_ppc_maddld:
3404     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3405                             diag::err_ppc_builtin_only_on_arch, "9");
3406   case PPC::BI__builtin_ppc_cmprb:
3407     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3408                             diag::err_ppc_builtin_only_on_arch, "9") ||
3409            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3410   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3411   // be a constant that represents a contiguous bit field.
3412   case PPC::BI__builtin_ppc_rlwnm:
3413     return SemaBuiltinConstantArg(TheCall, 1, Result) ||
3414            SemaValueIsRunOfOnes(TheCall, 2);
3415   case PPC::BI__builtin_ppc_rlwimi:
3416   case PPC::BI__builtin_ppc_rldimi:
3417     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3418            SemaValueIsRunOfOnes(TheCall, 3);
3419   case PPC::BI__builtin_ppc_extract_exp:
3420   case PPC::BI__builtin_ppc_extract_sig:
3421   case PPC::BI__builtin_ppc_insert_exp:
3422     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3423                             diag::err_ppc_builtin_only_on_arch, "9");
3424   case PPC::BI__builtin_ppc_mtfsb0:
3425   case PPC::BI__builtin_ppc_mtfsb1:
3426     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3427   case PPC::BI__builtin_ppc_mtfsf:
3428     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3429   case PPC::BI__builtin_ppc_mtfsfi:
3430     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3431            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3432   case PPC::BI__builtin_ppc_alignx:
3433     return SemaBuiltinConstantArgPower2(TheCall, 0);
3434   case PPC::BI__builtin_ppc_rdlam:
3435     return SemaValueIsRunOfOnes(TheCall, 2);
3436   case PPC::BI__builtin_ppc_icbt:
3437     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3438                             diag::err_ppc_builtin_only_on_arch, "8");
3439 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc) \
3440   case PPC::BI__builtin_##Name: \
3441     return SemaBuiltinPPCMMACall(TheCall, Types);
3442 #include "clang/Basic/BuiltinsPPC.def"
3443   }
3444   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3445 }
3446 
3447 // Check if the given type is a non-pointer PPC MMA type. This function is used
3448 // in Sema to prevent invalid uses of restricted PPC MMA types.
3449 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3450   if (Type->isPointerType() || Type->isArrayType())
3451     return false;
3452 
3453   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3454 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3455   if (false
3456 #include "clang/Basic/PPCTypes.def"
3457      ) {
3458     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3459     return true;
3460   }
3461   return false;
3462 }
3463 
3464 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3465                                           CallExpr *TheCall) {
3466   // position of memory order and scope arguments in the builtin
3467   unsigned OrderIndex, ScopeIndex;
3468   switch (BuiltinID) {
3469   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3470   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3471   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3472   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3473     OrderIndex = 2;
3474     ScopeIndex = 3;
3475     break;
3476   case AMDGPU::BI__builtin_amdgcn_fence:
3477     OrderIndex = 0;
3478     ScopeIndex = 1;
3479     break;
3480   default:
3481     return false;
3482   }
3483 
3484   ExprResult Arg = TheCall->getArg(OrderIndex);
3485   auto ArgExpr = Arg.get();
3486   Expr::EvalResult ArgResult;
3487 
3488   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3489     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3490            << ArgExpr->getType();
3491   auto Ord = ArgResult.Val.getInt().getZExtValue();
3492 
3493   // Check valididty of memory ordering as per C11 / C++11's memody model.
3494   // Only fence needs check. Atomic dec/inc allow all memory orders.
3495   if (!llvm::isValidAtomicOrderingCABI(Ord))
3496     return Diag(ArgExpr->getBeginLoc(),
3497                 diag::warn_atomic_op_has_invalid_memory_order)
3498            << ArgExpr->getSourceRange();
3499   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3500   case llvm::AtomicOrderingCABI::relaxed:
3501   case llvm::AtomicOrderingCABI::consume:
3502     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3503       return Diag(ArgExpr->getBeginLoc(),
3504                   diag::warn_atomic_op_has_invalid_memory_order)
3505              << ArgExpr->getSourceRange();
3506     break;
3507   case llvm::AtomicOrderingCABI::acquire:
3508   case llvm::AtomicOrderingCABI::release:
3509   case llvm::AtomicOrderingCABI::acq_rel:
3510   case llvm::AtomicOrderingCABI::seq_cst:
3511     break;
3512   }
3513 
3514   Arg = TheCall->getArg(ScopeIndex);
3515   ArgExpr = Arg.get();
3516   Expr::EvalResult ArgResult1;
3517   // Check that sync scope is a constant literal
3518   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3519     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3520            << ArgExpr->getType();
3521 
3522   return false;
3523 }
3524 
3525 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3526   llvm::APSInt Result;
3527 
3528   // We can't check the value of a dependent argument.
3529   Expr *Arg = TheCall->getArg(ArgNum);
3530   if (Arg->isTypeDependent() || Arg->isValueDependent())
3531     return false;
3532 
3533   // Check constant-ness first.
3534   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3535     return true;
3536 
3537   int64_t Val = Result.getSExtValue();
3538   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3539     return false;
3540 
3541   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3542          << Arg->getSourceRange();
3543 }
3544 
3545 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3546                                          unsigned BuiltinID,
3547                                          CallExpr *TheCall) {
3548   // CodeGenFunction can also detect this, but this gives a better error
3549   // message.
3550   bool FeatureMissing = false;
3551   SmallVector<StringRef> ReqFeatures;
3552   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3553   Features.split(ReqFeatures, ',');
3554 
3555   // Check if each required feature is included
3556   for (StringRef F : ReqFeatures) {
3557     if (TI.hasFeature(F))
3558       continue;
3559 
3560     // If the feature is 64bit, alter the string so it will print better in
3561     // the diagnostic.
3562     if (F == "64bit")
3563       F = "RV64";
3564 
3565     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3566     F.consume_front("experimental-");
3567     std::string FeatureStr = F.str();
3568     FeatureStr[0] = std::toupper(FeatureStr[0]);
3569 
3570     // Error message
3571     FeatureMissing = true;
3572     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3573         << TheCall->getSourceRange() << StringRef(FeatureStr);
3574   }
3575 
3576   if (FeatureMissing)
3577     return true;
3578 
3579   switch (BuiltinID) {
3580   case RISCV::BI__builtin_rvv_vsetvli:
3581     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3582            CheckRISCVLMUL(TheCall, 2);
3583   case RISCV::BI__builtin_rvv_vsetvlimax:
3584     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3585            CheckRISCVLMUL(TheCall, 1);
3586   case RISCV::BI__builtin_rvv_vget_v_i8m2_i8m1:
3587   case RISCV::BI__builtin_rvv_vget_v_i16m2_i16m1:
3588   case RISCV::BI__builtin_rvv_vget_v_i32m2_i32m1:
3589   case RISCV::BI__builtin_rvv_vget_v_i64m2_i64m1:
3590   case RISCV::BI__builtin_rvv_vget_v_f32m2_f32m1:
3591   case RISCV::BI__builtin_rvv_vget_v_f64m2_f64m1:
3592   case RISCV::BI__builtin_rvv_vget_v_u8m2_u8m1:
3593   case RISCV::BI__builtin_rvv_vget_v_u16m2_u16m1:
3594   case RISCV::BI__builtin_rvv_vget_v_u32m2_u32m1:
3595   case RISCV::BI__builtin_rvv_vget_v_u64m2_u64m1:
3596   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m2:
3597   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m2:
3598   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m2:
3599   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m2:
3600   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m2:
3601   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m2:
3602   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m2:
3603   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m2:
3604   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m2:
3605   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m2:
3606   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m4:
3607   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m4:
3608   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m4:
3609   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m4:
3610   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m4:
3611   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m4:
3612   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m4:
3613   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m4:
3614   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m4:
3615   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m4:
3616     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3617   case RISCV::BI__builtin_rvv_vget_v_i8m4_i8m1:
3618   case RISCV::BI__builtin_rvv_vget_v_i16m4_i16m1:
3619   case RISCV::BI__builtin_rvv_vget_v_i32m4_i32m1:
3620   case RISCV::BI__builtin_rvv_vget_v_i64m4_i64m1:
3621   case RISCV::BI__builtin_rvv_vget_v_f32m4_f32m1:
3622   case RISCV::BI__builtin_rvv_vget_v_f64m4_f64m1:
3623   case RISCV::BI__builtin_rvv_vget_v_u8m4_u8m1:
3624   case RISCV::BI__builtin_rvv_vget_v_u16m4_u16m1:
3625   case RISCV::BI__builtin_rvv_vget_v_u32m4_u32m1:
3626   case RISCV::BI__builtin_rvv_vget_v_u64m4_u64m1:
3627   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m2:
3628   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m2:
3629   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m2:
3630   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m2:
3631   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m2:
3632   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m2:
3633   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m2:
3634   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m2:
3635   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m2:
3636   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m2:
3637     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3638   case RISCV::BI__builtin_rvv_vget_v_i8m8_i8m1:
3639   case RISCV::BI__builtin_rvv_vget_v_i16m8_i16m1:
3640   case RISCV::BI__builtin_rvv_vget_v_i32m8_i32m1:
3641   case RISCV::BI__builtin_rvv_vget_v_i64m8_i64m1:
3642   case RISCV::BI__builtin_rvv_vget_v_f32m8_f32m1:
3643   case RISCV::BI__builtin_rvv_vget_v_f64m8_f64m1:
3644   case RISCV::BI__builtin_rvv_vget_v_u8m8_u8m1:
3645   case RISCV::BI__builtin_rvv_vget_v_u16m8_u16m1:
3646   case RISCV::BI__builtin_rvv_vget_v_u32m8_u32m1:
3647   case RISCV::BI__builtin_rvv_vget_v_u64m8_u64m1:
3648     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3649   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m2:
3650   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m2:
3651   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m2:
3652   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m2:
3653   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m2:
3654   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m2:
3655   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m2:
3656   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m2:
3657   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m2:
3658   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m2:
3659   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m4:
3660   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m4:
3661   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m4:
3662   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m4:
3663   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m4:
3664   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m4:
3665   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m4:
3666   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m4:
3667   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m4:
3668   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m4:
3669   case RISCV::BI__builtin_rvv_vset_v_i8m4_i8m8:
3670   case RISCV::BI__builtin_rvv_vset_v_i16m4_i16m8:
3671   case RISCV::BI__builtin_rvv_vset_v_i32m4_i32m8:
3672   case RISCV::BI__builtin_rvv_vset_v_i64m4_i64m8:
3673   case RISCV::BI__builtin_rvv_vset_v_f32m4_f32m8:
3674   case RISCV::BI__builtin_rvv_vset_v_f64m4_f64m8:
3675   case RISCV::BI__builtin_rvv_vset_v_u8m4_u8m8:
3676   case RISCV::BI__builtin_rvv_vset_v_u16m4_u16m8:
3677   case RISCV::BI__builtin_rvv_vset_v_u32m4_u32m8:
3678   case RISCV::BI__builtin_rvv_vset_v_u64m4_u64m8:
3679     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3680   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m4:
3681   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m4:
3682   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m4:
3683   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m4:
3684   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m4:
3685   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m4:
3686   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m4:
3687   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m4:
3688   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m4:
3689   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m4:
3690   case RISCV::BI__builtin_rvv_vset_v_i8m2_i8m8:
3691   case RISCV::BI__builtin_rvv_vset_v_i16m2_i16m8:
3692   case RISCV::BI__builtin_rvv_vset_v_i32m2_i32m8:
3693   case RISCV::BI__builtin_rvv_vset_v_i64m2_i64m8:
3694   case RISCV::BI__builtin_rvv_vset_v_f32m2_f32m8:
3695   case RISCV::BI__builtin_rvv_vset_v_f64m2_f64m8:
3696   case RISCV::BI__builtin_rvv_vset_v_u8m2_u8m8:
3697   case RISCV::BI__builtin_rvv_vset_v_u16m2_u16m8:
3698   case RISCV::BI__builtin_rvv_vset_v_u32m2_u32m8:
3699   case RISCV::BI__builtin_rvv_vset_v_u64m2_u64m8:
3700     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3701   case RISCV::BI__builtin_rvv_vset_v_i8m1_i8m8:
3702   case RISCV::BI__builtin_rvv_vset_v_i16m1_i16m8:
3703   case RISCV::BI__builtin_rvv_vset_v_i32m1_i32m8:
3704   case RISCV::BI__builtin_rvv_vset_v_i64m1_i64m8:
3705   case RISCV::BI__builtin_rvv_vset_v_f32m1_f32m8:
3706   case RISCV::BI__builtin_rvv_vset_v_f64m1_f64m8:
3707   case RISCV::BI__builtin_rvv_vset_v_u8m1_u8m8:
3708   case RISCV::BI__builtin_rvv_vset_v_u16m1_u16m8:
3709   case RISCV::BI__builtin_rvv_vset_v_u32m1_u32m8:
3710   case RISCV::BI__builtin_rvv_vset_v_u64m1_u64m8:
3711     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 7);
3712   }
3713 
3714   return false;
3715 }
3716 
3717 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3718                                            CallExpr *TheCall) {
3719   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3720     Expr *Arg = TheCall->getArg(0);
3721     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3722       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3723         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3724                << Arg->getSourceRange();
3725   }
3726 
3727   // For intrinsics which take an immediate value as part of the instruction,
3728   // range check them here.
3729   unsigned i = 0, l = 0, u = 0;
3730   switch (BuiltinID) {
3731   default: return false;
3732   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3733   case SystemZ::BI__builtin_s390_verimb:
3734   case SystemZ::BI__builtin_s390_verimh:
3735   case SystemZ::BI__builtin_s390_verimf:
3736   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3737   case SystemZ::BI__builtin_s390_vfaeb:
3738   case SystemZ::BI__builtin_s390_vfaeh:
3739   case SystemZ::BI__builtin_s390_vfaef:
3740   case SystemZ::BI__builtin_s390_vfaebs:
3741   case SystemZ::BI__builtin_s390_vfaehs:
3742   case SystemZ::BI__builtin_s390_vfaefs:
3743   case SystemZ::BI__builtin_s390_vfaezb:
3744   case SystemZ::BI__builtin_s390_vfaezh:
3745   case SystemZ::BI__builtin_s390_vfaezf:
3746   case SystemZ::BI__builtin_s390_vfaezbs:
3747   case SystemZ::BI__builtin_s390_vfaezhs:
3748   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3749   case SystemZ::BI__builtin_s390_vfisb:
3750   case SystemZ::BI__builtin_s390_vfidb:
3751     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3752            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3753   case SystemZ::BI__builtin_s390_vftcisb:
3754   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3755   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3756   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3757   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3758   case SystemZ::BI__builtin_s390_vstrcb:
3759   case SystemZ::BI__builtin_s390_vstrch:
3760   case SystemZ::BI__builtin_s390_vstrcf:
3761   case SystemZ::BI__builtin_s390_vstrczb:
3762   case SystemZ::BI__builtin_s390_vstrczh:
3763   case SystemZ::BI__builtin_s390_vstrczf:
3764   case SystemZ::BI__builtin_s390_vstrcbs:
3765   case SystemZ::BI__builtin_s390_vstrchs:
3766   case SystemZ::BI__builtin_s390_vstrcfs:
3767   case SystemZ::BI__builtin_s390_vstrczbs:
3768   case SystemZ::BI__builtin_s390_vstrczhs:
3769   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3770   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3771   case SystemZ::BI__builtin_s390_vfminsb:
3772   case SystemZ::BI__builtin_s390_vfmaxsb:
3773   case SystemZ::BI__builtin_s390_vfmindb:
3774   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3775   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3776   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3777   }
3778   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3779 }
3780 
3781 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3782 /// This checks that the target supports __builtin_cpu_supports and
3783 /// that the string argument is constant and valid.
3784 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3785                                    CallExpr *TheCall) {
3786   Expr *Arg = TheCall->getArg(0);
3787 
3788   // Check if the argument is a string literal.
3789   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3790     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3791            << Arg->getSourceRange();
3792 
3793   // Check the contents of the string.
3794   StringRef Feature =
3795       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3796   if (!TI.validateCpuSupports(Feature))
3797     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3798            << Arg->getSourceRange();
3799   return false;
3800 }
3801 
3802 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3803 /// This checks that the target supports __builtin_cpu_is and
3804 /// that the string argument is constant and valid.
3805 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3806   Expr *Arg = TheCall->getArg(0);
3807 
3808   // Check if the argument is a string literal.
3809   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3810     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3811            << Arg->getSourceRange();
3812 
3813   // Check the contents of the string.
3814   StringRef Feature =
3815       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3816   if (!TI.validateCpuIs(Feature))
3817     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3818            << Arg->getSourceRange();
3819   return false;
3820 }
3821 
3822 // Check if the rounding mode is legal.
3823 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3824   // Indicates if this instruction has rounding control or just SAE.
3825   bool HasRC = false;
3826 
3827   unsigned ArgNum = 0;
3828   switch (BuiltinID) {
3829   default:
3830     return false;
3831   case X86::BI__builtin_ia32_vcvttsd2si32:
3832   case X86::BI__builtin_ia32_vcvttsd2si64:
3833   case X86::BI__builtin_ia32_vcvttsd2usi32:
3834   case X86::BI__builtin_ia32_vcvttsd2usi64:
3835   case X86::BI__builtin_ia32_vcvttss2si32:
3836   case X86::BI__builtin_ia32_vcvttss2si64:
3837   case X86::BI__builtin_ia32_vcvttss2usi32:
3838   case X86::BI__builtin_ia32_vcvttss2usi64:
3839     ArgNum = 1;
3840     break;
3841   case X86::BI__builtin_ia32_maxpd512:
3842   case X86::BI__builtin_ia32_maxps512:
3843   case X86::BI__builtin_ia32_minpd512:
3844   case X86::BI__builtin_ia32_minps512:
3845     ArgNum = 2;
3846     break;
3847   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3848   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3849   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3850   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3851   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3852   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3853   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3854   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3855   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3856   case X86::BI__builtin_ia32_exp2pd_mask:
3857   case X86::BI__builtin_ia32_exp2ps_mask:
3858   case X86::BI__builtin_ia32_getexppd512_mask:
3859   case X86::BI__builtin_ia32_getexpps512_mask:
3860   case X86::BI__builtin_ia32_rcp28pd_mask:
3861   case X86::BI__builtin_ia32_rcp28ps_mask:
3862   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3863   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3864   case X86::BI__builtin_ia32_vcomisd:
3865   case X86::BI__builtin_ia32_vcomiss:
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_cvtss2sd_round_mask:
3874   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3875   case X86::BI__builtin_ia32_getexpss128_round_mask:
3876   case X86::BI__builtin_ia32_getmantpd512_mask:
3877   case X86::BI__builtin_ia32_getmantps512_mask:
3878   case X86::BI__builtin_ia32_maxsd_round_mask:
3879   case X86::BI__builtin_ia32_maxss_round_mask:
3880   case X86::BI__builtin_ia32_minsd_round_mask:
3881   case X86::BI__builtin_ia32_minss_round_mask:
3882   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3883   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3884   case X86::BI__builtin_ia32_reducepd512_mask:
3885   case X86::BI__builtin_ia32_reduceps512_mask:
3886   case X86::BI__builtin_ia32_rndscalepd_mask:
3887   case X86::BI__builtin_ia32_rndscaleps_mask:
3888   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3889   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3890     ArgNum = 4;
3891     break;
3892   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3893   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3894   case X86::BI__builtin_ia32_fixupimmps512_mask:
3895   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3896   case X86::BI__builtin_ia32_fixupimmsd_mask:
3897   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3898   case X86::BI__builtin_ia32_fixupimmss_mask:
3899   case X86::BI__builtin_ia32_fixupimmss_maskz:
3900   case X86::BI__builtin_ia32_getmantsd_round_mask:
3901   case X86::BI__builtin_ia32_getmantss_round_mask:
3902   case X86::BI__builtin_ia32_rangepd512_mask:
3903   case X86::BI__builtin_ia32_rangeps512_mask:
3904   case X86::BI__builtin_ia32_rangesd128_round_mask:
3905   case X86::BI__builtin_ia32_rangess128_round_mask:
3906   case X86::BI__builtin_ia32_reducesd_mask:
3907   case X86::BI__builtin_ia32_reducess_mask:
3908   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3909   case X86::BI__builtin_ia32_rndscaless_round_mask:
3910     ArgNum = 5;
3911     break;
3912   case X86::BI__builtin_ia32_vcvtsd2si64:
3913   case X86::BI__builtin_ia32_vcvtsd2si32:
3914   case X86::BI__builtin_ia32_vcvtsd2usi32:
3915   case X86::BI__builtin_ia32_vcvtsd2usi64:
3916   case X86::BI__builtin_ia32_vcvtss2si32:
3917   case X86::BI__builtin_ia32_vcvtss2si64:
3918   case X86::BI__builtin_ia32_vcvtss2usi32:
3919   case X86::BI__builtin_ia32_vcvtss2usi64:
3920   case X86::BI__builtin_ia32_sqrtpd512:
3921   case X86::BI__builtin_ia32_sqrtps512:
3922     ArgNum = 1;
3923     HasRC = true;
3924     break;
3925   case X86::BI__builtin_ia32_addpd512:
3926   case X86::BI__builtin_ia32_addps512:
3927   case X86::BI__builtin_ia32_divpd512:
3928   case X86::BI__builtin_ia32_divps512:
3929   case X86::BI__builtin_ia32_mulpd512:
3930   case X86::BI__builtin_ia32_mulps512:
3931   case X86::BI__builtin_ia32_subpd512:
3932   case X86::BI__builtin_ia32_subps512:
3933   case X86::BI__builtin_ia32_cvtsi2sd64:
3934   case X86::BI__builtin_ia32_cvtsi2ss32:
3935   case X86::BI__builtin_ia32_cvtsi2ss64:
3936   case X86::BI__builtin_ia32_cvtusi2sd64:
3937   case X86::BI__builtin_ia32_cvtusi2ss32:
3938   case X86::BI__builtin_ia32_cvtusi2ss64:
3939     ArgNum = 2;
3940     HasRC = true;
3941     break;
3942   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3943   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3944   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3945   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3946   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3947   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3948   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3949   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3950   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3951   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3952   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3953   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3954   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3955   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3956   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3957     ArgNum = 3;
3958     HasRC = true;
3959     break;
3960   case X86::BI__builtin_ia32_addss_round_mask:
3961   case X86::BI__builtin_ia32_addsd_round_mask:
3962   case X86::BI__builtin_ia32_divss_round_mask:
3963   case X86::BI__builtin_ia32_divsd_round_mask:
3964   case X86::BI__builtin_ia32_mulss_round_mask:
3965   case X86::BI__builtin_ia32_mulsd_round_mask:
3966   case X86::BI__builtin_ia32_subss_round_mask:
3967   case X86::BI__builtin_ia32_subsd_round_mask:
3968   case X86::BI__builtin_ia32_scalefpd512_mask:
3969   case X86::BI__builtin_ia32_scalefps512_mask:
3970   case X86::BI__builtin_ia32_scalefsd_round_mask:
3971   case X86::BI__builtin_ia32_scalefss_round_mask:
3972   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3973   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3974   case X86::BI__builtin_ia32_sqrtss_round_mask:
3975   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3976   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3977   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3978   case X86::BI__builtin_ia32_vfmaddss3_mask:
3979   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3980   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3981   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3982   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3983   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3984   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3985   case X86::BI__builtin_ia32_vfmaddps512_mask:
3986   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3987   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3988   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3989   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3990   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3991   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3992   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3993   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3994   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3995   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3996   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3997     ArgNum = 4;
3998     HasRC = true;
3999     break;
4000   }
4001 
4002   llvm::APSInt Result;
4003 
4004   // We can't check the value of a dependent argument.
4005   Expr *Arg = TheCall->getArg(ArgNum);
4006   if (Arg->isTypeDependent() || Arg->isValueDependent())
4007     return false;
4008 
4009   // Check constant-ness first.
4010   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4011     return true;
4012 
4013   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4014   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4015   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4016   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4017   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4018       Result == 8/*ROUND_NO_EXC*/ ||
4019       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4020       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4021     return false;
4022 
4023   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4024          << Arg->getSourceRange();
4025 }
4026 
4027 // Check if the gather/scatter scale is legal.
4028 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4029                                              CallExpr *TheCall) {
4030   unsigned ArgNum = 0;
4031   switch (BuiltinID) {
4032   default:
4033     return false;
4034   case X86::BI__builtin_ia32_gatherpfdpd:
4035   case X86::BI__builtin_ia32_gatherpfdps:
4036   case X86::BI__builtin_ia32_gatherpfqpd:
4037   case X86::BI__builtin_ia32_gatherpfqps:
4038   case X86::BI__builtin_ia32_scatterpfdpd:
4039   case X86::BI__builtin_ia32_scatterpfdps:
4040   case X86::BI__builtin_ia32_scatterpfqpd:
4041   case X86::BI__builtin_ia32_scatterpfqps:
4042     ArgNum = 3;
4043     break;
4044   case X86::BI__builtin_ia32_gatherd_pd:
4045   case X86::BI__builtin_ia32_gatherd_pd256:
4046   case X86::BI__builtin_ia32_gatherq_pd:
4047   case X86::BI__builtin_ia32_gatherq_pd256:
4048   case X86::BI__builtin_ia32_gatherd_ps:
4049   case X86::BI__builtin_ia32_gatherd_ps256:
4050   case X86::BI__builtin_ia32_gatherq_ps:
4051   case X86::BI__builtin_ia32_gatherq_ps256:
4052   case X86::BI__builtin_ia32_gatherd_q:
4053   case X86::BI__builtin_ia32_gatherd_q256:
4054   case X86::BI__builtin_ia32_gatherq_q:
4055   case X86::BI__builtin_ia32_gatherq_q256:
4056   case X86::BI__builtin_ia32_gatherd_d:
4057   case X86::BI__builtin_ia32_gatherd_d256:
4058   case X86::BI__builtin_ia32_gatherq_d:
4059   case X86::BI__builtin_ia32_gatherq_d256:
4060   case X86::BI__builtin_ia32_gather3div2df:
4061   case X86::BI__builtin_ia32_gather3div2di:
4062   case X86::BI__builtin_ia32_gather3div4df:
4063   case X86::BI__builtin_ia32_gather3div4di:
4064   case X86::BI__builtin_ia32_gather3div4sf:
4065   case X86::BI__builtin_ia32_gather3div4si:
4066   case X86::BI__builtin_ia32_gather3div8sf:
4067   case X86::BI__builtin_ia32_gather3div8si:
4068   case X86::BI__builtin_ia32_gather3siv2df:
4069   case X86::BI__builtin_ia32_gather3siv2di:
4070   case X86::BI__builtin_ia32_gather3siv4df:
4071   case X86::BI__builtin_ia32_gather3siv4di:
4072   case X86::BI__builtin_ia32_gather3siv4sf:
4073   case X86::BI__builtin_ia32_gather3siv4si:
4074   case X86::BI__builtin_ia32_gather3siv8sf:
4075   case X86::BI__builtin_ia32_gather3siv8si:
4076   case X86::BI__builtin_ia32_gathersiv8df:
4077   case X86::BI__builtin_ia32_gathersiv16sf:
4078   case X86::BI__builtin_ia32_gatherdiv8df:
4079   case X86::BI__builtin_ia32_gatherdiv16sf:
4080   case X86::BI__builtin_ia32_gathersiv8di:
4081   case X86::BI__builtin_ia32_gathersiv16si:
4082   case X86::BI__builtin_ia32_gatherdiv8di:
4083   case X86::BI__builtin_ia32_gatherdiv16si:
4084   case X86::BI__builtin_ia32_scatterdiv2df:
4085   case X86::BI__builtin_ia32_scatterdiv2di:
4086   case X86::BI__builtin_ia32_scatterdiv4df:
4087   case X86::BI__builtin_ia32_scatterdiv4di:
4088   case X86::BI__builtin_ia32_scatterdiv4sf:
4089   case X86::BI__builtin_ia32_scatterdiv4si:
4090   case X86::BI__builtin_ia32_scatterdiv8sf:
4091   case X86::BI__builtin_ia32_scatterdiv8si:
4092   case X86::BI__builtin_ia32_scattersiv2df:
4093   case X86::BI__builtin_ia32_scattersiv2di:
4094   case X86::BI__builtin_ia32_scattersiv4df:
4095   case X86::BI__builtin_ia32_scattersiv4di:
4096   case X86::BI__builtin_ia32_scattersiv4sf:
4097   case X86::BI__builtin_ia32_scattersiv4si:
4098   case X86::BI__builtin_ia32_scattersiv8sf:
4099   case X86::BI__builtin_ia32_scattersiv8si:
4100   case X86::BI__builtin_ia32_scattersiv8df:
4101   case X86::BI__builtin_ia32_scattersiv16sf:
4102   case X86::BI__builtin_ia32_scatterdiv8df:
4103   case X86::BI__builtin_ia32_scatterdiv16sf:
4104   case X86::BI__builtin_ia32_scattersiv8di:
4105   case X86::BI__builtin_ia32_scattersiv16si:
4106   case X86::BI__builtin_ia32_scatterdiv8di:
4107   case X86::BI__builtin_ia32_scatterdiv16si:
4108     ArgNum = 4;
4109     break;
4110   }
4111 
4112   llvm::APSInt Result;
4113 
4114   // We can't check the value of a dependent argument.
4115   Expr *Arg = TheCall->getArg(ArgNum);
4116   if (Arg->isTypeDependent() || Arg->isValueDependent())
4117     return false;
4118 
4119   // Check constant-ness first.
4120   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4121     return true;
4122 
4123   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4124     return false;
4125 
4126   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4127          << Arg->getSourceRange();
4128 }
4129 
4130 enum { TileRegLow = 0, TileRegHigh = 7 };
4131 
4132 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4133                                              ArrayRef<int> ArgNums) {
4134   for (int ArgNum : ArgNums) {
4135     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4136       return true;
4137   }
4138   return false;
4139 }
4140 
4141 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4142                                         ArrayRef<int> ArgNums) {
4143   // Because the max number of tile register is TileRegHigh + 1, so here we use
4144   // each bit to represent the usage of them in bitset.
4145   std::bitset<TileRegHigh + 1> ArgValues;
4146   for (int ArgNum : ArgNums) {
4147     Expr *Arg = TheCall->getArg(ArgNum);
4148     if (Arg->isTypeDependent() || Arg->isValueDependent())
4149       continue;
4150 
4151     llvm::APSInt Result;
4152     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4153       return true;
4154     int ArgExtValue = Result.getExtValue();
4155     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4156            "Incorrect tile register num.");
4157     if (ArgValues.test(ArgExtValue))
4158       return Diag(TheCall->getBeginLoc(),
4159                   diag::err_x86_builtin_tile_arg_duplicate)
4160              << TheCall->getArg(ArgNum)->getSourceRange();
4161     ArgValues.set(ArgExtValue);
4162   }
4163   return false;
4164 }
4165 
4166 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4167                                                 ArrayRef<int> ArgNums) {
4168   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4169          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4170 }
4171 
4172 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4173   switch (BuiltinID) {
4174   default:
4175     return false;
4176   case X86::BI__builtin_ia32_tileloadd64:
4177   case X86::BI__builtin_ia32_tileloaddt164:
4178   case X86::BI__builtin_ia32_tilestored64:
4179   case X86::BI__builtin_ia32_tilezero:
4180     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4181   case X86::BI__builtin_ia32_tdpbssd:
4182   case X86::BI__builtin_ia32_tdpbsud:
4183   case X86::BI__builtin_ia32_tdpbusd:
4184   case X86::BI__builtin_ia32_tdpbuud:
4185   case X86::BI__builtin_ia32_tdpbf16ps:
4186     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4187   }
4188 }
4189 static bool isX86_32Builtin(unsigned BuiltinID) {
4190   // These builtins only work on x86-32 targets.
4191   switch (BuiltinID) {
4192   case X86::BI__builtin_ia32_readeflags_u32:
4193   case X86::BI__builtin_ia32_writeeflags_u32:
4194     return true;
4195   }
4196 
4197   return false;
4198 }
4199 
4200 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4201                                        CallExpr *TheCall) {
4202   if (BuiltinID == X86::BI__builtin_cpu_supports)
4203     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4204 
4205   if (BuiltinID == X86::BI__builtin_cpu_is)
4206     return SemaBuiltinCpuIs(*this, TI, TheCall);
4207 
4208   // Check for 32-bit only builtins on a 64-bit target.
4209   const llvm::Triple &TT = TI.getTriple();
4210   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4211     return Diag(TheCall->getCallee()->getBeginLoc(),
4212                 diag::err_32_bit_builtin_64_bit_tgt);
4213 
4214   // If the intrinsic has rounding or SAE make sure its valid.
4215   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4216     return true;
4217 
4218   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4219   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4220     return true;
4221 
4222   // If the intrinsic has a tile arguments, make sure they are valid.
4223   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4224     return true;
4225 
4226   // For intrinsics which take an immediate value as part of the instruction,
4227   // range check them here.
4228   int i = 0, l = 0, u = 0;
4229   switch (BuiltinID) {
4230   default:
4231     return false;
4232   case X86::BI__builtin_ia32_vec_ext_v2si:
4233   case X86::BI__builtin_ia32_vec_ext_v2di:
4234   case X86::BI__builtin_ia32_vextractf128_pd256:
4235   case X86::BI__builtin_ia32_vextractf128_ps256:
4236   case X86::BI__builtin_ia32_vextractf128_si256:
4237   case X86::BI__builtin_ia32_extract128i256:
4238   case X86::BI__builtin_ia32_extractf64x4_mask:
4239   case X86::BI__builtin_ia32_extracti64x4_mask:
4240   case X86::BI__builtin_ia32_extractf32x8_mask:
4241   case X86::BI__builtin_ia32_extracti32x8_mask:
4242   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4243   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4244   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4245   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4246     i = 1; l = 0; u = 1;
4247     break;
4248   case X86::BI__builtin_ia32_vec_set_v2di:
4249   case X86::BI__builtin_ia32_vinsertf128_pd256:
4250   case X86::BI__builtin_ia32_vinsertf128_ps256:
4251   case X86::BI__builtin_ia32_vinsertf128_si256:
4252   case X86::BI__builtin_ia32_insert128i256:
4253   case X86::BI__builtin_ia32_insertf32x8:
4254   case X86::BI__builtin_ia32_inserti32x8:
4255   case X86::BI__builtin_ia32_insertf64x4:
4256   case X86::BI__builtin_ia32_inserti64x4:
4257   case X86::BI__builtin_ia32_insertf64x2_256:
4258   case X86::BI__builtin_ia32_inserti64x2_256:
4259   case X86::BI__builtin_ia32_insertf32x4_256:
4260   case X86::BI__builtin_ia32_inserti32x4_256:
4261     i = 2; l = 0; u = 1;
4262     break;
4263   case X86::BI__builtin_ia32_vpermilpd:
4264   case X86::BI__builtin_ia32_vec_ext_v4hi:
4265   case X86::BI__builtin_ia32_vec_ext_v4si:
4266   case X86::BI__builtin_ia32_vec_ext_v4sf:
4267   case X86::BI__builtin_ia32_vec_ext_v4di:
4268   case X86::BI__builtin_ia32_extractf32x4_mask:
4269   case X86::BI__builtin_ia32_extracti32x4_mask:
4270   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4271   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4272     i = 1; l = 0; u = 3;
4273     break;
4274   case X86::BI_mm_prefetch:
4275   case X86::BI__builtin_ia32_vec_ext_v8hi:
4276   case X86::BI__builtin_ia32_vec_ext_v8si:
4277     i = 1; l = 0; u = 7;
4278     break;
4279   case X86::BI__builtin_ia32_sha1rnds4:
4280   case X86::BI__builtin_ia32_blendpd:
4281   case X86::BI__builtin_ia32_shufpd:
4282   case X86::BI__builtin_ia32_vec_set_v4hi:
4283   case X86::BI__builtin_ia32_vec_set_v4si:
4284   case X86::BI__builtin_ia32_vec_set_v4di:
4285   case X86::BI__builtin_ia32_shuf_f32x4_256:
4286   case X86::BI__builtin_ia32_shuf_f64x2_256:
4287   case X86::BI__builtin_ia32_shuf_i32x4_256:
4288   case X86::BI__builtin_ia32_shuf_i64x2_256:
4289   case X86::BI__builtin_ia32_insertf64x2_512:
4290   case X86::BI__builtin_ia32_inserti64x2_512:
4291   case X86::BI__builtin_ia32_insertf32x4:
4292   case X86::BI__builtin_ia32_inserti32x4:
4293     i = 2; l = 0; u = 3;
4294     break;
4295   case X86::BI__builtin_ia32_vpermil2pd:
4296   case X86::BI__builtin_ia32_vpermil2pd256:
4297   case X86::BI__builtin_ia32_vpermil2ps:
4298   case X86::BI__builtin_ia32_vpermil2ps256:
4299     i = 3; l = 0; u = 3;
4300     break;
4301   case X86::BI__builtin_ia32_cmpb128_mask:
4302   case X86::BI__builtin_ia32_cmpw128_mask:
4303   case X86::BI__builtin_ia32_cmpd128_mask:
4304   case X86::BI__builtin_ia32_cmpq128_mask:
4305   case X86::BI__builtin_ia32_cmpb256_mask:
4306   case X86::BI__builtin_ia32_cmpw256_mask:
4307   case X86::BI__builtin_ia32_cmpd256_mask:
4308   case X86::BI__builtin_ia32_cmpq256_mask:
4309   case X86::BI__builtin_ia32_cmpb512_mask:
4310   case X86::BI__builtin_ia32_cmpw512_mask:
4311   case X86::BI__builtin_ia32_cmpd512_mask:
4312   case X86::BI__builtin_ia32_cmpq512_mask:
4313   case X86::BI__builtin_ia32_ucmpb128_mask:
4314   case X86::BI__builtin_ia32_ucmpw128_mask:
4315   case X86::BI__builtin_ia32_ucmpd128_mask:
4316   case X86::BI__builtin_ia32_ucmpq128_mask:
4317   case X86::BI__builtin_ia32_ucmpb256_mask:
4318   case X86::BI__builtin_ia32_ucmpw256_mask:
4319   case X86::BI__builtin_ia32_ucmpd256_mask:
4320   case X86::BI__builtin_ia32_ucmpq256_mask:
4321   case X86::BI__builtin_ia32_ucmpb512_mask:
4322   case X86::BI__builtin_ia32_ucmpw512_mask:
4323   case X86::BI__builtin_ia32_ucmpd512_mask:
4324   case X86::BI__builtin_ia32_ucmpq512_mask:
4325   case X86::BI__builtin_ia32_vpcomub:
4326   case X86::BI__builtin_ia32_vpcomuw:
4327   case X86::BI__builtin_ia32_vpcomud:
4328   case X86::BI__builtin_ia32_vpcomuq:
4329   case X86::BI__builtin_ia32_vpcomb:
4330   case X86::BI__builtin_ia32_vpcomw:
4331   case X86::BI__builtin_ia32_vpcomd:
4332   case X86::BI__builtin_ia32_vpcomq:
4333   case X86::BI__builtin_ia32_vec_set_v8hi:
4334   case X86::BI__builtin_ia32_vec_set_v8si:
4335     i = 2; l = 0; u = 7;
4336     break;
4337   case X86::BI__builtin_ia32_vpermilpd256:
4338   case X86::BI__builtin_ia32_roundps:
4339   case X86::BI__builtin_ia32_roundpd:
4340   case X86::BI__builtin_ia32_roundps256:
4341   case X86::BI__builtin_ia32_roundpd256:
4342   case X86::BI__builtin_ia32_getmantpd128_mask:
4343   case X86::BI__builtin_ia32_getmantpd256_mask:
4344   case X86::BI__builtin_ia32_getmantps128_mask:
4345   case X86::BI__builtin_ia32_getmantps256_mask:
4346   case X86::BI__builtin_ia32_getmantpd512_mask:
4347   case X86::BI__builtin_ia32_getmantps512_mask:
4348   case X86::BI__builtin_ia32_vec_ext_v16qi:
4349   case X86::BI__builtin_ia32_vec_ext_v16hi:
4350     i = 1; l = 0; u = 15;
4351     break;
4352   case X86::BI__builtin_ia32_pblendd128:
4353   case X86::BI__builtin_ia32_blendps:
4354   case X86::BI__builtin_ia32_blendpd256:
4355   case X86::BI__builtin_ia32_shufpd256:
4356   case X86::BI__builtin_ia32_roundss:
4357   case X86::BI__builtin_ia32_roundsd:
4358   case X86::BI__builtin_ia32_rangepd128_mask:
4359   case X86::BI__builtin_ia32_rangepd256_mask:
4360   case X86::BI__builtin_ia32_rangepd512_mask:
4361   case X86::BI__builtin_ia32_rangeps128_mask:
4362   case X86::BI__builtin_ia32_rangeps256_mask:
4363   case X86::BI__builtin_ia32_rangeps512_mask:
4364   case X86::BI__builtin_ia32_getmantsd_round_mask:
4365   case X86::BI__builtin_ia32_getmantss_round_mask:
4366   case X86::BI__builtin_ia32_vec_set_v16qi:
4367   case X86::BI__builtin_ia32_vec_set_v16hi:
4368     i = 2; l = 0; u = 15;
4369     break;
4370   case X86::BI__builtin_ia32_vec_ext_v32qi:
4371     i = 1; l = 0; u = 31;
4372     break;
4373   case X86::BI__builtin_ia32_cmpps:
4374   case X86::BI__builtin_ia32_cmpss:
4375   case X86::BI__builtin_ia32_cmppd:
4376   case X86::BI__builtin_ia32_cmpsd:
4377   case X86::BI__builtin_ia32_cmpps256:
4378   case X86::BI__builtin_ia32_cmppd256:
4379   case X86::BI__builtin_ia32_cmpps128_mask:
4380   case X86::BI__builtin_ia32_cmppd128_mask:
4381   case X86::BI__builtin_ia32_cmpps256_mask:
4382   case X86::BI__builtin_ia32_cmppd256_mask:
4383   case X86::BI__builtin_ia32_cmpps512_mask:
4384   case X86::BI__builtin_ia32_cmppd512_mask:
4385   case X86::BI__builtin_ia32_cmpsd_mask:
4386   case X86::BI__builtin_ia32_cmpss_mask:
4387   case X86::BI__builtin_ia32_vec_set_v32qi:
4388     i = 2; l = 0; u = 31;
4389     break;
4390   case X86::BI__builtin_ia32_permdf256:
4391   case X86::BI__builtin_ia32_permdi256:
4392   case X86::BI__builtin_ia32_permdf512:
4393   case X86::BI__builtin_ia32_permdi512:
4394   case X86::BI__builtin_ia32_vpermilps:
4395   case X86::BI__builtin_ia32_vpermilps256:
4396   case X86::BI__builtin_ia32_vpermilpd512:
4397   case X86::BI__builtin_ia32_vpermilps512:
4398   case X86::BI__builtin_ia32_pshufd:
4399   case X86::BI__builtin_ia32_pshufd256:
4400   case X86::BI__builtin_ia32_pshufd512:
4401   case X86::BI__builtin_ia32_pshufhw:
4402   case X86::BI__builtin_ia32_pshufhw256:
4403   case X86::BI__builtin_ia32_pshufhw512:
4404   case X86::BI__builtin_ia32_pshuflw:
4405   case X86::BI__builtin_ia32_pshuflw256:
4406   case X86::BI__builtin_ia32_pshuflw512:
4407   case X86::BI__builtin_ia32_vcvtps2ph:
4408   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4409   case X86::BI__builtin_ia32_vcvtps2ph256:
4410   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4411   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4412   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4413   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4414   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4415   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4416   case X86::BI__builtin_ia32_rndscaleps_mask:
4417   case X86::BI__builtin_ia32_rndscalepd_mask:
4418   case X86::BI__builtin_ia32_reducepd128_mask:
4419   case X86::BI__builtin_ia32_reducepd256_mask:
4420   case X86::BI__builtin_ia32_reducepd512_mask:
4421   case X86::BI__builtin_ia32_reduceps128_mask:
4422   case X86::BI__builtin_ia32_reduceps256_mask:
4423   case X86::BI__builtin_ia32_reduceps512_mask:
4424   case X86::BI__builtin_ia32_prold512:
4425   case X86::BI__builtin_ia32_prolq512:
4426   case X86::BI__builtin_ia32_prold128:
4427   case X86::BI__builtin_ia32_prold256:
4428   case X86::BI__builtin_ia32_prolq128:
4429   case X86::BI__builtin_ia32_prolq256:
4430   case X86::BI__builtin_ia32_prord512:
4431   case X86::BI__builtin_ia32_prorq512:
4432   case X86::BI__builtin_ia32_prord128:
4433   case X86::BI__builtin_ia32_prord256:
4434   case X86::BI__builtin_ia32_prorq128:
4435   case X86::BI__builtin_ia32_prorq256:
4436   case X86::BI__builtin_ia32_fpclasspd128_mask:
4437   case X86::BI__builtin_ia32_fpclasspd256_mask:
4438   case X86::BI__builtin_ia32_fpclassps128_mask:
4439   case X86::BI__builtin_ia32_fpclassps256_mask:
4440   case X86::BI__builtin_ia32_fpclassps512_mask:
4441   case X86::BI__builtin_ia32_fpclasspd512_mask:
4442   case X86::BI__builtin_ia32_fpclasssd_mask:
4443   case X86::BI__builtin_ia32_fpclassss_mask:
4444   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4445   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4446   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4447   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4448   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4449   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4450   case X86::BI__builtin_ia32_kshiftliqi:
4451   case X86::BI__builtin_ia32_kshiftlihi:
4452   case X86::BI__builtin_ia32_kshiftlisi:
4453   case X86::BI__builtin_ia32_kshiftlidi:
4454   case X86::BI__builtin_ia32_kshiftriqi:
4455   case X86::BI__builtin_ia32_kshiftrihi:
4456   case X86::BI__builtin_ia32_kshiftrisi:
4457   case X86::BI__builtin_ia32_kshiftridi:
4458     i = 1; l = 0; u = 255;
4459     break;
4460   case X86::BI__builtin_ia32_vperm2f128_pd256:
4461   case X86::BI__builtin_ia32_vperm2f128_ps256:
4462   case X86::BI__builtin_ia32_vperm2f128_si256:
4463   case X86::BI__builtin_ia32_permti256:
4464   case X86::BI__builtin_ia32_pblendw128:
4465   case X86::BI__builtin_ia32_pblendw256:
4466   case X86::BI__builtin_ia32_blendps256:
4467   case X86::BI__builtin_ia32_pblendd256:
4468   case X86::BI__builtin_ia32_palignr128:
4469   case X86::BI__builtin_ia32_palignr256:
4470   case X86::BI__builtin_ia32_palignr512:
4471   case X86::BI__builtin_ia32_alignq512:
4472   case X86::BI__builtin_ia32_alignd512:
4473   case X86::BI__builtin_ia32_alignd128:
4474   case X86::BI__builtin_ia32_alignd256:
4475   case X86::BI__builtin_ia32_alignq128:
4476   case X86::BI__builtin_ia32_alignq256:
4477   case X86::BI__builtin_ia32_vcomisd:
4478   case X86::BI__builtin_ia32_vcomiss:
4479   case X86::BI__builtin_ia32_shuf_f32x4:
4480   case X86::BI__builtin_ia32_shuf_f64x2:
4481   case X86::BI__builtin_ia32_shuf_i32x4:
4482   case X86::BI__builtin_ia32_shuf_i64x2:
4483   case X86::BI__builtin_ia32_shufpd512:
4484   case X86::BI__builtin_ia32_shufps:
4485   case X86::BI__builtin_ia32_shufps256:
4486   case X86::BI__builtin_ia32_shufps512:
4487   case X86::BI__builtin_ia32_dbpsadbw128:
4488   case X86::BI__builtin_ia32_dbpsadbw256:
4489   case X86::BI__builtin_ia32_dbpsadbw512:
4490   case X86::BI__builtin_ia32_vpshldd128:
4491   case X86::BI__builtin_ia32_vpshldd256:
4492   case X86::BI__builtin_ia32_vpshldd512:
4493   case X86::BI__builtin_ia32_vpshldq128:
4494   case X86::BI__builtin_ia32_vpshldq256:
4495   case X86::BI__builtin_ia32_vpshldq512:
4496   case X86::BI__builtin_ia32_vpshldw128:
4497   case X86::BI__builtin_ia32_vpshldw256:
4498   case X86::BI__builtin_ia32_vpshldw512:
4499   case X86::BI__builtin_ia32_vpshrdd128:
4500   case X86::BI__builtin_ia32_vpshrdd256:
4501   case X86::BI__builtin_ia32_vpshrdd512:
4502   case X86::BI__builtin_ia32_vpshrdq128:
4503   case X86::BI__builtin_ia32_vpshrdq256:
4504   case X86::BI__builtin_ia32_vpshrdq512:
4505   case X86::BI__builtin_ia32_vpshrdw128:
4506   case X86::BI__builtin_ia32_vpshrdw256:
4507   case X86::BI__builtin_ia32_vpshrdw512:
4508     i = 2; l = 0; u = 255;
4509     break;
4510   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4511   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4512   case X86::BI__builtin_ia32_fixupimmps512_mask:
4513   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4514   case X86::BI__builtin_ia32_fixupimmsd_mask:
4515   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4516   case X86::BI__builtin_ia32_fixupimmss_mask:
4517   case X86::BI__builtin_ia32_fixupimmss_maskz:
4518   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4519   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4520   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4521   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4522   case X86::BI__builtin_ia32_fixupimmps128_mask:
4523   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4524   case X86::BI__builtin_ia32_fixupimmps256_mask:
4525   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4526   case X86::BI__builtin_ia32_pternlogd512_mask:
4527   case X86::BI__builtin_ia32_pternlogd512_maskz:
4528   case X86::BI__builtin_ia32_pternlogq512_mask:
4529   case X86::BI__builtin_ia32_pternlogq512_maskz:
4530   case X86::BI__builtin_ia32_pternlogd128_mask:
4531   case X86::BI__builtin_ia32_pternlogd128_maskz:
4532   case X86::BI__builtin_ia32_pternlogd256_mask:
4533   case X86::BI__builtin_ia32_pternlogd256_maskz:
4534   case X86::BI__builtin_ia32_pternlogq128_mask:
4535   case X86::BI__builtin_ia32_pternlogq128_maskz:
4536   case X86::BI__builtin_ia32_pternlogq256_mask:
4537   case X86::BI__builtin_ia32_pternlogq256_maskz:
4538     i = 3; l = 0; u = 255;
4539     break;
4540   case X86::BI__builtin_ia32_gatherpfdpd:
4541   case X86::BI__builtin_ia32_gatherpfdps:
4542   case X86::BI__builtin_ia32_gatherpfqpd:
4543   case X86::BI__builtin_ia32_gatherpfqps:
4544   case X86::BI__builtin_ia32_scatterpfdpd:
4545   case X86::BI__builtin_ia32_scatterpfdps:
4546   case X86::BI__builtin_ia32_scatterpfqpd:
4547   case X86::BI__builtin_ia32_scatterpfqps:
4548     i = 4; l = 2; u = 3;
4549     break;
4550   case X86::BI__builtin_ia32_reducesd_mask:
4551   case X86::BI__builtin_ia32_reducess_mask:
4552   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4553   case X86::BI__builtin_ia32_rndscaless_round_mask:
4554     i = 4; l = 0; u = 255;
4555     break;
4556   }
4557 
4558   // Note that we don't force a hard error on the range check here, allowing
4559   // template-generated or macro-generated dead code to potentially have out-of-
4560   // range values. These need to code generate, but don't need to necessarily
4561   // make any sense. We use a warning that defaults to an error.
4562   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4563 }
4564 
4565 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4566 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4567 /// Returns true when the format fits the function and the FormatStringInfo has
4568 /// been populated.
4569 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4570                                FormatStringInfo *FSI) {
4571   FSI->HasVAListArg = Format->getFirstArg() == 0;
4572   FSI->FormatIdx = Format->getFormatIdx() - 1;
4573   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4574 
4575   // The way the format attribute works in GCC, the implicit this argument
4576   // of member functions is counted. However, it doesn't appear in our own
4577   // lists, so decrement format_idx in that case.
4578   if (IsCXXMember) {
4579     if(FSI->FormatIdx == 0)
4580       return false;
4581     --FSI->FormatIdx;
4582     if (FSI->FirstDataArg != 0)
4583       --FSI->FirstDataArg;
4584   }
4585   return true;
4586 }
4587 
4588 /// Checks if a the given expression evaluates to null.
4589 ///
4590 /// Returns true if the value evaluates to null.
4591 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4592   // If the expression has non-null type, it doesn't evaluate to null.
4593   if (auto nullability
4594         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4595     if (*nullability == NullabilityKind::NonNull)
4596       return false;
4597   }
4598 
4599   // As a special case, transparent unions initialized with zero are
4600   // considered null for the purposes of the nonnull attribute.
4601   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4602     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4603       if (const CompoundLiteralExpr *CLE =
4604           dyn_cast<CompoundLiteralExpr>(Expr))
4605         if (const InitListExpr *ILE =
4606             dyn_cast<InitListExpr>(CLE->getInitializer()))
4607           Expr = ILE->getInit(0);
4608   }
4609 
4610   bool Result;
4611   return (!Expr->isValueDependent() &&
4612           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4613           !Result);
4614 }
4615 
4616 static void CheckNonNullArgument(Sema &S,
4617                                  const Expr *ArgExpr,
4618                                  SourceLocation CallSiteLoc) {
4619   if (CheckNonNullExpr(S, ArgExpr))
4620     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4621                           S.PDiag(diag::warn_null_arg)
4622                               << ArgExpr->getSourceRange());
4623 }
4624 
4625 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4626   FormatStringInfo FSI;
4627   if ((GetFormatStringType(Format) == FST_NSString) &&
4628       getFormatStringInfo(Format, false, &FSI)) {
4629     Idx = FSI.FormatIdx;
4630     return true;
4631   }
4632   return false;
4633 }
4634 
4635 /// Diagnose use of %s directive in an NSString which is being passed
4636 /// as formatting string to formatting method.
4637 static void
4638 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4639                                         const NamedDecl *FDecl,
4640                                         Expr **Args,
4641                                         unsigned NumArgs) {
4642   unsigned Idx = 0;
4643   bool Format = false;
4644   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4645   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4646     Idx = 2;
4647     Format = true;
4648   }
4649   else
4650     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4651       if (S.GetFormatNSStringIdx(I, Idx)) {
4652         Format = true;
4653         break;
4654       }
4655     }
4656   if (!Format || NumArgs <= Idx)
4657     return;
4658   const Expr *FormatExpr = Args[Idx];
4659   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4660     FormatExpr = CSCE->getSubExpr();
4661   const StringLiteral *FormatString;
4662   if (const ObjCStringLiteral *OSL =
4663       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4664     FormatString = OSL->getString();
4665   else
4666     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4667   if (!FormatString)
4668     return;
4669   if (S.FormatStringHasSArg(FormatString)) {
4670     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4671       << "%s" << 1 << 1;
4672     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4673       << FDecl->getDeclName();
4674   }
4675 }
4676 
4677 /// Determine whether the given type has a non-null nullability annotation.
4678 static bool isNonNullType(ASTContext &ctx, QualType type) {
4679   if (auto nullability = type->getNullability(ctx))
4680     return *nullability == NullabilityKind::NonNull;
4681 
4682   return false;
4683 }
4684 
4685 static void CheckNonNullArguments(Sema &S,
4686                                   const NamedDecl *FDecl,
4687                                   const FunctionProtoType *Proto,
4688                                   ArrayRef<const Expr *> Args,
4689                                   SourceLocation CallSiteLoc) {
4690   assert((FDecl || Proto) && "Need a function declaration or prototype");
4691 
4692   // Already checked by by constant evaluator.
4693   if (S.isConstantEvaluated())
4694     return;
4695   // Check the attributes attached to the method/function itself.
4696   llvm::SmallBitVector NonNullArgs;
4697   if (FDecl) {
4698     // Handle the nonnull attribute on the function/method declaration itself.
4699     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4700       if (!NonNull->args_size()) {
4701         // Easy case: all pointer arguments are nonnull.
4702         for (const auto *Arg : Args)
4703           if (S.isValidPointerAttrType(Arg->getType()))
4704             CheckNonNullArgument(S, Arg, CallSiteLoc);
4705         return;
4706       }
4707 
4708       for (const ParamIdx &Idx : NonNull->args()) {
4709         unsigned IdxAST = Idx.getASTIndex();
4710         if (IdxAST >= Args.size())
4711           continue;
4712         if (NonNullArgs.empty())
4713           NonNullArgs.resize(Args.size());
4714         NonNullArgs.set(IdxAST);
4715       }
4716     }
4717   }
4718 
4719   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4720     // Handle the nonnull attribute on the parameters of the
4721     // function/method.
4722     ArrayRef<ParmVarDecl*> parms;
4723     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4724       parms = FD->parameters();
4725     else
4726       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4727 
4728     unsigned ParamIndex = 0;
4729     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4730          I != E; ++I, ++ParamIndex) {
4731       const ParmVarDecl *PVD = *I;
4732       if (PVD->hasAttr<NonNullAttr>() ||
4733           isNonNullType(S.Context, PVD->getType())) {
4734         if (NonNullArgs.empty())
4735           NonNullArgs.resize(Args.size());
4736 
4737         NonNullArgs.set(ParamIndex);
4738       }
4739     }
4740   } else {
4741     // If we have a non-function, non-method declaration but no
4742     // function prototype, try to dig out the function prototype.
4743     if (!Proto) {
4744       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4745         QualType type = VD->getType().getNonReferenceType();
4746         if (auto pointerType = type->getAs<PointerType>())
4747           type = pointerType->getPointeeType();
4748         else if (auto blockType = type->getAs<BlockPointerType>())
4749           type = blockType->getPointeeType();
4750         // FIXME: data member pointers?
4751 
4752         // Dig out the function prototype, if there is one.
4753         Proto = type->getAs<FunctionProtoType>();
4754       }
4755     }
4756 
4757     // Fill in non-null argument information from the nullability
4758     // information on the parameter types (if we have them).
4759     if (Proto) {
4760       unsigned Index = 0;
4761       for (auto paramType : Proto->getParamTypes()) {
4762         if (isNonNullType(S.Context, paramType)) {
4763           if (NonNullArgs.empty())
4764             NonNullArgs.resize(Args.size());
4765 
4766           NonNullArgs.set(Index);
4767         }
4768 
4769         ++Index;
4770       }
4771     }
4772   }
4773 
4774   // Check for non-null arguments.
4775   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4776        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4777     if (NonNullArgs[ArgIndex])
4778       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4779   }
4780 }
4781 
4782 /// Warn if a pointer or reference argument passed to a function points to an
4783 /// object that is less aligned than the parameter. This can happen when
4784 /// creating a typedef with a lower alignment than the original type and then
4785 /// calling functions defined in terms of the original type.
4786 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4787                              StringRef ParamName, QualType ArgTy,
4788                              QualType ParamTy) {
4789 
4790   // If a function accepts a pointer or reference type
4791   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4792     return;
4793 
4794   // If the parameter is a pointer type, get the pointee type for the
4795   // argument too. If the parameter is a reference type, don't try to get
4796   // the pointee type for the argument.
4797   if (ParamTy->isPointerType())
4798     ArgTy = ArgTy->getPointeeType();
4799 
4800   // Remove reference or pointer
4801   ParamTy = ParamTy->getPointeeType();
4802 
4803   // Find expected alignment, and the actual alignment of the passed object.
4804   // getTypeAlignInChars requires complete types
4805   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4806       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4807       ArgTy->isUndeducedType())
4808     return;
4809 
4810   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4811   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4812 
4813   // If the argument is less aligned than the parameter, there is a
4814   // potential alignment issue.
4815   if (ArgAlign < ParamAlign)
4816     Diag(Loc, diag::warn_param_mismatched_alignment)
4817         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4818         << ParamName << FDecl;
4819 }
4820 
4821 /// Handles the checks for format strings, non-POD arguments to vararg
4822 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4823 /// attributes.
4824 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4825                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4826                      bool IsMemberFunction, SourceLocation Loc,
4827                      SourceRange Range, VariadicCallType CallType) {
4828   // FIXME: We should check as much as we can in the template definition.
4829   if (CurContext->isDependentContext())
4830     return;
4831 
4832   // Printf and scanf checking.
4833   llvm::SmallBitVector CheckedVarArgs;
4834   if (FDecl) {
4835     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4836       // Only create vector if there are format attributes.
4837       CheckedVarArgs.resize(Args.size());
4838 
4839       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4840                            CheckedVarArgs);
4841     }
4842   }
4843 
4844   // Refuse POD arguments that weren't caught by the format string
4845   // checks above.
4846   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4847   if (CallType != VariadicDoesNotApply &&
4848       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4849     unsigned NumParams = Proto ? Proto->getNumParams()
4850                        : FDecl && isa<FunctionDecl>(FDecl)
4851                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4852                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4853                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4854                        : 0;
4855 
4856     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4857       // Args[ArgIdx] can be null in malformed code.
4858       if (const Expr *Arg = Args[ArgIdx]) {
4859         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4860           checkVariadicArgument(Arg, CallType);
4861       }
4862     }
4863   }
4864 
4865   if (FDecl || Proto) {
4866     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4867 
4868     // Type safety checking.
4869     if (FDecl) {
4870       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4871         CheckArgumentWithTypeTag(I, Args, Loc);
4872     }
4873   }
4874 
4875   // Check that passed arguments match the alignment of original arguments.
4876   // Try to get the missing prototype from the declaration.
4877   if (!Proto && FDecl) {
4878     const auto *FT = FDecl->getFunctionType();
4879     if (isa_and_nonnull<FunctionProtoType>(FT))
4880       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4881   }
4882   if (Proto) {
4883     // For variadic functions, we may have more args than parameters.
4884     // For some K&R functions, we may have less args than parameters.
4885     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4886     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4887       // Args[ArgIdx] can be null in malformed code.
4888       if (const Expr *Arg = Args[ArgIdx]) {
4889         if (Arg->containsErrors())
4890           continue;
4891 
4892         QualType ParamTy = Proto->getParamType(ArgIdx);
4893         QualType ArgTy = Arg->getType();
4894         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4895                           ArgTy, ParamTy);
4896       }
4897     }
4898   }
4899 
4900   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4901     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4902     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4903     if (!Arg->isValueDependent()) {
4904       Expr::EvalResult Align;
4905       if (Arg->EvaluateAsInt(Align, Context)) {
4906         const llvm::APSInt &I = Align.Val.getInt();
4907         if (!I.isPowerOf2())
4908           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4909               << Arg->getSourceRange();
4910 
4911         if (I > Sema::MaximumAlignment)
4912           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4913               << Arg->getSourceRange() << Sema::MaximumAlignment;
4914       }
4915     }
4916   }
4917 
4918   if (FD)
4919     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4920 }
4921 
4922 /// CheckConstructorCall - Check a constructor call for correctness and safety
4923 /// properties not enforced by the C type system.
4924 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4925                                 ArrayRef<const Expr *> Args,
4926                                 const FunctionProtoType *Proto,
4927                                 SourceLocation Loc) {
4928   VariadicCallType CallType =
4929       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4930 
4931   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4932   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4933                     Context.getPointerType(Ctor->getThisObjectType()));
4934 
4935   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4936             Loc, SourceRange(), CallType);
4937 }
4938 
4939 /// CheckFunctionCall - Check a direct function call for various correctness
4940 /// and safety properties not strictly enforced by the C type system.
4941 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4942                              const FunctionProtoType *Proto) {
4943   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4944                               isa<CXXMethodDecl>(FDecl);
4945   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4946                           IsMemberOperatorCall;
4947   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4948                                                   TheCall->getCallee());
4949   Expr** Args = TheCall->getArgs();
4950   unsigned NumArgs = TheCall->getNumArgs();
4951 
4952   Expr *ImplicitThis = nullptr;
4953   if (IsMemberOperatorCall) {
4954     // If this is a call to a member operator, hide the first argument
4955     // from checkCall.
4956     // FIXME: Our choice of AST representation here is less than ideal.
4957     ImplicitThis = Args[0];
4958     ++Args;
4959     --NumArgs;
4960   } else if (IsMemberFunction)
4961     ImplicitThis =
4962         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4963 
4964   if (ImplicitThis) {
4965     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
4966     // used.
4967     QualType ThisType = ImplicitThis->getType();
4968     if (!ThisType->isPointerType()) {
4969       assert(!ThisType->isReferenceType());
4970       ThisType = Context.getPointerType(ThisType);
4971     }
4972 
4973     QualType ThisTypeFromDecl =
4974         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
4975 
4976     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
4977                       ThisTypeFromDecl);
4978   }
4979 
4980   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4981             IsMemberFunction, TheCall->getRParenLoc(),
4982             TheCall->getCallee()->getSourceRange(), CallType);
4983 
4984   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4985   // None of the checks below are needed for functions that don't have
4986   // simple names (e.g., C++ conversion functions).
4987   if (!FnInfo)
4988     return false;
4989 
4990   CheckTCBEnforcement(TheCall, FDecl);
4991 
4992   CheckAbsoluteValueFunction(TheCall, FDecl);
4993   CheckMaxUnsignedZero(TheCall, FDecl);
4994 
4995   if (getLangOpts().ObjC)
4996     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4997 
4998   unsigned CMId = FDecl->getMemoryFunctionKind();
4999 
5000   // Handle memory setting and copying functions.
5001   switch (CMId) {
5002   case 0:
5003     return false;
5004   case Builtin::BIstrlcpy: // fallthrough
5005   case Builtin::BIstrlcat:
5006     CheckStrlcpycatArguments(TheCall, FnInfo);
5007     break;
5008   case Builtin::BIstrncat:
5009     CheckStrncatArguments(TheCall, FnInfo);
5010     break;
5011   case Builtin::BIfree:
5012     CheckFreeArguments(TheCall);
5013     break;
5014   default:
5015     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5016   }
5017 
5018   return false;
5019 }
5020 
5021 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5022                                ArrayRef<const Expr *> Args) {
5023   VariadicCallType CallType =
5024       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5025 
5026   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5027             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5028             CallType);
5029 
5030   return false;
5031 }
5032 
5033 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5034                             const FunctionProtoType *Proto) {
5035   QualType Ty;
5036   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5037     Ty = V->getType().getNonReferenceType();
5038   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5039     Ty = F->getType().getNonReferenceType();
5040   else
5041     return false;
5042 
5043   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5044       !Ty->isFunctionProtoType())
5045     return false;
5046 
5047   VariadicCallType CallType;
5048   if (!Proto || !Proto->isVariadic()) {
5049     CallType = VariadicDoesNotApply;
5050   } else if (Ty->isBlockPointerType()) {
5051     CallType = VariadicBlock;
5052   } else { // Ty->isFunctionPointerType()
5053     CallType = VariadicFunction;
5054   }
5055 
5056   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5057             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5058             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5059             TheCall->getCallee()->getSourceRange(), CallType);
5060 
5061   return false;
5062 }
5063 
5064 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5065 /// such as function pointers returned from functions.
5066 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5067   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5068                                                   TheCall->getCallee());
5069   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5070             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5071             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5072             TheCall->getCallee()->getSourceRange(), CallType);
5073 
5074   return false;
5075 }
5076 
5077 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5078   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5079     return false;
5080 
5081   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5082   switch (Op) {
5083   case AtomicExpr::AO__c11_atomic_init:
5084   case AtomicExpr::AO__opencl_atomic_init:
5085     llvm_unreachable("There is no ordering argument for an init");
5086 
5087   case AtomicExpr::AO__c11_atomic_load:
5088   case AtomicExpr::AO__opencl_atomic_load:
5089   case AtomicExpr::AO__atomic_load_n:
5090   case AtomicExpr::AO__atomic_load:
5091     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5092            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5093 
5094   case AtomicExpr::AO__c11_atomic_store:
5095   case AtomicExpr::AO__opencl_atomic_store:
5096   case AtomicExpr::AO__atomic_store:
5097   case AtomicExpr::AO__atomic_store_n:
5098     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5099            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5100            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5101 
5102   default:
5103     return true;
5104   }
5105 }
5106 
5107 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5108                                          AtomicExpr::AtomicOp Op) {
5109   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5110   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5111   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5112   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5113                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5114                          Op);
5115 }
5116 
5117 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5118                                  SourceLocation RParenLoc, MultiExprArg Args,
5119                                  AtomicExpr::AtomicOp Op,
5120                                  AtomicArgumentOrder ArgOrder) {
5121   // All the non-OpenCL operations take one of the following forms.
5122   // The OpenCL operations take the __c11 forms with one extra argument for
5123   // synchronization scope.
5124   enum {
5125     // C    __c11_atomic_init(A *, C)
5126     Init,
5127 
5128     // C    __c11_atomic_load(A *, int)
5129     Load,
5130 
5131     // void __atomic_load(A *, CP, int)
5132     LoadCopy,
5133 
5134     // void __atomic_store(A *, CP, int)
5135     Copy,
5136 
5137     // C    __c11_atomic_add(A *, M, int)
5138     Arithmetic,
5139 
5140     // C    __atomic_exchange_n(A *, CP, int)
5141     Xchg,
5142 
5143     // void __atomic_exchange(A *, C *, CP, int)
5144     GNUXchg,
5145 
5146     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5147     C11CmpXchg,
5148 
5149     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5150     GNUCmpXchg
5151   } Form = Init;
5152 
5153   const unsigned NumForm = GNUCmpXchg + 1;
5154   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5155   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5156   // where:
5157   //   C is an appropriate type,
5158   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5159   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5160   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5161   //   the int parameters are for orderings.
5162 
5163   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5164       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5165       "need to update code for modified forms");
5166   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5167                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5168                         AtomicExpr::AO__atomic_load,
5169                 "need to update code for modified C11 atomics");
5170   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5171                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5172   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5173                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5174                IsOpenCL;
5175   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5176              Op == AtomicExpr::AO__atomic_store_n ||
5177              Op == AtomicExpr::AO__atomic_exchange_n ||
5178              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5179   bool IsAddSub = false;
5180 
5181   switch (Op) {
5182   case AtomicExpr::AO__c11_atomic_init:
5183   case AtomicExpr::AO__opencl_atomic_init:
5184     Form = Init;
5185     break;
5186 
5187   case AtomicExpr::AO__c11_atomic_load:
5188   case AtomicExpr::AO__opencl_atomic_load:
5189   case AtomicExpr::AO__atomic_load_n:
5190     Form = Load;
5191     break;
5192 
5193   case AtomicExpr::AO__atomic_load:
5194     Form = LoadCopy;
5195     break;
5196 
5197   case AtomicExpr::AO__c11_atomic_store:
5198   case AtomicExpr::AO__opencl_atomic_store:
5199   case AtomicExpr::AO__atomic_store:
5200   case AtomicExpr::AO__atomic_store_n:
5201     Form = Copy;
5202     break;
5203 
5204   case AtomicExpr::AO__c11_atomic_fetch_add:
5205   case AtomicExpr::AO__c11_atomic_fetch_sub:
5206   case AtomicExpr::AO__opencl_atomic_fetch_add:
5207   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5208   case AtomicExpr::AO__atomic_fetch_add:
5209   case AtomicExpr::AO__atomic_fetch_sub:
5210   case AtomicExpr::AO__atomic_add_fetch:
5211   case AtomicExpr::AO__atomic_sub_fetch:
5212     IsAddSub = true;
5213     Form = Arithmetic;
5214     break;
5215   case AtomicExpr::AO__c11_atomic_fetch_and:
5216   case AtomicExpr::AO__c11_atomic_fetch_or:
5217   case AtomicExpr::AO__c11_atomic_fetch_xor:
5218   case AtomicExpr::AO__opencl_atomic_fetch_and:
5219   case AtomicExpr::AO__opencl_atomic_fetch_or:
5220   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5221   case AtomicExpr::AO__atomic_fetch_and:
5222   case AtomicExpr::AO__atomic_fetch_or:
5223   case AtomicExpr::AO__atomic_fetch_xor:
5224   case AtomicExpr::AO__atomic_fetch_nand:
5225   case AtomicExpr::AO__atomic_and_fetch:
5226   case AtomicExpr::AO__atomic_or_fetch:
5227   case AtomicExpr::AO__atomic_xor_fetch:
5228   case AtomicExpr::AO__atomic_nand_fetch:
5229     Form = Arithmetic;
5230     break;
5231   case AtomicExpr::AO__c11_atomic_fetch_min:
5232   case AtomicExpr::AO__c11_atomic_fetch_max:
5233   case AtomicExpr::AO__opencl_atomic_fetch_min:
5234   case AtomicExpr::AO__opencl_atomic_fetch_max:
5235   case AtomicExpr::AO__atomic_min_fetch:
5236   case AtomicExpr::AO__atomic_max_fetch:
5237   case AtomicExpr::AO__atomic_fetch_min:
5238   case AtomicExpr::AO__atomic_fetch_max:
5239     Form = Arithmetic;
5240     break;
5241 
5242   case AtomicExpr::AO__c11_atomic_exchange:
5243   case AtomicExpr::AO__opencl_atomic_exchange:
5244   case AtomicExpr::AO__atomic_exchange_n:
5245     Form = Xchg;
5246     break;
5247 
5248   case AtomicExpr::AO__atomic_exchange:
5249     Form = GNUXchg;
5250     break;
5251 
5252   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5253   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5254   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5255   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5256     Form = C11CmpXchg;
5257     break;
5258 
5259   case AtomicExpr::AO__atomic_compare_exchange:
5260   case AtomicExpr::AO__atomic_compare_exchange_n:
5261     Form = GNUCmpXchg;
5262     break;
5263   }
5264 
5265   unsigned AdjustedNumArgs = NumArgs[Form];
5266   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5267     ++AdjustedNumArgs;
5268   // Check we have the right number of arguments.
5269   if (Args.size() < AdjustedNumArgs) {
5270     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5271         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5272         << ExprRange;
5273     return ExprError();
5274   } else if (Args.size() > AdjustedNumArgs) {
5275     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5276          diag::err_typecheck_call_too_many_args)
5277         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5278         << ExprRange;
5279     return ExprError();
5280   }
5281 
5282   // Inspect the first argument of the atomic operation.
5283   Expr *Ptr = Args[0];
5284   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5285   if (ConvertedPtr.isInvalid())
5286     return ExprError();
5287 
5288   Ptr = ConvertedPtr.get();
5289   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5290   if (!pointerType) {
5291     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5292         << Ptr->getType() << Ptr->getSourceRange();
5293     return ExprError();
5294   }
5295 
5296   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5297   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5298   QualType ValType = AtomTy; // 'C'
5299   if (IsC11) {
5300     if (!AtomTy->isAtomicType()) {
5301       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5302           << Ptr->getType() << Ptr->getSourceRange();
5303       return ExprError();
5304     }
5305     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5306         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5307       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5308           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5309           << Ptr->getSourceRange();
5310       return ExprError();
5311     }
5312     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5313   } else if (Form != Load && Form != LoadCopy) {
5314     if (ValType.isConstQualified()) {
5315       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5316           << Ptr->getType() << Ptr->getSourceRange();
5317       return ExprError();
5318     }
5319   }
5320 
5321   // For an arithmetic operation, the implied arithmetic must be well-formed.
5322   if (Form == Arithmetic) {
5323     // gcc does not enforce these rules for GNU atomics, but we do so for
5324     // sanity.
5325     auto IsAllowedValueType = [&](QualType ValType) {
5326       if (ValType->isIntegerType())
5327         return true;
5328       if (ValType->isPointerType())
5329         return true;
5330       if (!ValType->isFloatingType())
5331         return false;
5332       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5333       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5334           &Context.getTargetInfo().getLongDoubleFormat() ==
5335               &llvm::APFloat::x87DoubleExtended())
5336         return false;
5337       return true;
5338     };
5339     if (IsAddSub && !IsAllowedValueType(ValType)) {
5340       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5341           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5342       return ExprError();
5343     }
5344     if (!IsAddSub && !ValType->isIntegerType()) {
5345       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5346           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5347       return ExprError();
5348     }
5349     if (IsC11 && ValType->isPointerType() &&
5350         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5351                             diag::err_incomplete_type)) {
5352       return ExprError();
5353     }
5354   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5355     // For __atomic_*_n operations, the value type must be a scalar integral or
5356     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5357     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5358         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5359     return ExprError();
5360   }
5361 
5362   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5363       !AtomTy->isScalarType()) {
5364     // For GNU atomics, require a trivially-copyable type. This is not part of
5365     // the GNU atomics specification, but we enforce it for sanity.
5366     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5367         << Ptr->getType() << Ptr->getSourceRange();
5368     return ExprError();
5369   }
5370 
5371   switch (ValType.getObjCLifetime()) {
5372   case Qualifiers::OCL_None:
5373   case Qualifiers::OCL_ExplicitNone:
5374     // okay
5375     break;
5376 
5377   case Qualifiers::OCL_Weak:
5378   case Qualifiers::OCL_Strong:
5379   case Qualifiers::OCL_Autoreleasing:
5380     // FIXME: Can this happen? By this point, ValType should be known
5381     // to be trivially copyable.
5382     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5383         << ValType << Ptr->getSourceRange();
5384     return ExprError();
5385   }
5386 
5387   // All atomic operations have an overload which takes a pointer to a volatile
5388   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5389   // into the result or the other operands. Similarly atomic_load takes a
5390   // pointer to a const 'A'.
5391   ValType.removeLocalVolatile();
5392   ValType.removeLocalConst();
5393   QualType ResultType = ValType;
5394   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5395       Form == Init)
5396     ResultType = Context.VoidTy;
5397   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5398     ResultType = Context.BoolTy;
5399 
5400   // The type of a parameter passed 'by value'. In the GNU atomics, such
5401   // arguments are actually passed as pointers.
5402   QualType ByValType = ValType; // 'CP'
5403   bool IsPassedByAddress = false;
5404   if (!IsC11 && !IsN) {
5405     ByValType = Ptr->getType();
5406     IsPassedByAddress = true;
5407   }
5408 
5409   SmallVector<Expr *, 5> APIOrderedArgs;
5410   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5411     APIOrderedArgs.push_back(Args[0]);
5412     switch (Form) {
5413     case Init:
5414     case Load:
5415       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5416       break;
5417     case LoadCopy:
5418     case Copy:
5419     case Arithmetic:
5420     case Xchg:
5421       APIOrderedArgs.push_back(Args[2]); // Val1
5422       APIOrderedArgs.push_back(Args[1]); // Order
5423       break;
5424     case GNUXchg:
5425       APIOrderedArgs.push_back(Args[2]); // Val1
5426       APIOrderedArgs.push_back(Args[3]); // Val2
5427       APIOrderedArgs.push_back(Args[1]); // Order
5428       break;
5429     case C11CmpXchg:
5430       APIOrderedArgs.push_back(Args[2]); // Val1
5431       APIOrderedArgs.push_back(Args[4]); // Val2
5432       APIOrderedArgs.push_back(Args[1]); // Order
5433       APIOrderedArgs.push_back(Args[3]); // OrderFail
5434       break;
5435     case GNUCmpXchg:
5436       APIOrderedArgs.push_back(Args[2]); // Val1
5437       APIOrderedArgs.push_back(Args[4]); // Val2
5438       APIOrderedArgs.push_back(Args[5]); // Weak
5439       APIOrderedArgs.push_back(Args[1]); // Order
5440       APIOrderedArgs.push_back(Args[3]); // OrderFail
5441       break;
5442     }
5443   } else
5444     APIOrderedArgs.append(Args.begin(), Args.end());
5445 
5446   // The first argument's non-CV pointer type is used to deduce the type of
5447   // subsequent arguments, except for:
5448   //  - weak flag (always converted to bool)
5449   //  - memory order (always converted to int)
5450   //  - scope  (always converted to int)
5451   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5452     QualType Ty;
5453     if (i < NumVals[Form] + 1) {
5454       switch (i) {
5455       case 0:
5456         // The first argument is always a pointer. It has a fixed type.
5457         // It is always dereferenced, a nullptr is undefined.
5458         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5459         // Nothing else to do: we already know all we want about this pointer.
5460         continue;
5461       case 1:
5462         // The second argument is the non-atomic operand. For arithmetic, this
5463         // is always passed by value, and for a compare_exchange it is always
5464         // passed by address. For the rest, GNU uses by-address and C11 uses
5465         // by-value.
5466         assert(Form != Load);
5467         if (Form == Arithmetic && ValType->isPointerType())
5468           Ty = Context.getPointerDiffType();
5469         else if (Form == Init || Form == Arithmetic)
5470           Ty = ValType;
5471         else if (Form == Copy || Form == Xchg) {
5472           if (IsPassedByAddress) {
5473             // The value pointer is always dereferenced, a nullptr is undefined.
5474             CheckNonNullArgument(*this, APIOrderedArgs[i],
5475                                  ExprRange.getBegin());
5476           }
5477           Ty = ByValType;
5478         } else {
5479           Expr *ValArg = APIOrderedArgs[i];
5480           // The value pointer is always dereferenced, a nullptr is undefined.
5481           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5482           LangAS AS = LangAS::Default;
5483           // Keep address space of non-atomic pointer type.
5484           if (const PointerType *PtrTy =
5485                   ValArg->getType()->getAs<PointerType>()) {
5486             AS = PtrTy->getPointeeType().getAddressSpace();
5487           }
5488           Ty = Context.getPointerType(
5489               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5490         }
5491         break;
5492       case 2:
5493         // The third argument to compare_exchange / GNU exchange is the desired
5494         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5495         if (IsPassedByAddress)
5496           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5497         Ty = ByValType;
5498         break;
5499       case 3:
5500         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5501         Ty = Context.BoolTy;
5502         break;
5503       }
5504     } else {
5505       // The order(s) and scope are always converted to int.
5506       Ty = Context.IntTy;
5507     }
5508 
5509     InitializedEntity Entity =
5510         InitializedEntity::InitializeParameter(Context, Ty, false);
5511     ExprResult Arg = APIOrderedArgs[i];
5512     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5513     if (Arg.isInvalid())
5514       return true;
5515     APIOrderedArgs[i] = Arg.get();
5516   }
5517 
5518   // Permute the arguments into a 'consistent' order.
5519   SmallVector<Expr*, 5> SubExprs;
5520   SubExprs.push_back(Ptr);
5521   switch (Form) {
5522   case Init:
5523     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5524     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5525     break;
5526   case Load:
5527     SubExprs.push_back(APIOrderedArgs[1]); // Order
5528     break;
5529   case LoadCopy:
5530   case Copy:
5531   case Arithmetic:
5532   case Xchg:
5533     SubExprs.push_back(APIOrderedArgs[2]); // Order
5534     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5535     break;
5536   case GNUXchg:
5537     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5538     SubExprs.push_back(APIOrderedArgs[3]); // Order
5539     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5540     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5541     break;
5542   case C11CmpXchg:
5543     SubExprs.push_back(APIOrderedArgs[3]); // Order
5544     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5545     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5546     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5547     break;
5548   case GNUCmpXchg:
5549     SubExprs.push_back(APIOrderedArgs[4]); // Order
5550     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5551     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5552     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5553     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5554     break;
5555   }
5556 
5557   if (SubExprs.size() >= 2 && Form != Init) {
5558     if (Optional<llvm::APSInt> Result =
5559             SubExprs[1]->getIntegerConstantExpr(Context))
5560       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5561         Diag(SubExprs[1]->getBeginLoc(),
5562              diag::warn_atomic_op_has_invalid_memory_order)
5563             << SubExprs[1]->getSourceRange();
5564   }
5565 
5566   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5567     auto *Scope = Args[Args.size() - 1];
5568     if (Optional<llvm::APSInt> Result =
5569             Scope->getIntegerConstantExpr(Context)) {
5570       if (!ScopeModel->isValid(Result->getZExtValue()))
5571         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5572             << Scope->getSourceRange();
5573     }
5574     SubExprs.push_back(Scope);
5575   }
5576 
5577   AtomicExpr *AE = new (Context)
5578       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5579 
5580   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5581        Op == AtomicExpr::AO__c11_atomic_store ||
5582        Op == AtomicExpr::AO__opencl_atomic_load ||
5583        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5584       Context.AtomicUsesUnsupportedLibcall(AE))
5585     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5586         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5587              Op == AtomicExpr::AO__opencl_atomic_load)
5588                 ? 0
5589                 : 1);
5590 
5591   if (ValType->isExtIntType()) {
5592     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5593     return ExprError();
5594   }
5595 
5596   return AE;
5597 }
5598 
5599 /// checkBuiltinArgument - Given a call to a builtin function, perform
5600 /// normal type-checking on the given argument, updating the call in
5601 /// place.  This is useful when a builtin function requires custom
5602 /// type-checking for some of its arguments but not necessarily all of
5603 /// them.
5604 ///
5605 /// Returns true on error.
5606 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5607   FunctionDecl *Fn = E->getDirectCallee();
5608   assert(Fn && "builtin call without direct callee!");
5609 
5610   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5611   InitializedEntity Entity =
5612     InitializedEntity::InitializeParameter(S.Context, Param);
5613 
5614   ExprResult Arg = E->getArg(0);
5615   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5616   if (Arg.isInvalid())
5617     return true;
5618 
5619   E->setArg(ArgIndex, Arg.get());
5620   return false;
5621 }
5622 
5623 /// We have a call to a function like __sync_fetch_and_add, which is an
5624 /// overloaded function based on the pointer type of its first argument.
5625 /// The main BuildCallExpr routines have already promoted the types of
5626 /// arguments because all of these calls are prototyped as void(...).
5627 ///
5628 /// This function goes through and does final semantic checking for these
5629 /// builtins, as well as generating any warnings.
5630 ExprResult
5631 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5632   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5633   Expr *Callee = TheCall->getCallee();
5634   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5635   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5636 
5637   // Ensure that we have at least one argument to do type inference from.
5638   if (TheCall->getNumArgs() < 1) {
5639     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5640         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5641     return ExprError();
5642   }
5643 
5644   // Inspect the first argument of the atomic builtin.  This should always be
5645   // a pointer type, whose element is an integral scalar or pointer type.
5646   // Because it is a pointer type, we don't have to worry about any implicit
5647   // casts here.
5648   // FIXME: We don't allow floating point scalars as input.
5649   Expr *FirstArg = TheCall->getArg(0);
5650   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5651   if (FirstArgResult.isInvalid())
5652     return ExprError();
5653   FirstArg = FirstArgResult.get();
5654   TheCall->setArg(0, FirstArg);
5655 
5656   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5657   if (!pointerType) {
5658     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5659         << FirstArg->getType() << FirstArg->getSourceRange();
5660     return ExprError();
5661   }
5662 
5663   QualType ValType = pointerType->getPointeeType();
5664   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5665       !ValType->isBlockPointerType()) {
5666     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5667         << FirstArg->getType() << FirstArg->getSourceRange();
5668     return ExprError();
5669   }
5670 
5671   if (ValType.isConstQualified()) {
5672     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5673         << FirstArg->getType() << FirstArg->getSourceRange();
5674     return ExprError();
5675   }
5676 
5677   switch (ValType.getObjCLifetime()) {
5678   case Qualifiers::OCL_None:
5679   case Qualifiers::OCL_ExplicitNone:
5680     // okay
5681     break;
5682 
5683   case Qualifiers::OCL_Weak:
5684   case Qualifiers::OCL_Strong:
5685   case Qualifiers::OCL_Autoreleasing:
5686     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5687         << ValType << FirstArg->getSourceRange();
5688     return ExprError();
5689   }
5690 
5691   // Strip any qualifiers off ValType.
5692   ValType = ValType.getUnqualifiedType();
5693 
5694   // The majority of builtins return a value, but a few have special return
5695   // types, so allow them to override appropriately below.
5696   QualType ResultType = ValType;
5697 
5698   // We need to figure out which concrete builtin this maps onto.  For example,
5699   // __sync_fetch_and_add with a 2 byte object turns into
5700   // __sync_fetch_and_add_2.
5701 #define BUILTIN_ROW(x) \
5702   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5703     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5704 
5705   static const unsigned BuiltinIndices[][5] = {
5706     BUILTIN_ROW(__sync_fetch_and_add),
5707     BUILTIN_ROW(__sync_fetch_and_sub),
5708     BUILTIN_ROW(__sync_fetch_and_or),
5709     BUILTIN_ROW(__sync_fetch_and_and),
5710     BUILTIN_ROW(__sync_fetch_and_xor),
5711     BUILTIN_ROW(__sync_fetch_and_nand),
5712 
5713     BUILTIN_ROW(__sync_add_and_fetch),
5714     BUILTIN_ROW(__sync_sub_and_fetch),
5715     BUILTIN_ROW(__sync_and_and_fetch),
5716     BUILTIN_ROW(__sync_or_and_fetch),
5717     BUILTIN_ROW(__sync_xor_and_fetch),
5718     BUILTIN_ROW(__sync_nand_and_fetch),
5719 
5720     BUILTIN_ROW(__sync_val_compare_and_swap),
5721     BUILTIN_ROW(__sync_bool_compare_and_swap),
5722     BUILTIN_ROW(__sync_lock_test_and_set),
5723     BUILTIN_ROW(__sync_lock_release),
5724     BUILTIN_ROW(__sync_swap)
5725   };
5726 #undef BUILTIN_ROW
5727 
5728   // Determine the index of the size.
5729   unsigned SizeIndex;
5730   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5731   case 1: SizeIndex = 0; break;
5732   case 2: SizeIndex = 1; break;
5733   case 4: SizeIndex = 2; break;
5734   case 8: SizeIndex = 3; break;
5735   case 16: SizeIndex = 4; break;
5736   default:
5737     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5738         << FirstArg->getType() << FirstArg->getSourceRange();
5739     return ExprError();
5740   }
5741 
5742   // Each of these builtins has one pointer argument, followed by some number of
5743   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5744   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5745   // as the number of fixed args.
5746   unsigned BuiltinID = FDecl->getBuiltinID();
5747   unsigned BuiltinIndex, NumFixed = 1;
5748   bool WarnAboutSemanticsChange = false;
5749   switch (BuiltinID) {
5750   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5751   case Builtin::BI__sync_fetch_and_add:
5752   case Builtin::BI__sync_fetch_and_add_1:
5753   case Builtin::BI__sync_fetch_and_add_2:
5754   case Builtin::BI__sync_fetch_and_add_4:
5755   case Builtin::BI__sync_fetch_and_add_8:
5756   case Builtin::BI__sync_fetch_and_add_16:
5757     BuiltinIndex = 0;
5758     break;
5759 
5760   case Builtin::BI__sync_fetch_and_sub:
5761   case Builtin::BI__sync_fetch_and_sub_1:
5762   case Builtin::BI__sync_fetch_and_sub_2:
5763   case Builtin::BI__sync_fetch_and_sub_4:
5764   case Builtin::BI__sync_fetch_and_sub_8:
5765   case Builtin::BI__sync_fetch_and_sub_16:
5766     BuiltinIndex = 1;
5767     break;
5768 
5769   case Builtin::BI__sync_fetch_and_or:
5770   case Builtin::BI__sync_fetch_and_or_1:
5771   case Builtin::BI__sync_fetch_and_or_2:
5772   case Builtin::BI__sync_fetch_and_or_4:
5773   case Builtin::BI__sync_fetch_and_or_8:
5774   case Builtin::BI__sync_fetch_and_or_16:
5775     BuiltinIndex = 2;
5776     break;
5777 
5778   case Builtin::BI__sync_fetch_and_and:
5779   case Builtin::BI__sync_fetch_and_and_1:
5780   case Builtin::BI__sync_fetch_and_and_2:
5781   case Builtin::BI__sync_fetch_and_and_4:
5782   case Builtin::BI__sync_fetch_and_and_8:
5783   case Builtin::BI__sync_fetch_and_and_16:
5784     BuiltinIndex = 3;
5785     break;
5786 
5787   case Builtin::BI__sync_fetch_and_xor:
5788   case Builtin::BI__sync_fetch_and_xor_1:
5789   case Builtin::BI__sync_fetch_and_xor_2:
5790   case Builtin::BI__sync_fetch_and_xor_4:
5791   case Builtin::BI__sync_fetch_and_xor_8:
5792   case Builtin::BI__sync_fetch_and_xor_16:
5793     BuiltinIndex = 4;
5794     break;
5795 
5796   case Builtin::BI__sync_fetch_and_nand:
5797   case Builtin::BI__sync_fetch_and_nand_1:
5798   case Builtin::BI__sync_fetch_and_nand_2:
5799   case Builtin::BI__sync_fetch_and_nand_4:
5800   case Builtin::BI__sync_fetch_and_nand_8:
5801   case Builtin::BI__sync_fetch_and_nand_16:
5802     BuiltinIndex = 5;
5803     WarnAboutSemanticsChange = true;
5804     break;
5805 
5806   case Builtin::BI__sync_add_and_fetch:
5807   case Builtin::BI__sync_add_and_fetch_1:
5808   case Builtin::BI__sync_add_and_fetch_2:
5809   case Builtin::BI__sync_add_and_fetch_4:
5810   case Builtin::BI__sync_add_and_fetch_8:
5811   case Builtin::BI__sync_add_and_fetch_16:
5812     BuiltinIndex = 6;
5813     break;
5814 
5815   case Builtin::BI__sync_sub_and_fetch:
5816   case Builtin::BI__sync_sub_and_fetch_1:
5817   case Builtin::BI__sync_sub_and_fetch_2:
5818   case Builtin::BI__sync_sub_and_fetch_4:
5819   case Builtin::BI__sync_sub_and_fetch_8:
5820   case Builtin::BI__sync_sub_and_fetch_16:
5821     BuiltinIndex = 7;
5822     break;
5823 
5824   case Builtin::BI__sync_and_and_fetch:
5825   case Builtin::BI__sync_and_and_fetch_1:
5826   case Builtin::BI__sync_and_and_fetch_2:
5827   case Builtin::BI__sync_and_and_fetch_4:
5828   case Builtin::BI__sync_and_and_fetch_8:
5829   case Builtin::BI__sync_and_and_fetch_16:
5830     BuiltinIndex = 8;
5831     break;
5832 
5833   case Builtin::BI__sync_or_and_fetch:
5834   case Builtin::BI__sync_or_and_fetch_1:
5835   case Builtin::BI__sync_or_and_fetch_2:
5836   case Builtin::BI__sync_or_and_fetch_4:
5837   case Builtin::BI__sync_or_and_fetch_8:
5838   case Builtin::BI__sync_or_and_fetch_16:
5839     BuiltinIndex = 9;
5840     break;
5841 
5842   case Builtin::BI__sync_xor_and_fetch:
5843   case Builtin::BI__sync_xor_and_fetch_1:
5844   case Builtin::BI__sync_xor_and_fetch_2:
5845   case Builtin::BI__sync_xor_and_fetch_4:
5846   case Builtin::BI__sync_xor_and_fetch_8:
5847   case Builtin::BI__sync_xor_and_fetch_16:
5848     BuiltinIndex = 10;
5849     break;
5850 
5851   case Builtin::BI__sync_nand_and_fetch:
5852   case Builtin::BI__sync_nand_and_fetch_1:
5853   case Builtin::BI__sync_nand_and_fetch_2:
5854   case Builtin::BI__sync_nand_and_fetch_4:
5855   case Builtin::BI__sync_nand_and_fetch_8:
5856   case Builtin::BI__sync_nand_and_fetch_16:
5857     BuiltinIndex = 11;
5858     WarnAboutSemanticsChange = true;
5859     break;
5860 
5861   case Builtin::BI__sync_val_compare_and_swap:
5862   case Builtin::BI__sync_val_compare_and_swap_1:
5863   case Builtin::BI__sync_val_compare_and_swap_2:
5864   case Builtin::BI__sync_val_compare_and_swap_4:
5865   case Builtin::BI__sync_val_compare_and_swap_8:
5866   case Builtin::BI__sync_val_compare_and_swap_16:
5867     BuiltinIndex = 12;
5868     NumFixed = 2;
5869     break;
5870 
5871   case Builtin::BI__sync_bool_compare_and_swap:
5872   case Builtin::BI__sync_bool_compare_and_swap_1:
5873   case Builtin::BI__sync_bool_compare_and_swap_2:
5874   case Builtin::BI__sync_bool_compare_and_swap_4:
5875   case Builtin::BI__sync_bool_compare_and_swap_8:
5876   case Builtin::BI__sync_bool_compare_and_swap_16:
5877     BuiltinIndex = 13;
5878     NumFixed = 2;
5879     ResultType = Context.BoolTy;
5880     break;
5881 
5882   case Builtin::BI__sync_lock_test_and_set:
5883   case Builtin::BI__sync_lock_test_and_set_1:
5884   case Builtin::BI__sync_lock_test_and_set_2:
5885   case Builtin::BI__sync_lock_test_and_set_4:
5886   case Builtin::BI__sync_lock_test_and_set_8:
5887   case Builtin::BI__sync_lock_test_and_set_16:
5888     BuiltinIndex = 14;
5889     break;
5890 
5891   case Builtin::BI__sync_lock_release:
5892   case Builtin::BI__sync_lock_release_1:
5893   case Builtin::BI__sync_lock_release_2:
5894   case Builtin::BI__sync_lock_release_4:
5895   case Builtin::BI__sync_lock_release_8:
5896   case Builtin::BI__sync_lock_release_16:
5897     BuiltinIndex = 15;
5898     NumFixed = 0;
5899     ResultType = Context.VoidTy;
5900     break;
5901 
5902   case Builtin::BI__sync_swap:
5903   case Builtin::BI__sync_swap_1:
5904   case Builtin::BI__sync_swap_2:
5905   case Builtin::BI__sync_swap_4:
5906   case Builtin::BI__sync_swap_8:
5907   case Builtin::BI__sync_swap_16:
5908     BuiltinIndex = 16;
5909     break;
5910   }
5911 
5912   // Now that we know how many fixed arguments we expect, first check that we
5913   // have at least that many.
5914   if (TheCall->getNumArgs() < 1+NumFixed) {
5915     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5916         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5917         << Callee->getSourceRange();
5918     return ExprError();
5919   }
5920 
5921   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5922       << Callee->getSourceRange();
5923 
5924   if (WarnAboutSemanticsChange) {
5925     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5926         << Callee->getSourceRange();
5927   }
5928 
5929   // Get the decl for the concrete builtin from this, we can tell what the
5930   // concrete integer type we should convert to is.
5931   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5932   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5933   FunctionDecl *NewBuiltinDecl;
5934   if (NewBuiltinID == BuiltinID)
5935     NewBuiltinDecl = FDecl;
5936   else {
5937     // Perform builtin lookup to avoid redeclaring it.
5938     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5939     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5940     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5941     assert(Res.getFoundDecl());
5942     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5943     if (!NewBuiltinDecl)
5944       return ExprError();
5945   }
5946 
5947   // The first argument --- the pointer --- has a fixed type; we
5948   // deduce the types of the rest of the arguments accordingly.  Walk
5949   // the remaining arguments, converting them to the deduced value type.
5950   for (unsigned i = 0; i != NumFixed; ++i) {
5951     ExprResult Arg = TheCall->getArg(i+1);
5952 
5953     // GCC does an implicit conversion to the pointer or integer ValType.  This
5954     // can fail in some cases (1i -> int**), check for this error case now.
5955     // Initialize the argument.
5956     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5957                                                    ValType, /*consume*/ false);
5958     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5959     if (Arg.isInvalid())
5960       return ExprError();
5961 
5962     // Okay, we have something that *can* be converted to the right type.  Check
5963     // to see if there is a potentially weird extension going on here.  This can
5964     // happen when you do an atomic operation on something like an char* and
5965     // pass in 42.  The 42 gets converted to char.  This is even more strange
5966     // for things like 45.123 -> char, etc.
5967     // FIXME: Do this check.
5968     TheCall->setArg(i+1, Arg.get());
5969   }
5970 
5971   // Create a new DeclRefExpr to refer to the new decl.
5972   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5973       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5974       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5975       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5976 
5977   // Set the callee in the CallExpr.
5978   // FIXME: This loses syntactic information.
5979   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5980   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5981                                               CK_BuiltinFnToFnPtr);
5982   TheCall->setCallee(PromotedCall.get());
5983 
5984   // Change the result type of the call to match the original value type. This
5985   // is arbitrary, but the codegen for these builtins ins design to handle it
5986   // gracefully.
5987   TheCall->setType(ResultType);
5988 
5989   // Prohibit use of _ExtInt with atomic builtins.
5990   // The arguments would have already been converted to the first argument's
5991   // type, so only need to check the first argument.
5992   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5993   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5994     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5995     return ExprError();
5996   }
5997 
5998   return TheCallResult;
5999 }
6000 
6001 /// SemaBuiltinNontemporalOverloaded - We have a call to
6002 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6003 /// overloaded function based on the pointer type of its last argument.
6004 ///
6005 /// This function goes through and does final semantic checking for these
6006 /// builtins.
6007 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6008   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6009   DeclRefExpr *DRE =
6010       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6011   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6012   unsigned BuiltinID = FDecl->getBuiltinID();
6013   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6014           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6015          "Unexpected nontemporal load/store builtin!");
6016   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6017   unsigned numArgs = isStore ? 2 : 1;
6018 
6019   // Ensure that we have the proper number of arguments.
6020   if (checkArgCount(*this, TheCall, numArgs))
6021     return ExprError();
6022 
6023   // Inspect the last argument of the nontemporal builtin.  This should always
6024   // be a pointer type, from which we imply the type of the memory access.
6025   // Because it is a pointer type, we don't have to worry about any implicit
6026   // casts here.
6027   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6028   ExprResult PointerArgResult =
6029       DefaultFunctionArrayLvalueConversion(PointerArg);
6030 
6031   if (PointerArgResult.isInvalid())
6032     return ExprError();
6033   PointerArg = PointerArgResult.get();
6034   TheCall->setArg(numArgs - 1, PointerArg);
6035 
6036   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6037   if (!pointerType) {
6038     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6039         << PointerArg->getType() << PointerArg->getSourceRange();
6040     return ExprError();
6041   }
6042 
6043   QualType ValType = pointerType->getPointeeType();
6044 
6045   // Strip any qualifiers off ValType.
6046   ValType = ValType.getUnqualifiedType();
6047   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6048       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6049       !ValType->isVectorType()) {
6050     Diag(DRE->getBeginLoc(),
6051          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6052         << PointerArg->getType() << PointerArg->getSourceRange();
6053     return ExprError();
6054   }
6055 
6056   if (!isStore) {
6057     TheCall->setType(ValType);
6058     return TheCallResult;
6059   }
6060 
6061   ExprResult ValArg = TheCall->getArg(0);
6062   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6063       Context, ValType, /*consume*/ false);
6064   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6065   if (ValArg.isInvalid())
6066     return ExprError();
6067 
6068   TheCall->setArg(0, ValArg.get());
6069   TheCall->setType(Context.VoidTy);
6070   return TheCallResult;
6071 }
6072 
6073 /// CheckObjCString - Checks that the argument to the builtin
6074 /// CFString constructor is correct
6075 /// Note: It might also make sense to do the UTF-16 conversion here (would
6076 /// simplify the backend).
6077 bool Sema::CheckObjCString(Expr *Arg) {
6078   Arg = Arg->IgnoreParenCasts();
6079   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6080 
6081   if (!Literal || !Literal->isAscii()) {
6082     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6083         << Arg->getSourceRange();
6084     return true;
6085   }
6086 
6087   if (Literal->containsNonAsciiOrNull()) {
6088     StringRef String = Literal->getString();
6089     unsigned NumBytes = String.size();
6090     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6091     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6092     llvm::UTF16 *ToPtr = &ToBuf[0];
6093 
6094     llvm::ConversionResult Result =
6095         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6096                                  ToPtr + NumBytes, llvm::strictConversion);
6097     // Check for conversion failure.
6098     if (Result != llvm::conversionOK)
6099       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6100           << Arg->getSourceRange();
6101   }
6102   return false;
6103 }
6104 
6105 /// CheckObjCString - Checks that the format string argument to the os_log()
6106 /// and os_trace() functions is correct, and converts it to const char *.
6107 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6108   Arg = Arg->IgnoreParenCasts();
6109   auto *Literal = dyn_cast<StringLiteral>(Arg);
6110   if (!Literal) {
6111     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6112       Literal = ObjcLiteral->getString();
6113     }
6114   }
6115 
6116   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6117     return ExprError(
6118         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6119         << Arg->getSourceRange());
6120   }
6121 
6122   ExprResult Result(Literal);
6123   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6124   InitializedEntity Entity =
6125       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6126   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6127   return Result;
6128 }
6129 
6130 /// Check that the user is calling the appropriate va_start builtin for the
6131 /// target and calling convention.
6132 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6133   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6134   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6135   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6136                     TT.getArch() == llvm::Triple::aarch64_32);
6137   bool IsWindows = TT.isOSWindows();
6138   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6139   if (IsX64 || IsAArch64) {
6140     CallingConv CC = CC_C;
6141     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6142       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6143     if (IsMSVAStart) {
6144       // Don't allow this in System V ABI functions.
6145       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6146         return S.Diag(Fn->getBeginLoc(),
6147                       diag::err_ms_va_start_used_in_sysv_function);
6148     } else {
6149       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6150       // On x64 Windows, don't allow this in System V ABI functions.
6151       // (Yes, that means there's no corresponding way to support variadic
6152       // System V ABI functions on Windows.)
6153       if ((IsWindows && CC == CC_X86_64SysV) ||
6154           (!IsWindows && CC == CC_Win64))
6155         return S.Diag(Fn->getBeginLoc(),
6156                       diag::err_va_start_used_in_wrong_abi_function)
6157                << !IsWindows;
6158     }
6159     return false;
6160   }
6161 
6162   if (IsMSVAStart)
6163     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6164   return false;
6165 }
6166 
6167 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6168                                              ParmVarDecl **LastParam = nullptr) {
6169   // Determine whether the current function, block, or obj-c method is variadic
6170   // and get its parameter list.
6171   bool IsVariadic = false;
6172   ArrayRef<ParmVarDecl *> Params;
6173   DeclContext *Caller = S.CurContext;
6174   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6175     IsVariadic = Block->isVariadic();
6176     Params = Block->parameters();
6177   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6178     IsVariadic = FD->isVariadic();
6179     Params = FD->parameters();
6180   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6181     IsVariadic = MD->isVariadic();
6182     // FIXME: This isn't correct for methods (results in bogus warning).
6183     Params = MD->parameters();
6184   } else if (isa<CapturedDecl>(Caller)) {
6185     // We don't support va_start in a CapturedDecl.
6186     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6187     return true;
6188   } else {
6189     // This must be some other declcontext that parses exprs.
6190     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6191     return true;
6192   }
6193 
6194   if (!IsVariadic) {
6195     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6196     return true;
6197   }
6198 
6199   if (LastParam)
6200     *LastParam = Params.empty() ? nullptr : Params.back();
6201 
6202   return false;
6203 }
6204 
6205 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6206 /// for validity.  Emit an error and return true on failure; return false
6207 /// on success.
6208 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6209   Expr *Fn = TheCall->getCallee();
6210 
6211   if (checkVAStartABI(*this, BuiltinID, Fn))
6212     return true;
6213 
6214   if (checkArgCount(*this, TheCall, 2))
6215     return true;
6216 
6217   // Type-check the first argument normally.
6218   if (checkBuiltinArgument(*this, TheCall, 0))
6219     return true;
6220 
6221   // Check that the current function is variadic, and get its last parameter.
6222   ParmVarDecl *LastParam;
6223   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6224     return true;
6225 
6226   // Verify that the second argument to the builtin is the last argument of the
6227   // current function or method.
6228   bool SecondArgIsLastNamedArgument = false;
6229   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6230 
6231   // These are valid if SecondArgIsLastNamedArgument is false after the next
6232   // block.
6233   QualType Type;
6234   SourceLocation ParamLoc;
6235   bool IsCRegister = false;
6236 
6237   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6238     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6239       SecondArgIsLastNamedArgument = PV == LastParam;
6240 
6241       Type = PV->getType();
6242       ParamLoc = PV->getLocation();
6243       IsCRegister =
6244           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6245     }
6246   }
6247 
6248   if (!SecondArgIsLastNamedArgument)
6249     Diag(TheCall->getArg(1)->getBeginLoc(),
6250          diag::warn_second_arg_of_va_start_not_last_named_param);
6251   else if (IsCRegister || Type->isReferenceType() ||
6252            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6253              // Promotable integers are UB, but enumerations need a bit of
6254              // extra checking to see what their promotable type actually is.
6255              if (!Type->isPromotableIntegerType())
6256                return false;
6257              if (!Type->isEnumeralType())
6258                return true;
6259              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6260              return !(ED &&
6261                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6262            }()) {
6263     unsigned Reason = 0;
6264     if (Type->isReferenceType())  Reason = 1;
6265     else if (IsCRegister)         Reason = 2;
6266     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6267     Diag(ParamLoc, diag::note_parameter_type) << Type;
6268   }
6269 
6270   TheCall->setType(Context.VoidTy);
6271   return false;
6272 }
6273 
6274 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6275   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6276   //                 const char *named_addr);
6277 
6278   Expr *Func = Call->getCallee();
6279 
6280   if (Call->getNumArgs() < 3)
6281     return Diag(Call->getEndLoc(),
6282                 diag::err_typecheck_call_too_few_args_at_least)
6283            << 0 /*function call*/ << 3 << Call->getNumArgs();
6284 
6285   // Type-check the first argument normally.
6286   if (checkBuiltinArgument(*this, Call, 0))
6287     return true;
6288 
6289   // Check that the current function is variadic.
6290   if (checkVAStartIsInVariadicFunction(*this, Func))
6291     return true;
6292 
6293   // __va_start on Windows does not validate the parameter qualifiers
6294 
6295   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6296   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6297 
6298   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6299   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6300 
6301   const QualType &ConstCharPtrTy =
6302       Context.getPointerType(Context.CharTy.withConst());
6303   if (!Arg1Ty->isPointerType() ||
6304       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
6305     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6306         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6307         << 0                                      /* qualifier difference */
6308         << 3                                      /* parameter mismatch */
6309         << 2 << Arg1->getType() << ConstCharPtrTy;
6310 
6311   const QualType SizeTy = Context.getSizeType();
6312   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6313     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6314         << Arg2->getType() << SizeTy << 1 /* different class */
6315         << 0                              /* qualifier difference */
6316         << 3                              /* parameter mismatch */
6317         << 3 << Arg2->getType() << SizeTy;
6318 
6319   return false;
6320 }
6321 
6322 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6323 /// friends.  This is declared to take (...), so we have to check everything.
6324 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6325   if (checkArgCount(*this, TheCall, 2))
6326     return true;
6327 
6328   ExprResult OrigArg0 = TheCall->getArg(0);
6329   ExprResult OrigArg1 = TheCall->getArg(1);
6330 
6331   // Do standard promotions between the two arguments, returning their common
6332   // type.
6333   QualType Res = UsualArithmeticConversions(
6334       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6335   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6336     return true;
6337 
6338   // Make sure any conversions are pushed back into the call; this is
6339   // type safe since unordered compare builtins are declared as "_Bool
6340   // foo(...)".
6341   TheCall->setArg(0, OrigArg0.get());
6342   TheCall->setArg(1, OrigArg1.get());
6343 
6344   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6345     return false;
6346 
6347   // If the common type isn't a real floating type, then the arguments were
6348   // invalid for this operation.
6349   if (Res.isNull() || !Res->isRealFloatingType())
6350     return Diag(OrigArg0.get()->getBeginLoc(),
6351                 diag::err_typecheck_call_invalid_ordered_compare)
6352            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6353            << SourceRange(OrigArg0.get()->getBeginLoc(),
6354                           OrigArg1.get()->getEndLoc());
6355 
6356   return false;
6357 }
6358 
6359 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6360 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6361 /// to check everything. We expect the last argument to be a floating point
6362 /// value.
6363 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6364   if (checkArgCount(*this, TheCall, NumArgs))
6365     return true;
6366 
6367   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6368   // on all preceding parameters just being int.  Try all of those.
6369   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6370     Expr *Arg = TheCall->getArg(i);
6371 
6372     if (Arg->isTypeDependent())
6373       return false;
6374 
6375     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6376 
6377     if (Res.isInvalid())
6378       return true;
6379     TheCall->setArg(i, Res.get());
6380   }
6381 
6382   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6383 
6384   if (OrigArg->isTypeDependent())
6385     return false;
6386 
6387   // Usual Unary Conversions will convert half to float, which we want for
6388   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6389   // type how it is, but do normal L->Rvalue conversions.
6390   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6391     OrigArg = UsualUnaryConversions(OrigArg).get();
6392   else
6393     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6394   TheCall->setArg(NumArgs - 1, OrigArg);
6395 
6396   // This operation requires a non-_Complex floating-point number.
6397   if (!OrigArg->getType()->isRealFloatingType())
6398     return Diag(OrigArg->getBeginLoc(),
6399                 diag::err_typecheck_call_invalid_unary_fp)
6400            << OrigArg->getType() << OrigArg->getSourceRange();
6401 
6402   return false;
6403 }
6404 
6405 /// Perform semantic analysis for a call to __builtin_complex.
6406 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6407   if (checkArgCount(*this, TheCall, 2))
6408     return true;
6409 
6410   bool Dependent = false;
6411   for (unsigned I = 0; I != 2; ++I) {
6412     Expr *Arg = TheCall->getArg(I);
6413     QualType T = Arg->getType();
6414     if (T->isDependentType()) {
6415       Dependent = true;
6416       continue;
6417     }
6418 
6419     // Despite supporting _Complex int, GCC requires a real floating point type
6420     // for the operands of __builtin_complex.
6421     if (!T->isRealFloatingType()) {
6422       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6423              << Arg->getType() << Arg->getSourceRange();
6424     }
6425 
6426     ExprResult Converted = DefaultLvalueConversion(Arg);
6427     if (Converted.isInvalid())
6428       return true;
6429     TheCall->setArg(I, Converted.get());
6430   }
6431 
6432   if (Dependent) {
6433     TheCall->setType(Context.DependentTy);
6434     return false;
6435   }
6436 
6437   Expr *Real = TheCall->getArg(0);
6438   Expr *Imag = TheCall->getArg(1);
6439   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6440     return Diag(Real->getBeginLoc(),
6441                 diag::err_typecheck_call_different_arg_types)
6442            << Real->getType() << Imag->getType()
6443            << Real->getSourceRange() << Imag->getSourceRange();
6444   }
6445 
6446   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6447   // don't allow this builtin to form those types either.
6448   // FIXME: Should we allow these types?
6449   if (Real->getType()->isFloat16Type())
6450     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6451            << "_Float16";
6452   if (Real->getType()->isHalfType())
6453     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6454            << "half";
6455 
6456   TheCall->setType(Context.getComplexType(Real->getType()));
6457   return false;
6458 }
6459 
6460 // Customized Sema Checking for VSX builtins that have the following signature:
6461 // vector [...] builtinName(vector [...], vector [...], const int);
6462 // Which takes the same type of vectors (any legal vector type) for the first
6463 // two arguments and takes compile time constant for the third argument.
6464 // Example builtins are :
6465 // vector double vec_xxpermdi(vector double, vector double, int);
6466 // vector short vec_xxsldwi(vector short, vector short, int);
6467 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6468   unsigned ExpectedNumArgs = 3;
6469   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6470     return true;
6471 
6472   // Check the third argument is a compile time constant
6473   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6474     return Diag(TheCall->getBeginLoc(),
6475                 diag::err_vsx_builtin_nonconstant_argument)
6476            << 3 /* argument index */ << TheCall->getDirectCallee()
6477            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6478                           TheCall->getArg(2)->getEndLoc());
6479 
6480   QualType Arg1Ty = TheCall->getArg(0)->getType();
6481   QualType Arg2Ty = TheCall->getArg(1)->getType();
6482 
6483   // Check the type of argument 1 and argument 2 are vectors.
6484   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6485   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6486       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6487     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6488            << TheCall->getDirectCallee()
6489            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6490                           TheCall->getArg(1)->getEndLoc());
6491   }
6492 
6493   // Check the first two arguments are the same type.
6494   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6495     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6496            << TheCall->getDirectCallee()
6497            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6498                           TheCall->getArg(1)->getEndLoc());
6499   }
6500 
6501   // When default clang type checking is turned off and the customized type
6502   // checking is used, the returning type of the function must be explicitly
6503   // set. Otherwise it is _Bool by default.
6504   TheCall->setType(Arg1Ty);
6505 
6506   return false;
6507 }
6508 
6509 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6510 // This is declared to take (...), so we have to check everything.
6511 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6512   if (TheCall->getNumArgs() < 2)
6513     return ExprError(Diag(TheCall->getEndLoc(),
6514                           diag::err_typecheck_call_too_few_args_at_least)
6515                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6516                      << TheCall->getSourceRange());
6517 
6518   // Determine which of the following types of shufflevector we're checking:
6519   // 1) unary, vector mask: (lhs, mask)
6520   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6521   QualType resType = TheCall->getArg(0)->getType();
6522   unsigned numElements = 0;
6523 
6524   if (!TheCall->getArg(0)->isTypeDependent() &&
6525       !TheCall->getArg(1)->isTypeDependent()) {
6526     QualType LHSType = TheCall->getArg(0)->getType();
6527     QualType RHSType = TheCall->getArg(1)->getType();
6528 
6529     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6530       return ExprError(
6531           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6532           << TheCall->getDirectCallee()
6533           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6534                          TheCall->getArg(1)->getEndLoc()));
6535 
6536     numElements = LHSType->castAs<VectorType>()->getNumElements();
6537     unsigned numResElements = TheCall->getNumArgs() - 2;
6538 
6539     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6540     // with mask.  If so, verify that RHS is an integer vector type with the
6541     // same number of elts as lhs.
6542     if (TheCall->getNumArgs() == 2) {
6543       if (!RHSType->hasIntegerRepresentation() ||
6544           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6545         return ExprError(Diag(TheCall->getBeginLoc(),
6546                               diag::err_vec_builtin_incompatible_vector)
6547                          << TheCall->getDirectCallee()
6548                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6549                                         TheCall->getArg(1)->getEndLoc()));
6550     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6551       return ExprError(Diag(TheCall->getBeginLoc(),
6552                             diag::err_vec_builtin_incompatible_vector)
6553                        << TheCall->getDirectCallee()
6554                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6555                                       TheCall->getArg(1)->getEndLoc()));
6556     } else if (numElements != numResElements) {
6557       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6558       resType = Context.getVectorType(eltType, numResElements,
6559                                       VectorType::GenericVector);
6560     }
6561   }
6562 
6563   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6564     if (TheCall->getArg(i)->isTypeDependent() ||
6565         TheCall->getArg(i)->isValueDependent())
6566       continue;
6567 
6568     Optional<llvm::APSInt> Result;
6569     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6570       return ExprError(Diag(TheCall->getBeginLoc(),
6571                             diag::err_shufflevector_nonconstant_argument)
6572                        << TheCall->getArg(i)->getSourceRange());
6573 
6574     // Allow -1 which will be translated to undef in the IR.
6575     if (Result->isSigned() && Result->isAllOnesValue())
6576       continue;
6577 
6578     if (Result->getActiveBits() > 64 ||
6579         Result->getZExtValue() >= numElements * 2)
6580       return ExprError(Diag(TheCall->getBeginLoc(),
6581                             diag::err_shufflevector_argument_too_large)
6582                        << TheCall->getArg(i)->getSourceRange());
6583   }
6584 
6585   SmallVector<Expr*, 32> exprs;
6586 
6587   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6588     exprs.push_back(TheCall->getArg(i));
6589     TheCall->setArg(i, nullptr);
6590   }
6591 
6592   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6593                                          TheCall->getCallee()->getBeginLoc(),
6594                                          TheCall->getRParenLoc());
6595 }
6596 
6597 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6598 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6599                                        SourceLocation BuiltinLoc,
6600                                        SourceLocation RParenLoc) {
6601   ExprValueKind VK = VK_PRValue;
6602   ExprObjectKind OK = OK_Ordinary;
6603   QualType DstTy = TInfo->getType();
6604   QualType SrcTy = E->getType();
6605 
6606   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6607     return ExprError(Diag(BuiltinLoc,
6608                           diag::err_convertvector_non_vector)
6609                      << E->getSourceRange());
6610   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6611     return ExprError(Diag(BuiltinLoc,
6612                           diag::err_convertvector_non_vector_type));
6613 
6614   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6615     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6616     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6617     if (SrcElts != DstElts)
6618       return ExprError(Diag(BuiltinLoc,
6619                             diag::err_convertvector_incompatible_vector)
6620                        << E->getSourceRange());
6621   }
6622 
6623   return new (Context)
6624       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6625 }
6626 
6627 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6628 // This is declared to take (const void*, ...) and can take two
6629 // optional constant int args.
6630 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6631   unsigned NumArgs = TheCall->getNumArgs();
6632 
6633   if (NumArgs > 3)
6634     return Diag(TheCall->getEndLoc(),
6635                 diag::err_typecheck_call_too_many_args_at_most)
6636            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6637 
6638   // Argument 0 is checked for us and the remaining arguments must be
6639   // constant integers.
6640   for (unsigned i = 1; i != NumArgs; ++i)
6641     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6642       return true;
6643 
6644   return false;
6645 }
6646 
6647 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6648 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6649   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6650     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6651            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6652   if (checkArgCount(*this, TheCall, 1))
6653     return true;
6654   Expr *Arg = TheCall->getArg(0);
6655   if (Arg->isInstantiationDependent())
6656     return false;
6657 
6658   QualType ArgTy = Arg->getType();
6659   if (!ArgTy->hasFloatingRepresentation())
6660     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6661            << ArgTy;
6662   if (Arg->isLValue()) {
6663     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6664     TheCall->setArg(0, FirstArg.get());
6665   }
6666   TheCall->setType(TheCall->getArg(0)->getType());
6667   return false;
6668 }
6669 
6670 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6671 // __assume does not evaluate its arguments, and should warn if its argument
6672 // has side effects.
6673 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6674   Expr *Arg = TheCall->getArg(0);
6675   if (Arg->isInstantiationDependent()) return false;
6676 
6677   if (Arg->HasSideEffects(Context))
6678     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6679         << Arg->getSourceRange()
6680         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6681 
6682   return false;
6683 }
6684 
6685 /// Handle __builtin_alloca_with_align. This is declared
6686 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6687 /// than 8.
6688 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6689   // The alignment must be a constant integer.
6690   Expr *Arg = TheCall->getArg(1);
6691 
6692   // We can't check the value of a dependent argument.
6693   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6694     if (const auto *UE =
6695             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6696       if (UE->getKind() == UETT_AlignOf ||
6697           UE->getKind() == UETT_PreferredAlignOf)
6698         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6699             << Arg->getSourceRange();
6700 
6701     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6702 
6703     if (!Result.isPowerOf2())
6704       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6705              << Arg->getSourceRange();
6706 
6707     if (Result < Context.getCharWidth())
6708       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6709              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6710 
6711     if (Result > std::numeric_limits<int32_t>::max())
6712       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6713              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6714   }
6715 
6716   return false;
6717 }
6718 
6719 /// Handle __builtin_assume_aligned. This is declared
6720 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6721 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6722   unsigned NumArgs = TheCall->getNumArgs();
6723 
6724   if (NumArgs > 3)
6725     return Diag(TheCall->getEndLoc(),
6726                 diag::err_typecheck_call_too_many_args_at_most)
6727            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6728 
6729   // The alignment must be a constant integer.
6730   Expr *Arg = TheCall->getArg(1);
6731 
6732   // We can't check the value of a dependent argument.
6733   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6734     llvm::APSInt Result;
6735     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6736       return true;
6737 
6738     if (!Result.isPowerOf2())
6739       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6740              << Arg->getSourceRange();
6741 
6742     if (Result > Sema::MaximumAlignment)
6743       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6744           << Arg->getSourceRange() << Sema::MaximumAlignment;
6745   }
6746 
6747   if (NumArgs > 2) {
6748     ExprResult Arg(TheCall->getArg(2));
6749     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6750       Context.getSizeType(), false);
6751     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6752     if (Arg.isInvalid()) return true;
6753     TheCall->setArg(2, Arg.get());
6754   }
6755 
6756   return false;
6757 }
6758 
6759 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6760   unsigned BuiltinID =
6761       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6762   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6763 
6764   unsigned NumArgs = TheCall->getNumArgs();
6765   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6766   if (NumArgs < NumRequiredArgs) {
6767     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6768            << 0 /* function call */ << NumRequiredArgs << NumArgs
6769            << TheCall->getSourceRange();
6770   }
6771   if (NumArgs >= NumRequiredArgs + 0x100) {
6772     return Diag(TheCall->getEndLoc(),
6773                 diag::err_typecheck_call_too_many_args_at_most)
6774            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6775            << TheCall->getSourceRange();
6776   }
6777   unsigned i = 0;
6778 
6779   // For formatting call, check buffer arg.
6780   if (!IsSizeCall) {
6781     ExprResult Arg(TheCall->getArg(i));
6782     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6783         Context, Context.VoidPtrTy, false);
6784     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6785     if (Arg.isInvalid())
6786       return true;
6787     TheCall->setArg(i, Arg.get());
6788     i++;
6789   }
6790 
6791   // Check string literal arg.
6792   unsigned FormatIdx = i;
6793   {
6794     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6795     if (Arg.isInvalid())
6796       return true;
6797     TheCall->setArg(i, Arg.get());
6798     i++;
6799   }
6800 
6801   // Make sure variadic args are scalar.
6802   unsigned FirstDataArg = i;
6803   while (i < NumArgs) {
6804     ExprResult Arg = DefaultVariadicArgumentPromotion(
6805         TheCall->getArg(i), VariadicFunction, nullptr);
6806     if (Arg.isInvalid())
6807       return true;
6808     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6809     if (ArgSize.getQuantity() >= 0x100) {
6810       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6811              << i << (int)ArgSize.getQuantity() << 0xff
6812              << TheCall->getSourceRange();
6813     }
6814     TheCall->setArg(i, Arg.get());
6815     i++;
6816   }
6817 
6818   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6819   // call to avoid duplicate diagnostics.
6820   if (!IsSizeCall) {
6821     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6822     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6823     bool Success = CheckFormatArguments(
6824         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6825         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6826         CheckedVarArgs);
6827     if (!Success)
6828       return true;
6829   }
6830 
6831   if (IsSizeCall) {
6832     TheCall->setType(Context.getSizeType());
6833   } else {
6834     TheCall->setType(Context.VoidPtrTy);
6835   }
6836   return false;
6837 }
6838 
6839 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6840 /// TheCall is a constant expression.
6841 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6842                                   llvm::APSInt &Result) {
6843   Expr *Arg = TheCall->getArg(ArgNum);
6844   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6845   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6846 
6847   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6848 
6849   Optional<llvm::APSInt> R;
6850   if (!(R = Arg->getIntegerConstantExpr(Context)))
6851     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6852            << FDecl->getDeclName() << Arg->getSourceRange();
6853   Result = *R;
6854   return false;
6855 }
6856 
6857 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6858 /// TheCall is a constant expression in the range [Low, High].
6859 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6860                                        int Low, int High, bool RangeIsError) {
6861   if (isConstantEvaluated())
6862     return false;
6863   llvm::APSInt Result;
6864 
6865   // We can't check the value of a dependent argument.
6866   Expr *Arg = TheCall->getArg(ArgNum);
6867   if (Arg->isTypeDependent() || Arg->isValueDependent())
6868     return false;
6869 
6870   // Check constant-ness first.
6871   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6872     return true;
6873 
6874   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6875     if (RangeIsError)
6876       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6877              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6878     else
6879       // Defer the warning until we know if the code will be emitted so that
6880       // dead code can ignore this.
6881       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6882                           PDiag(diag::warn_argument_invalid_range)
6883                               << toString(Result, 10) << Low << High
6884                               << Arg->getSourceRange());
6885   }
6886 
6887   return false;
6888 }
6889 
6890 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6891 /// TheCall is a constant expression is a multiple of Num..
6892 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6893                                           unsigned Num) {
6894   llvm::APSInt Result;
6895 
6896   // We can't check the value of a dependent argument.
6897   Expr *Arg = TheCall->getArg(ArgNum);
6898   if (Arg->isTypeDependent() || Arg->isValueDependent())
6899     return false;
6900 
6901   // Check constant-ness first.
6902   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6903     return true;
6904 
6905   if (Result.getSExtValue() % Num != 0)
6906     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6907            << Num << Arg->getSourceRange();
6908 
6909   return false;
6910 }
6911 
6912 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6913 /// constant expression representing a power of 2.
6914 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6915   llvm::APSInt Result;
6916 
6917   // We can't check the value of a dependent argument.
6918   Expr *Arg = TheCall->getArg(ArgNum);
6919   if (Arg->isTypeDependent() || Arg->isValueDependent())
6920     return false;
6921 
6922   // Check constant-ness first.
6923   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6924     return true;
6925 
6926   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6927   // and only if x is a power of 2.
6928   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6929     return false;
6930 
6931   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6932          << Arg->getSourceRange();
6933 }
6934 
6935 static bool IsShiftedByte(llvm::APSInt Value) {
6936   if (Value.isNegative())
6937     return false;
6938 
6939   // Check if it's a shifted byte, by shifting it down
6940   while (true) {
6941     // If the value fits in the bottom byte, the check passes.
6942     if (Value < 0x100)
6943       return true;
6944 
6945     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6946     // fails.
6947     if ((Value & 0xFF) != 0)
6948       return false;
6949 
6950     // If the bottom 8 bits are all 0, but something above that is nonzero,
6951     // then shifting the value right by 8 bits won't affect whether it's a
6952     // shifted byte or not. So do that, and go round again.
6953     Value >>= 8;
6954   }
6955 }
6956 
6957 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6958 /// a constant expression representing an arbitrary byte value shifted left by
6959 /// a multiple of 8 bits.
6960 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6961                                              unsigned ArgBits) {
6962   llvm::APSInt Result;
6963 
6964   // We can't check the value of a dependent argument.
6965   Expr *Arg = TheCall->getArg(ArgNum);
6966   if (Arg->isTypeDependent() || Arg->isValueDependent())
6967     return false;
6968 
6969   // Check constant-ness first.
6970   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6971     return true;
6972 
6973   // Truncate to the given size.
6974   Result = Result.getLoBits(ArgBits);
6975   Result.setIsUnsigned(true);
6976 
6977   if (IsShiftedByte(Result))
6978     return false;
6979 
6980   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6981          << Arg->getSourceRange();
6982 }
6983 
6984 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6985 /// TheCall is a constant expression representing either a shifted byte value,
6986 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6987 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6988 /// Arm MVE intrinsics.
6989 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6990                                                    int ArgNum,
6991                                                    unsigned ArgBits) {
6992   llvm::APSInt Result;
6993 
6994   // We can't check the value of a dependent argument.
6995   Expr *Arg = TheCall->getArg(ArgNum);
6996   if (Arg->isTypeDependent() || Arg->isValueDependent())
6997     return false;
6998 
6999   // Check constant-ness first.
7000   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7001     return true;
7002 
7003   // Truncate to the given size.
7004   Result = Result.getLoBits(ArgBits);
7005   Result.setIsUnsigned(true);
7006 
7007   // Check to see if it's in either of the required forms.
7008   if (IsShiftedByte(Result) ||
7009       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7010     return false;
7011 
7012   return Diag(TheCall->getBeginLoc(),
7013               diag::err_argument_not_shifted_byte_or_xxff)
7014          << Arg->getSourceRange();
7015 }
7016 
7017 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7018 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7019   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7020     if (checkArgCount(*this, TheCall, 2))
7021       return true;
7022     Expr *Arg0 = TheCall->getArg(0);
7023     Expr *Arg1 = TheCall->getArg(1);
7024 
7025     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7026     if (FirstArg.isInvalid())
7027       return true;
7028     QualType FirstArgType = FirstArg.get()->getType();
7029     if (!FirstArgType->isAnyPointerType())
7030       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7031                << "first" << FirstArgType << Arg0->getSourceRange();
7032     TheCall->setArg(0, FirstArg.get());
7033 
7034     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7035     if (SecArg.isInvalid())
7036       return true;
7037     QualType SecArgType = SecArg.get()->getType();
7038     if (!SecArgType->isIntegerType())
7039       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7040                << "second" << SecArgType << Arg1->getSourceRange();
7041 
7042     // Derive the return type from the pointer argument.
7043     TheCall->setType(FirstArgType);
7044     return false;
7045   }
7046 
7047   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7048     if (checkArgCount(*this, TheCall, 2))
7049       return true;
7050 
7051     Expr *Arg0 = TheCall->getArg(0);
7052     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7053     if (FirstArg.isInvalid())
7054       return true;
7055     QualType FirstArgType = FirstArg.get()->getType();
7056     if (!FirstArgType->isAnyPointerType())
7057       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7058                << "first" << FirstArgType << Arg0->getSourceRange();
7059     TheCall->setArg(0, FirstArg.get());
7060 
7061     // Derive the return type from the pointer argument.
7062     TheCall->setType(FirstArgType);
7063 
7064     // Second arg must be an constant in range [0,15]
7065     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7066   }
7067 
7068   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7069     if (checkArgCount(*this, TheCall, 2))
7070       return true;
7071     Expr *Arg0 = TheCall->getArg(0);
7072     Expr *Arg1 = TheCall->getArg(1);
7073 
7074     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7075     if (FirstArg.isInvalid())
7076       return true;
7077     QualType FirstArgType = FirstArg.get()->getType();
7078     if (!FirstArgType->isAnyPointerType())
7079       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7080                << "first" << FirstArgType << Arg0->getSourceRange();
7081 
7082     QualType SecArgType = Arg1->getType();
7083     if (!SecArgType->isIntegerType())
7084       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7085                << "second" << SecArgType << Arg1->getSourceRange();
7086     TheCall->setType(Context.IntTy);
7087     return false;
7088   }
7089 
7090   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7091       BuiltinID == AArch64::BI__builtin_arm_stg) {
7092     if (checkArgCount(*this, TheCall, 1))
7093       return true;
7094     Expr *Arg0 = TheCall->getArg(0);
7095     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7096     if (FirstArg.isInvalid())
7097       return true;
7098 
7099     QualType FirstArgType = FirstArg.get()->getType();
7100     if (!FirstArgType->isAnyPointerType())
7101       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7102                << "first" << FirstArgType << Arg0->getSourceRange();
7103     TheCall->setArg(0, FirstArg.get());
7104 
7105     // Derive the return type from the pointer argument.
7106     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7107       TheCall->setType(FirstArgType);
7108     return false;
7109   }
7110 
7111   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7112     Expr *ArgA = TheCall->getArg(0);
7113     Expr *ArgB = TheCall->getArg(1);
7114 
7115     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7116     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7117 
7118     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7119       return true;
7120 
7121     QualType ArgTypeA = ArgExprA.get()->getType();
7122     QualType ArgTypeB = ArgExprB.get()->getType();
7123 
7124     auto isNull = [&] (Expr *E) -> bool {
7125       return E->isNullPointerConstant(
7126                         Context, Expr::NPC_ValueDependentIsNotNull); };
7127 
7128     // argument should be either a pointer or null
7129     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7130       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7131         << "first" << ArgTypeA << ArgA->getSourceRange();
7132 
7133     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7134       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7135         << "second" << ArgTypeB << ArgB->getSourceRange();
7136 
7137     // Ensure Pointee types are compatible
7138     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7139         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7140       QualType pointeeA = ArgTypeA->getPointeeType();
7141       QualType pointeeB = ArgTypeB->getPointeeType();
7142       if (!Context.typesAreCompatible(
7143              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7144              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7145         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7146           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7147           << ArgB->getSourceRange();
7148       }
7149     }
7150 
7151     // at least one argument should be pointer type
7152     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7153       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7154         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7155 
7156     if (isNull(ArgA)) // adopt type of the other pointer
7157       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7158 
7159     if (isNull(ArgB))
7160       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7161 
7162     TheCall->setArg(0, ArgExprA.get());
7163     TheCall->setArg(1, ArgExprB.get());
7164     TheCall->setType(Context.LongLongTy);
7165     return false;
7166   }
7167   assert(false && "Unhandled ARM MTE intrinsic");
7168   return true;
7169 }
7170 
7171 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7172 /// TheCall is an ARM/AArch64 special register string literal.
7173 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7174                                     int ArgNum, unsigned ExpectedFieldNum,
7175                                     bool AllowName) {
7176   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7177                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7178                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7179                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7180                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7181                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7182   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7183                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7184                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7185                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7186                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7187                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7188   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7189 
7190   // We can't check the value of a dependent argument.
7191   Expr *Arg = TheCall->getArg(ArgNum);
7192   if (Arg->isTypeDependent() || Arg->isValueDependent())
7193     return false;
7194 
7195   // Check if the argument is a string literal.
7196   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7197     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7198            << Arg->getSourceRange();
7199 
7200   // Check the type of special register given.
7201   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7202   SmallVector<StringRef, 6> Fields;
7203   Reg.split(Fields, ":");
7204 
7205   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7206     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7207            << Arg->getSourceRange();
7208 
7209   // If the string is the name of a register then we cannot check that it is
7210   // valid here but if the string is of one the forms described in ACLE then we
7211   // can check that the supplied fields are integers and within the valid
7212   // ranges.
7213   if (Fields.size() > 1) {
7214     bool FiveFields = Fields.size() == 5;
7215 
7216     bool ValidString = true;
7217     if (IsARMBuiltin) {
7218       ValidString &= Fields[0].startswith_insensitive("cp") ||
7219                      Fields[0].startswith_insensitive("p");
7220       if (ValidString)
7221         Fields[0] = Fields[0].drop_front(
7222             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7223 
7224       ValidString &= Fields[2].startswith_insensitive("c");
7225       if (ValidString)
7226         Fields[2] = Fields[2].drop_front(1);
7227 
7228       if (FiveFields) {
7229         ValidString &= Fields[3].startswith_insensitive("c");
7230         if (ValidString)
7231           Fields[3] = Fields[3].drop_front(1);
7232       }
7233     }
7234 
7235     SmallVector<int, 5> Ranges;
7236     if (FiveFields)
7237       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7238     else
7239       Ranges.append({15, 7, 15});
7240 
7241     for (unsigned i=0; i<Fields.size(); ++i) {
7242       int IntField;
7243       ValidString &= !Fields[i].getAsInteger(10, IntField);
7244       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7245     }
7246 
7247     if (!ValidString)
7248       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7249              << Arg->getSourceRange();
7250   } else if (IsAArch64Builtin && Fields.size() == 1) {
7251     // If the register name is one of those that appear in the condition below
7252     // and the special register builtin being used is one of the write builtins,
7253     // then we require that the argument provided for writing to the register
7254     // is an integer constant expression. This is because it will be lowered to
7255     // an MSR (immediate) instruction, so we need to know the immediate at
7256     // compile time.
7257     if (TheCall->getNumArgs() != 2)
7258       return false;
7259 
7260     std::string RegLower = Reg.lower();
7261     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7262         RegLower != "pan" && RegLower != "uao")
7263       return false;
7264 
7265     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7266   }
7267 
7268   return false;
7269 }
7270 
7271 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7272 /// Emit an error and return true on failure; return false on success.
7273 /// TypeStr is a string containing the type descriptor of the value returned by
7274 /// the builtin and the descriptors of the expected type of the arguments.
7275 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
7276 
7277   assert((TypeStr[0] != '\0') &&
7278          "Invalid types in PPC MMA builtin declaration");
7279 
7280   unsigned Mask = 0;
7281   unsigned ArgNum = 0;
7282 
7283   // The first type in TypeStr is the type of the value returned by the
7284   // builtin. So we first read that type and change the type of TheCall.
7285   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7286   TheCall->setType(type);
7287 
7288   while (*TypeStr != '\0') {
7289     Mask = 0;
7290     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7291     if (ArgNum >= TheCall->getNumArgs()) {
7292       ArgNum++;
7293       break;
7294     }
7295 
7296     Expr *Arg = TheCall->getArg(ArgNum);
7297     QualType ArgType = Arg->getType();
7298 
7299     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
7300         (!ExpectedType->isVoidPointerType() &&
7301            ArgType.getCanonicalType() != ExpectedType))
7302       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
7303              << ArgType << ExpectedType << 1 << 0 << 0;
7304 
7305     // If the value of the Mask is not 0, we have a constraint in the size of
7306     // the integer argument so here we ensure the argument is a constant that
7307     // is in the valid range.
7308     if (Mask != 0 &&
7309         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7310       return true;
7311 
7312     ArgNum++;
7313   }
7314 
7315   // In case we exited early from the previous loop, there are other types to
7316   // read from TypeStr. So we need to read them all to ensure we have the right
7317   // number of arguments in TheCall and if it is not the case, to display a
7318   // better error message.
7319   while (*TypeStr != '\0') {
7320     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7321     ArgNum++;
7322   }
7323   if (checkArgCount(*this, TheCall, ArgNum))
7324     return true;
7325 
7326   return false;
7327 }
7328 
7329 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7330 /// This checks that the target supports __builtin_longjmp and
7331 /// that val is a constant 1.
7332 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7333   if (!Context.getTargetInfo().hasSjLjLowering())
7334     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7335            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7336 
7337   Expr *Arg = TheCall->getArg(1);
7338   llvm::APSInt Result;
7339 
7340   // TODO: This is less than ideal. Overload this to take a value.
7341   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7342     return true;
7343 
7344   if (Result != 1)
7345     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7346            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7347 
7348   return false;
7349 }
7350 
7351 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7352 /// This checks that the target supports __builtin_setjmp.
7353 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7354   if (!Context.getTargetInfo().hasSjLjLowering())
7355     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7356            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7357   return false;
7358 }
7359 
7360 namespace {
7361 
7362 class UncoveredArgHandler {
7363   enum { Unknown = -1, AllCovered = -2 };
7364 
7365   signed FirstUncoveredArg = Unknown;
7366   SmallVector<const Expr *, 4> DiagnosticExprs;
7367 
7368 public:
7369   UncoveredArgHandler() = default;
7370 
7371   bool hasUncoveredArg() const {
7372     return (FirstUncoveredArg >= 0);
7373   }
7374 
7375   unsigned getUncoveredArg() const {
7376     assert(hasUncoveredArg() && "no uncovered argument");
7377     return FirstUncoveredArg;
7378   }
7379 
7380   void setAllCovered() {
7381     // A string has been found with all arguments covered, so clear out
7382     // the diagnostics.
7383     DiagnosticExprs.clear();
7384     FirstUncoveredArg = AllCovered;
7385   }
7386 
7387   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7388     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7389 
7390     // Don't update if a previous string covers all arguments.
7391     if (FirstUncoveredArg == AllCovered)
7392       return;
7393 
7394     // UncoveredArgHandler tracks the highest uncovered argument index
7395     // and with it all the strings that match this index.
7396     if (NewFirstUncoveredArg == FirstUncoveredArg)
7397       DiagnosticExprs.push_back(StrExpr);
7398     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7399       DiagnosticExprs.clear();
7400       DiagnosticExprs.push_back(StrExpr);
7401       FirstUncoveredArg = NewFirstUncoveredArg;
7402     }
7403   }
7404 
7405   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7406 };
7407 
7408 enum StringLiteralCheckType {
7409   SLCT_NotALiteral,
7410   SLCT_UncheckedLiteral,
7411   SLCT_CheckedLiteral
7412 };
7413 
7414 } // namespace
7415 
7416 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7417                                      BinaryOperatorKind BinOpKind,
7418                                      bool AddendIsRight) {
7419   unsigned BitWidth = Offset.getBitWidth();
7420   unsigned AddendBitWidth = Addend.getBitWidth();
7421   // There might be negative interim results.
7422   if (Addend.isUnsigned()) {
7423     Addend = Addend.zext(++AddendBitWidth);
7424     Addend.setIsSigned(true);
7425   }
7426   // Adjust the bit width of the APSInts.
7427   if (AddendBitWidth > BitWidth) {
7428     Offset = Offset.sext(AddendBitWidth);
7429     BitWidth = AddendBitWidth;
7430   } else if (BitWidth > AddendBitWidth) {
7431     Addend = Addend.sext(BitWidth);
7432   }
7433 
7434   bool Ov = false;
7435   llvm::APSInt ResOffset = Offset;
7436   if (BinOpKind == BO_Add)
7437     ResOffset = Offset.sadd_ov(Addend, Ov);
7438   else {
7439     assert(AddendIsRight && BinOpKind == BO_Sub &&
7440            "operator must be add or sub with addend on the right");
7441     ResOffset = Offset.ssub_ov(Addend, Ov);
7442   }
7443 
7444   // We add an offset to a pointer here so we should support an offset as big as
7445   // possible.
7446   if (Ov) {
7447     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7448            "index (intermediate) result too big");
7449     Offset = Offset.sext(2 * BitWidth);
7450     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7451     return;
7452   }
7453 
7454   Offset = ResOffset;
7455 }
7456 
7457 namespace {
7458 
7459 // This is a wrapper class around StringLiteral to support offsetted string
7460 // literals as format strings. It takes the offset into account when returning
7461 // the string and its length or the source locations to display notes correctly.
7462 class FormatStringLiteral {
7463   const StringLiteral *FExpr;
7464   int64_t Offset;
7465 
7466  public:
7467   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7468       : FExpr(fexpr), Offset(Offset) {}
7469 
7470   StringRef getString() const {
7471     return FExpr->getString().drop_front(Offset);
7472   }
7473 
7474   unsigned getByteLength() const {
7475     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7476   }
7477 
7478   unsigned getLength() const { return FExpr->getLength() - Offset; }
7479   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7480 
7481   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7482 
7483   QualType getType() const { return FExpr->getType(); }
7484 
7485   bool isAscii() const { return FExpr->isAscii(); }
7486   bool isWide() const { return FExpr->isWide(); }
7487   bool isUTF8() const { return FExpr->isUTF8(); }
7488   bool isUTF16() const { return FExpr->isUTF16(); }
7489   bool isUTF32() const { return FExpr->isUTF32(); }
7490   bool isPascal() const { return FExpr->isPascal(); }
7491 
7492   SourceLocation getLocationOfByte(
7493       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7494       const TargetInfo &Target, unsigned *StartToken = nullptr,
7495       unsigned *StartTokenByteOffset = nullptr) const {
7496     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7497                                     StartToken, StartTokenByteOffset);
7498   }
7499 
7500   SourceLocation getBeginLoc() const LLVM_READONLY {
7501     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7502   }
7503 
7504   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7505 };
7506 
7507 }  // namespace
7508 
7509 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7510                               const Expr *OrigFormatExpr,
7511                               ArrayRef<const Expr *> Args,
7512                               bool HasVAListArg, unsigned format_idx,
7513                               unsigned firstDataArg,
7514                               Sema::FormatStringType Type,
7515                               bool inFunctionCall,
7516                               Sema::VariadicCallType CallType,
7517                               llvm::SmallBitVector &CheckedVarArgs,
7518                               UncoveredArgHandler &UncoveredArg,
7519                               bool IgnoreStringsWithoutSpecifiers);
7520 
7521 // Determine if an expression is a string literal or constant string.
7522 // If this function returns false on the arguments to a function expecting a
7523 // format string, we will usually need to emit a warning.
7524 // True string literals are then checked by CheckFormatString.
7525 static StringLiteralCheckType
7526 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7527                       bool HasVAListArg, unsigned format_idx,
7528                       unsigned firstDataArg, Sema::FormatStringType Type,
7529                       Sema::VariadicCallType CallType, bool InFunctionCall,
7530                       llvm::SmallBitVector &CheckedVarArgs,
7531                       UncoveredArgHandler &UncoveredArg,
7532                       llvm::APSInt Offset,
7533                       bool IgnoreStringsWithoutSpecifiers = false) {
7534   if (S.isConstantEvaluated())
7535     return SLCT_NotALiteral;
7536  tryAgain:
7537   assert(Offset.isSigned() && "invalid offset");
7538 
7539   if (E->isTypeDependent() || E->isValueDependent())
7540     return SLCT_NotALiteral;
7541 
7542   E = E->IgnoreParenCasts();
7543 
7544   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7545     // Technically -Wformat-nonliteral does not warn about this case.
7546     // The behavior of printf and friends in this case is implementation
7547     // dependent.  Ideally if the format string cannot be null then
7548     // it should have a 'nonnull' attribute in the function prototype.
7549     return SLCT_UncheckedLiteral;
7550 
7551   switch (E->getStmtClass()) {
7552   case Stmt::BinaryConditionalOperatorClass:
7553   case Stmt::ConditionalOperatorClass: {
7554     // The expression is a literal if both sub-expressions were, and it was
7555     // completely checked only if both sub-expressions were checked.
7556     const AbstractConditionalOperator *C =
7557         cast<AbstractConditionalOperator>(E);
7558 
7559     // Determine whether it is necessary to check both sub-expressions, for
7560     // example, because the condition expression is a constant that can be
7561     // evaluated at compile time.
7562     bool CheckLeft = true, CheckRight = true;
7563 
7564     bool Cond;
7565     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7566                                                  S.isConstantEvaluated())) {
7567       if (Cond)
7568         CheckRight = false;
7569       else
7570         CheckLeft = false;
7571     }
7572 
7573     // We need to maintain the offsets for the right and the left hand side
7574     // separately to check if every possible indexed expression is a valid
7575     // string literal. They might have different offsets for different string
7576     // literals in the end.
7577     StringLiteralCheckType Left;
7578     if (!CheckLeft)
7579       Left = SLCT_UncheckedLiteral;
7580     else {
7581       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7582                                    HasVAListArg, format_idx, firstDataArg,
7583                                    Type, CallType, InFunctionCall,
7584                                    CheckedVarArgs, UncoveredArg, Offset,
7585                                    IgnoreStringsWithoutSpecifiers);
7586       if (Left == SLCT_NotALiteral || !CheckRight) {
7587         return Left;
7588       }
7589     }
7590 
7591     StringLiteralCheckType Right = checkFormatStringExpr(
7592         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7593         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7594         IgnoreStringsWithoutSpecifiers);
7595 
7596     return (CheckLeft && Left < Right) ? Left : Right;
7597   }
7598 
7599   case Stmt::ImplicitCastExprClass:
7600     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7601     goto tryAgain;
7602 
7603   case Stmt::OpaqueValueExprClass:
7604     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7605       E = src;
7606       goto tryAgain;
7607     }
7608     return SLCT_NotALiteral;
7609 
7610   case Stmt::PredefinedExprClass:
7611     // While __func__, etc., are technically not string literals, they
7612     // cannot contain format specifiers and thus are not a security
7613     // liability.
7614     return SLCT_UncheckedLiteral;
7615 
7616   case Stmt::DeclRefExprClass: {
7617     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7618 
7619     // As an exception, do not flag errors for variables binding to
7620     // const string literals.
7621     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7622       bool isConstant = false;
7623       QualType T = DR->getType();
7624 
7625       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7626         isConstant = AT->getElementType().isConstant(S.Context);
7627       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7628         isConstant = T.isConstant(S.Context) &&
7629                      PT->getPointeeType().isConstant(S.Context);
7630       } else if (T->isObjCObjectPointerType()) {
7631         // In ObjC, there is usually no "const ObjectPointer" type,
7632         // so don't check if the pointee type is constant.
7633         isConstant = T.isConstant(S.Context);
7634       }
7635 
7636       if (isConstant) {
7637         if (const Expr *Init = VD->getAnyInitializer()) {
7638           // Look through initializers like const char c[] = { "foo" }
7639           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7640             if (InitList->isStringLiteralInit())
7641               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7642           }
7643           return checkFormatStringExpr(S, Init, Args,
7644                                        HasVAListArg, format_idx,
7645                                        firstDataArg, Type, CallType,
7646                                        /*InFunctionCall*/ false, CheckedVarArgs,
7647                                        UncoveredArg, Offset);
7648         }
7649       }
7650 
7651       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7652       // special check to see if the format string is a function parameter
7653       // of the function calling the printf function.  If the function
7654       // has an attribute indicating it is a printf-like function, then we
7655       // should suppress warnings concerning non-literals being used in a call
7656       // to a vprintf function.  For example:
7657       //
7658       // void
7659       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7660       //      va_list ap;
7661       //      va_start(ap, fmt);
7662       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7663       //      ...
7664       // }
7665       if (HasVAListArg) {
7666         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7667           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7668             int PVIndex = PV->getFunctionScopeIndex() + 1;
7669             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7670               // adjust for implicit parameter
7671               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7672                 if (MD->isInstance())
7673                   ++PVIndex;
7674               // We also check if the formats are compatible.
7675               // We can't pass a 'scanf' string to a 'printf' function.
7676               if (PVIndex == PVFormat->getFormatIdx() &&
7677                   Type == S.GetFormatStringType(PVFormat))
7678                 return SLCT_UncheckedLiteral;
7679             }
7680           }
7681         }
7682       }
7683     }
7684 
7685     return SLCT_NotALiteral;
7686   }
7687 
7688   case Stmt::CallExprClass:
7689   case Stmt::CXXMemberCallExprClass: {
7690     const CallExpr *CE = cast<CallExpr>(E);
7691     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7692       bool IsFirst = true;
7693       StringLiteralCheckType CommonResult;
7694       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7695         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7696         StringLiteralCheckType Result = checkFormatStringExpr(
7697             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7698             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7699             IgnoreStringsWithoutSpecifiers);
7700         if (IsFirst) {
7701           CommonResult = Result;
7702           IsFirst = false;
7703         }
7704       }
7705       if (!IsFirst)
7706         return CommonResult;
7707 
7708       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7709         unsigned BuiltinID = FD->getBuiltinID();
7710         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7711             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7712           const Expr *Arg = CE->getArg(0);
7713           return checkFormatStringExpr(S, Arg, Args,
7714                                        HasVAListArg, format_idx,
7715                                        firstDataArg, Type, CallType,
7716                                        InFunctionCall, CheckedVarArgs,
7717                                        UncoveredArg, Offset,
7718                                        IgnoreStringsWithoutSpecifiers);
7719         }
7720       }
7721     }
7722 
7723     return SLCT_NotALiteral;
7724   }
7725   case Stmt::ObjCMessageExprClass: {
7726     const auto *ME = cast<ObjCMessageExpr>(E);
7727     if (const auto *MD = ME->getMethodDecl()) {
7728       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7729         // As a special case heuristic, if we're using the method -[NSBundle
7730         // localizedStringForKey:value:table:], ignore any key strings that lack
7731         // format specifiers. The idea is that if the key doesn't have any
7732         // format specifiers then its probably just a key to map to the
7733         // localized strings. If it does have format specifiers though, then its
7734         // likely that the text of the key is the format string in the
7735         // programmer's language, and should be checked.
7736         const ObjCInterfaceDecl *IFace;
7737         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7738             IFace->getIdentifier()->isStr("NSBundle") &&
7739             MD->getSelector().isKeywordSelector(
7740                 {"localizedStringForKey", "value", "table"})) {
7741           IgnoreStringsWithoutSpecifiers = true;
7742         }
7743 
7744         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7745         return checkFormatStringExpr(
7746             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7747             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7748             IgnoreStringsWithoutSpecifiers);
7749       }
7750     }
7751 
7752     return SLCT_NotALiteral;
7753   }
7754   case Stmt::ObjCStringLiteralClass:
7755   case Stmt::StringLiteralClass: {
7756     const StringLiteral *StrE = nullptr;
7757 
7758     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7759       StrE = ObjCFExpr->getString();
7760     else
7761       StrE = cast<StringLiteral>(E);
7762 
7763     if (StrE) {
7764       if (Offset.isNegative() || Offset > StrE->getLength()) {
7765         // TODO: It would be better to have an explicit warning for out of
7766         // bounds literals.
7767         return SLCT_NotALiteral;
7768       }
7769       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7770       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7771                         firstDataArg, Type, InFunctionCall, CallType,
7772                         CheckedVarArgs, UncoveredArg,
7773                         IgnoreStringsWithoutSpecifiers);
7774       return SLCT_CheckedLiteral;
7775     }
7776 
7777     return SLCT_NotALiteral;
7778   }
7779   case Stmt::BinaryOperatorClass: {
7780     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7781 
7782     // A string literal + an int offset is still a string literal.
7783     if (BinOp->isAdditiveOp()) {
7784       Expr::EvalResult LResult, RResult;
7785 
7786       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7787           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7788       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7789           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7790 
7791       if (LIsInt != RIsInt) {
7792         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7793 
7794         if (LIsInt) {
7795           if (BinOpKind == BO_Add) {
7796             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7797             E = BinOp->getRHS();
7798             goto tryAgain;
7799           }
7800         } else {
7801           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7802           E = BinOp->getLHS();
7803           goto tryAgain;
7804         }
7805       }
7806     }
7807 
7808     return SLCT_NotALiteral;
7809   }
7810   case Stmt::UnaryOperatorClass: {
7811     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7812     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7813     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7814       Expr::EvalResult IndexResult;
7815       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7816                                        Expr::SE_NoSideEffects,
7817                                        S.isConstantEvaluated())) {
7818         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7819                    /*RHS is int*/ true);
7820         E = ASE->getBase();
7821         goto tryAgain;
7822       }
7823     }
7824 
7825     return SLCT_NotALiteral;
7826   }
7827 
7828   default:
7829     return SLCT_NotALiteral;
7830   }
7831 }
7832 
7833 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7834   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7835       .Case("scanf", FST_Scanf)
7836       .Cases("printf", "printf0", FST_Printf)
7837       .Cases("NSString", "CFString", FST_NSString)
7838       .Case("strftime", FST_Strftime)
7839       .Case("strfmon", FST_Strfmon)
7840       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7841       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7842       .Case("os_trace", FST_OSLog)
7843       .Case("os_log", FST_OSLog)
7844       .Default(FST_Unknown);
7845 }
7846 
7847 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7848 /// functions) for correct use of format strings.
7849 /// Returns true if a format string has been fully checked.
7850 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7851                                 ArrayRef<const Expr *> Args,
7852                                 bool IsCXXMember,
7853                                 VariadicCallType CallType,
7854                                 SourceLocation Loc, SourceRange Range,
7855                                 llvm::SmallBitVector &CheckedVarArgs) {
7856   FormatStringInfo FSI;
7857   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7858     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7859                                 FSI.FirstDataArg, GetFormatStringType(Format),
7860                                 CallType, Loc, Range, CheckedVarArgs);
7861   return false;
7862 }
7863 
7864 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7865                                 bool HasVAListArg, unsigned format_idx,
7866                                 unsigned firstDataArg, FormatStringType Type,
7867                                 VariadicCallType CallType,
7868                                 SourceLocation Loc, SourceRange Range,
7869                                 llvm::SmallBitVector &CheckedVarArgs) {
7870   // CHECK: printf/scanf-like function is called with no format string.
7871   if (format_idx >= Args.size()) {
7872     Diag(Loc, diag::warn_missing_format_string) << Range;
7873     return false;
7874   }
7875 
7876   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7877 
7878   // CHECK: format string is not a string literal.
7879   //
7880   // Dynamically generated format strings are difficult to
7881   // automatically vet at compile time.  Requiring that format strings
7882   // are string literals: (1) permits the checking of format strings by
7883   // the compiler and thereby (2) can practically remove the source of
7884   // many format string exploits.
7885 
7886   // Format string can be either ObjC string (e.g. @"%d") or
7887   // C string (e.g. "%d")
7888   // ObjC string uses the same format specifiers as C string, so we can use
7889   // the same format string checking logic for both ObjC and C strings.
7890   UncoveredArgHandler UncoveredArg;
7891   StringLiteralCheckType CT =
7892       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7893                             format_idx, firstDataArg, Type, CallType,
7894                             /*IsFunctionCall*/ true, CheckedVarArgs,
7895                             UncoveredArg,
7896                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7897 
7898   // Generate a diagnostic where an uncovered argument is detected.
7899   if (UncoveredArg.hasUncoveredArg()) {
7900     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7901     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7902     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7903   }
7904 
7905   if (CT != SLCT_NotALiteral)
7906     // Literal format string found, check done!
7907     return CT == SLCT_CheckedLiteral;
7908 
7909   // Strftime is particular as it always uses a single 'time' argument,
7910   // so it is safe to pass a non-literal string.
7911   if (Type == FST_Strftime)
7912     return false;
7913 
7914   // Do not emit diag when the string param is a macro expansion and the
7915   // format is either NSString or CFString. This is a hack to prevent
7916   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7917   // which are usually used in place of NS and CF string literals.
7918   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7919   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7920     return false;
7921 
7922   // If there are no arguments specified, warn with -Wformat-security, otherwise
7923   // warn only with -Wformat-nonliteral.
7924   if (Args.size() == firstDataArg) {
7925     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7926       << OrigFormatExpr->getSourceRange();
7927     switch (Type) {
7928     default:
7929       break;
7930     case FST_Kprintf:
7931     case FST_FreeBSDKPrintf:
7932     case FST_Printf:
7933       Diag(FormatLoc, diag::note_format_security_fixit)
7934         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7935       break;
7936     case FST_NSString:
7937       Diag(FormatLoc, diag::note_format_security_fixit)
7938         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7939       break;
7940     }
7941   } else {
7942     Diag(FormatLoc, diag::warn_format_nonliteral)
7943       << OrigFormatExpr->getSourceRange();
7944   }
7945   return false;
7946 }
7947 
7948 namespace {
7949 
7950 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7951 protected:
7952   Sema &S;
7953   const FormatStringLiteral *FExpr;
7954   const Expr *OrigFormatExpr;
7955   const Sema::FormatStringType FSType;
7956   const unsigned FirstDataArg;
7957   const unsigned NumDataArgs;
7958   const char *Beg; // Start of format string.
7959   const bool HasVAListArg;
7960   ArrayRef<const Expr *> Args;
7961   unsigned FormatIdx;
7962   llvm::SmallBitVector CoveredArgs;
7963   bool usesPositionalArgs = false;
7964   bool atFirstArg = true;
7965   bool inFunctionCall;
7966   Sema::VariadicCallType CallType;
7967   llvm::SmallBitVector &CheckedVarArgs;
7968   UncoveredArgHandler &UncoveredArg;
7969 
7970 public:
7971   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7972                      const Expr *origFormatExpr,
7973                      const Sema::FormatStringType type, unsigned firstDataArg,
7974                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7975                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7976                      bool inFunctionCall, Sema::VariadicCallType callType,
7977                      llvm::SmallBitVector &CheckedVarArgs,
7978                      UncoveredArgHandler &UncoveredArg)
7979       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7980         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7981         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7982         inFunctionCall(inFunctionCall), CallType(callType),
7983         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7984     CoveredArgs.resize(numDataArgs);
7985     CoveredArgs.reset();
7986   }
7987 
7988   void DoneProcessing();
7989 
7990   void HandleIncompleteSpecifier(const char *startSpecifier,
7991                                  unsigned specifierLen) override;
7992 
7993   void HandleInvalidLengthModifier(
7994                            const analyze_format_string::FormatSpecifier &FS,
7995                            const analyze_format_string::ConversionSpecifier &CS,
7996                            const char *startSpecifier, unsigned specifierLen,
7997                            unsigned DiagID);
7998 
7999   void HandleNonStandardLengthModifier(
8000                     const analyze_format_string::FormatSpecifier &FS,
8001                     const char *startSpecifier, unsigned specifierLen);
8002 
8003   void HandleNonStandardConversionSpecifier(
8004                     const analyze_format_string::ConversionSpecifier &CS,
8005                     const char *startSpecifier, unsigned specifierLen);
8006 
8007   void HandlePosition(const char *startPos, unsigned posLen) override;
8008 
8009   void HandleInvalidPosition(const char *startSpecifier,
8010                              unsigned specifierLen,
8011                              analyze_format_string::PositionContext p) override;
8012 
8013   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8014 
8015   void HandleNullChar(const char *nullCharacter) override;
8016 
8017   template <typename Range>
8018   static void
8019   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8020                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8021                        bool IsStringLocation, Range StringRange,
8022                        ArrayRef<FixItHint> Fixit = None);
8023 
8024 protected:
8025   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8026                                         const char *startSpec,
8027                                         unsigned specifierLen,
8028                                         const char *csStart, unsigned csLen);
8029 
8030   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8031                                          const char *startSpec,
8032                                          unsigned specifierLen);
8033 
8034   SourceRange getFormatStringRange();
8035   CharSourceRange getSpecifierRange(const char *startSpecifier,
8036                                     unsigned specifierLen);
8037   SourceLocation getLocationOfByte(const char *x);
8038 
8039   const Expr *getDataArg(unsigned i) const;
8040 
8041   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8042                     const analyze_format_string::ConversionSpecifier &CS,
8043                     const char *startSpecifier, unsigned specifierLen,
8044                     unsigned argIndex);
8045 
8046   template <typename Range>
8047   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8048                             bool IsStringLocation, Range StringRange,
8049                             ArrayRef<FixItHint> Fixit = None);
8050 };
8051 
8052 } // namespace
8053 
8054 SourceRange CheckFormatHandler::getFormatStringRange() {
8055   return OrigFormatExpr->getSourceRange();
8056 }
8057 
8058 CharSourceRange CheckFormatHandler::
8059 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8060   SourceLocation Start = getLocationOfByte(startSpecifier);
8061   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8062 
8063   // Advance the end SourceLocation by one due to half-open ranges.
8064   End = End.getLocWithOffset(1);
8065 
8066   return CharSourceRange::getCharRange(Start, End);
8067 }
8068 
8069 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8070   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8071                                   S.getLangOpts(), S.Context.getTargetInfo());
8072 }
8073 
8074 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8075                                                    unsigned specifierLen){
8076   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8077                        getLocationOfByte(startSpecifier),
8078                        /*IsStringLocation*/true,
8079                        getSpecifierRange(startSpecifier, specifierLen));
8080 }
8081 
8082 void CheckFormatHandler::HandleInvalidLengthModifier(
8083     const analyze_format_string::FormatSpecifier &FS,
8084     const analyze_format_string::ConversionSpecifier &CS,
8085     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8086   using namespace analyze_format_string;
8087 
8088   const LengthModifier &LM = FS.getLengthModifier();
8089   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8090 
8091   // See if we know how to fix this length modifier.
8092   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8093   if (FixedLM) {
8094     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8095                          getLocationOfByte(LM.getStart()),
8096                          /*IsStringLocation*/true,
8097                          getSpecifierRange(startSpecifier, specifierLen));
8098 
8099     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8100       << FixedLM->toString()
8101       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8102 
8103   } else {
8104     FixItHint Hint;
8105     if (DiagID == diag::warn_format_nonsensical_length)
8106       Hint = FixItHint::CreateRemoval(LMRange);
8107 
8108     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8109                          getLocationOfByte(LM.getStart()),
8110                          /*IsStringLocation*/true,
8111                          getSpecifierRange(startSpecifier, specifierLen),
8112                          Hint);
8113   }
8114 }
8115 
8116 void CheckFormatHandler::HandleNonStandardLengthModifier(
8117     const analyze_format_string::FormatSpecifier &FS,
8118     const char *startSpecifier, unsigned specifierLen) {
8119   using namespace analyze_format_string;
8120 
8121   const LengthModifier &LM = FS.getLengthModifier();
8122   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8123 
8124   // See if we know how to fix this length modifier.
8125   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8126   if (FixedLM) {
8127     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8128                            << LM.toString() << 0,
8129                          getLocationOfByte(LM.getStart()),
8130                          /*IsStringLocation*/true,
8131                          getSpecifierRange(startSpecifier, specifierLen));
8132 
8133     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8134       << FixedLM->toString()
8135       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8136 
8137   } else {
8138     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8139                            << LM.toString() << 0,
8140                          getLocationOfByte(LM.getStart()),
8141                          /*IsStringLocation*/true,
8142                          getSpecifierRange(startSpecifier, specifierLen));
8143   }
8144 }
8145 
8146 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8147     const analyze_format_string::ConversionSpecifier &CS,
8148     const char *startSpecifier, unsigned specifierLen) {
8149   using namespace analyze_format_string;
8150 
8151   // See if we know how to fix this conversion specifier.
8152   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8153   if (FixedCS) {
8154     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8155                           << CS.toString() << /*conversion specifier*/1,
8156                          getLocationOfByte(CS.getStart()),
8157                          /*IsStringLocation*/true,
8158                          getSpecifierRange(startSpecifier, specifierLen));
8159 
8160     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8161     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8162       << FixedCS->toString()
8163       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8164   } else {
8165     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8166                           << CS.toString() << /*conversion specifier*/1,
8167                          getLocationOfByte(CS.getStart()),
8168                          /*IsStringLocation*/true,
8169                          getSpecifierRange(startSpecifier, specifierLen));
8170   }
8171 }
8172 
8173 void CheckFormatHandler::HandlePosition(const char *startPos,
8174                                         unsigned posLen) {
8175   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8176                                getLocationOfByte(startPos),
8177                                /*IsStringLocation*/true,
8178                                getSpecifierRange(startPos, posLen));
8179 }
8180 
8181 void
8182 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8183                                      analyze_format_string::PositionContext p) {
8184   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8185                          << (unsigned) p,
8186                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8187                        getSpecifierRange(startPos, posLen));
8188 }
8189 
8190 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8191                                             unsigned posLen) {
8192   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8193                                getLocationOfByte(startPos),
8194                                /*IsStringLocation*/true,
8195                                getSpecifierRange(startPos, posLen));
8196 }
8197 
8198 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8199   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8200     // The presence of a null character is likely an error.
8201     EmitFormatDiagnostic(
8202       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8203       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8204       getFormatStringRange());
8205   }
8206 }
8207 
8208 // Note that this may return NULL if there was an error parsing or building
8209 // one of the argument expressions.
8210 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8211   return Args[FirstDataArg + i];
8212 }
8213 
8214 void CheckFormatHandler::DoneProcessing() {
8215   // Does the number of data arguments exceed the number of
8216   // format conversions in the format string?
8217   if (!HasVAListArg) {
8218       // Find any arguments that weren't covered.
8219     CoveredArgs.flip();
8220     signed notCoveredArg = CoveredArgs.find_first();
8221     if (notCoveredArg >= 0) {
8222       assert((unsigned)notCoveredArg < NumDataArgs);
8223       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8224     } else {
8225       UncoveredArg.setAllCovered();
8226     }
8227   }
8228 }
8229 
8230 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8231                                    const Expr *ArgExpr) {
8232   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8233          "Invalid state");
8234 
8235   if (!ArgExpr)
8236     return;
8237 
8238   SourceLocation Loc = ArgExpr->getBeginLoc();
8239 
8240   if (S.getSourceManager().isInSystemMacro(Loc))
8241     return;
8242 
8243   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8244   for (auto E : DiagnosticExprs)
8245     PDiag << E->getSourceRange();
8246 
8247   CheckFormatHandler::EmitFormatDiagnostic(
8248                                   S, IsFunctionCall, DiagnosticExprs[0],
8249                                   PDiag, Loc, /*IsStringLocation*/false,
8250                                   DiagnosticExprs[0]->getSourceRange());
8251 }
8252 
8253 bool
8254 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8255                                                      SourceLocation Loc,
8256                                                      const char *startSpec,
8257                                                      unsigned specifierLen,
8258                                                      const char *csStart,
8259                                                      unsigned csLen) {
8260   bool keepGoing = true;
8261   if (argIndex < NumDataArgs) {
8262     // Consider the argument coverered, even though the specifier doesn't
8263     // make sense.
8264     CoveredArgs.set(argIndex);
8265   }
8266   else {
8267     // If argIndex exceeds the number of data arguments we
8268     // don't issue a warning because that is just a cascade of warnings (and
8269     // they may have intended '%%' anyway). We don't want to continue processing
8270     // the format string after this point, however, as we will like just get
8271     // gibberish when trying to match arguments.
8272     keepGoing = false;
8273   }
8274 
8275   StringRef Specifier(csStart, csLen);
8276 
8277   // If the specifier in non-printable, it could be the first byte of a UTF-8
8278   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8279   // hex value.
8280   std::string CodePointStr;
8281   if (!llvm::sys::locale::isPrint(*csStart)) {
8282     llvm::UTF32 CodePoint;
8283     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8284     const llvm::UTF8 *E =
8285         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8286     llvm::ConversionResult Result =
8287         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8288 
8289     if (Result != llvm::conversionOK) {
8290       unsigned char FirstChar = *csStart;
8291       CodePoint = (llvm::UTF32)FirstChar;
8292     }
8293 
8294     llvm::raw_string_ostream OS(CodePointStr);
8295     if (CodePoint < 256)
8296       OS << "\\x" << llvm::format("%02x", CodePoint);
8297     else if (CodePoint <= 0xFFFF)
8298       OS << "\\u" << llvm::format("%04x", CodePoint);
8299     else
8300       OS << "\\U" << llvm::format("%08x", CodePoint);
8301     OS.flush();
8302     Specifier = CodePointStr;
8303   }
8304 
8305   EmitFormatDiagnostic(
8306       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8307       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8308 
8309   return keepGoing;
8310 }
8311 
8312 void
8313 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8314                                                       const char *startSpec,
8315                                                       unsigned specifierLen) {
8316   EmitFormatDiagnostic(
8317     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8318     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8319 }
8320 
8321 bool
8322 CheckFormatHandler::CheckNumArgs(
8323   const analyze_format_string::FormatSpecifier &FS,
8324   const analyze_format_string::ConversionSpecifier &CS,
8325   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8326 
8327   if (argIndex >= NumDataArgs) {
8328     PartialDiagnostic PDiag = FS.usesPositionalArg()
8329       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8330            << (argIndex+1) << NumDataArgs)
8331       : S.PDiag(diag::warn_printf_insufficient_data_args);
8332     EmitFormatDiagnostic(
8333       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8334       getSpecifierRange(startSpecifier, specifierLen));
8335 
8336     // Since more arguments than conversion tokens are given, by extension
8337     // all arguments are covered, so mark this as so.
8338     UncoveredArg.setAllCovered();
8339     return false;
8340   }
8341   return true;
8342 }
8343 
8344 template<typename Range>
8345 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8346                                               SourceLocation Loc,
8347                                               bool IsStringLocation,
8348                                               Range StringRange,
8349                                               ArrayRef<FixItHint> FixIt) {
8350   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8351                        Loc, IsStringLocation, StringRange, FixIt);
8352 }
8353 
8354 /// If the format string is not within the function call, emit a note
8355 /// so that the function call and string are in diagnostic messages.
8356 ///
8357 /// \param InFunctionCall if true, the format string is within the function
8358 /// call and only one diagnostic message will be produced.  Otherwise, an
8359 /// extra note will be emitted pointing to location of the format string.
8360 ///
8361 /// \param ArgumentExpr the expression that is passed as the format string
8362 /// argument in the function call.  Used for getting locations when two
8363 /// diagnostics are emitted.
8364 ///
8365 /// \param PDiag the callee should already have provided any strings for the
8366 /// diagnostic message.  This function only adds locations and fixits
8367 /// to diagnostics.
8368 ///
8369 /// \param Loc primary location for diagnostic.  If two diagnostics are
8370 /// required, one will be at Loc and a new SourceLocation will be created for
8371 /// the other one.
8372 ///
8373 /// \param IsStringLocation if true, Loc points to the format string should be
8374 /// used for the note.  Otherwise, Loc points to the argument list and will
8375 /// be used with PDiag.
8376 ///
8377 /// \param StringRange some or all of the string to highlight.  This is
8378 /// templated so it can accept either a CharSourceRange or a SourceRange.
8379 ///
8380 /// \param FixIt optional fix it hint for the format string.
8381 template <typename Range>
8382 void CheckFormatHandler::EmitFormatDiagnostic(
8383     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8384     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8385     Range StringRange, ArrayRef<FixItHint> FixIt) {
8386   if (InFunctionCall) {
8387     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8388     D << StringRange;
8389     D << FixIt;
8390   } else {
8391     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8392       << ArgumentExpr->getSourceRange();
8393 
8394     const Sema::SemaDiagnosticBuilder &Note =
8395       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8396              diag::note_format_string_defined);
8397 
8398     Note << StringRange;
8399     Note << FixIt;
8400   }
8401 }
8402 
8403 //===--- CHECK: Printf format string checking ------------------------------===//
8404 
8405 namespace {
8406 
8407 class CheckPrintfHandler : public CheckFormatHandler {
8408 public:
8409   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8410                      const Expr *origFormatExpr,
8411                      const Sema::FormatStringType type, unsigned firstDataArg,
8412                      unsigned numDataArgs, bool isObjC, const char *beg,
8413                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8414                      unsigned formatIdx, bool inFunctionCall,
8415                      Sema::VariadicCallType CallType,
8416                      llvm::SmallBitVector &CheckedVarArgs,
8417                      UncoveredArgHandler &UncoveredArg)
8418       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8419                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8420                            inFunctionCall, CallType, CheckedVarArgs,
8421                            UncoveredArg) {}
8422 
8423   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8424 
8425   /// Returns true if '%@' specifiers are allowed in the format string.
8426   bool allowsObjCArg() const {
8427     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8428            FSType == Sema::FST_OSTrace;
8429   }
8430 
8431   bool HandleInvalidPrintfConversionSpecifier(
8432                                       const analyze_printf::PrintfSpecifier &FS,
8433                                       const char *startSpecifier,
8434                                       unsigned specifierLen) override;
8435 
8436   void handleInvalidMaskType(StringRef MaskType) override;
8437 
8438   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8439                              const char *startSpecifier,
8440                              unsigned specifierLen) override;
8441   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8442                        const char *StartSpecifier,
8443                        unsigned SpecifierLen,
8444                        const Expr *E);
8445 
8446   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8447                     const char *startSpecifier, unsigned specifierLen);
8448   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8449                            const analyze_printf::OptionalAmount &Amt,
8450                            unsigned type,
8451                            const char *startSpecifier, unsigned specifierLen);
8452   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8453                   const analyze_printf::OptionalFlag &flag,
8454                   const char *startSpecifier, unsigned specifierLen);
8455   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8456                          const analyze_printf::OptionalFlag &ignoredFlag,
8457                          const analyze_printf::OptionalFlag &flag,
8458                          const char *startSpecifier, unsigned specifierLen);
8459   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8460                            const Expr *E);
8461 
8462   void HandleEmptyObjCModifierFlag(const char *startFlag,
8463                                    unsigned flagLen) override;
8464 
8465   void HandleInvalidObjCModifierFlag(const char *startFlag,
8466                                             unsigned flagLen) override;
8467 
8468   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8469                                            const char *flagsEnd,
8470                                            const char *conversionPosition)
8471                                              override;
8472 };
8473 
8474 } // namespace
8475 
8476 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8477                                       const analyze_printf::PrintfSpecifier &FS,
8478                                       const char *startSpecifier,
8479                                       unsigned specifierLen) {
8480   const analyze_printf::PrintfConversionSpecifier &CS =
8481     FS.getConversionSpecifier();
8482 
8483   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8484                                           getLocationOfByte(CS.getStart()),
8485                                           startSpecifier, specifierLen,
8486                                           CS.getStart(), CS.getLength());
8487 }
8488 
8489 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8490   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8491 }
8492 
8493 bool CheckPrintfHandler::HandleAmount(
8494                                const analyze_format_string::OptionalAmount &Amt,
8495                                unsigned k, const char *startSpecifier,
8496                                unsigned specifierLen) {
8497   if (Amt.hasDataArgument()) {
8498     if (!HasVAListArg) {
8499       unsigned argIndex = Amt.getArgIndex();
8500       if (argIndex >= NumDataArgs) {
8501         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8502                                << k,
8503                              getLocationOfByte(Amt.getStart()),
8504                              /*IsStringLocation*/true,
8505                              getSpecifierRange(startSpecifier, specifierLen));
8506         // Don't do any more checking.  We will just emit
8507         // spurious errors.
8508         return false;
8509       }
8510 
8511       // Type check the data argument.  It should be an 'int'.
8512       // Although not in conformance with C99, we also allow the argument to be
8513       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8514       // doesn't emit a warning for that case.
8515       CoveredArgs.set(argIndex);
8516       const Expr *Arg = getDataArg(argIndex);
8517       if (!Arg)
8518         return false;
8519 
8520       QualType T = Arg->getType();
8521 
8522       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8523       assert(AT.isValid());
8524 
8525       if (!AT.matchesType(S.Context, T)) {
8526         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8527                                << k << AT.getRepresentativeTypeName(S.Context)
8528                                << T << Arg->getSourceRange(),
8529                              getLocationOfByte(Amt.getStart()),
8530                              /*IsStringLocation*/true,
8531                              getSpecifierRange(startSpecifier, specifierLen));
8532         // Don't do any more checking.  We will just emit
8533         // spurious errors.
8534         return false;
8535       }
8536     }
8537   }
8538   return true;
8539 }
8540 
8541 void CheckPrintfHandler::HandleInvalidAmount(
8542                                       const analyze_printf::PrintfSpecifier &FS,
8543                                       const analyze_printf::OptionalAmount &Amt,
8544                                       unsigned type,
8545                                       const char *startSpecifier,
8546                                       unsigned specifierLen) {
8547   const analyze_printf::PrintfConversionSpecifier &CS =
8548     FS.getConversionSpecifier();
8549 
8550   FixItHint fixit =
8551     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8552       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8553                                  Amt.getConstantLength()))
8554       : FixItHint();
8555 
8556   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8557                          << type << CS.toString(),
8558                        getLocationOfByte(Amt.getStart()),
8559                        /*IsStringLocation*/true,
8560                        getSpecifierRange(startSpecifier, specifierLen),
8561                        fixit);
8562 }
8563 
8564 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8565                                     const analyze_printf::OptionalFlag &flag,
8566                                     const char *startSpecifier,
8567                                     unsigned specifierLen) {
8568   // Warn about pointless flag with a fixit removal.
8569   const analyze_printf::PrintfConversionSpecifier &CS =
8570     FS.getConversionSpecifier();
8571   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8572                          << flag.toString() << CS.toString(),
8573                        getLocationOfByte(flag.getPosition()),
8574                        /*IsStringLocation*/true,
8575                        getSpecifierRange(startSpecifier, specifierLen),
8576                        FixItHint::CreateRemoval(
8577                          getSpecifierRange(flag.getPosition(), 1)));
8578 }
8579 
8580 void CheckPrintfHandler::HandleIgnoredFlag(
8581                                 const analyze_printf::PrintfSpecifier &FS,
8582                                 const analyze_printf::OptionalFlag &ignoredFlag,
8583                                 const analyze_printf::OptionalFlag &flag,
8584                                 const char *startSpecifier,
8585                                 unsigned specifierLen) {
8586   // Warn about ignored flag with a fixit removal.
8587   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8588                          << ignoredFlag.toString() << flag.toString(),
8589                        getLocationOfByte(ignoredFlag.getPosition()),
8590                        /*IsStringLocation*/true,
8591                        getSpecifierRange(startSpecifier, specifierLen),
8592                        FixItHint::CreateRemoval(
8593                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8594 }
8595 
8596 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8597                                                      unsigned flagLen) {
8598   // Warn about an empty flag.
8599   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8600                        getLocationOfByte(startFlag),
8601                        /*IsStringLocation*/true,
8602                        getSpecifierRange(startFlag, flagLen));
8603 }
8604 
8605 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8606                                                        unsigned flagLen) {
8607   // Warn about an invalid flag.
8608   auto Range = getSpecifierRange(startFlag, flagLen);
8609   StringRef flag(startFlag, flagLen);
8610   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8611                       getLocationOfByte(startFlag),
8612                       /*IsStringLocation*/true,
8613                       Range, FixItHint::CreateRemoval(Range));
8614 }
8615 
8616 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8617     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8618     // Warn about using '[...]' without a '@' conversion.
8619     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8620     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8621     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8622                          getLocationOfByte(conversionPosition),
8623                          /*IsStringLocation*/true,
8624                          Range, FixItHint::CreateRemoval(Range));
8625 }
8626 
8627 // Determines if the specified is a C++ class or struct containing
8628 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8629 // "c_str()").
8630 template<typename MemberKind>
8631 static llvm::SmallPtrSet<MemberKind*, 1>
8632 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8633   const RecordType *RT = Ty->getAs<RecordType>();
8634   llvm::SmallPtrSet<MemberKind*, 1> Results;
8635 
8636   if (!RT)
8637     return Results;
8638   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8639   if (!RD || !RD->getDefinition())
8640     return Results;
8641 
8642   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8643                  Sema::LookupMemberName);
8644   R.suppressDiagnostics();
8645 
8646   // We just need to include all members of the right kind turned up by the
8647   // filter, at this point.
8648   if (S.LookupQualifiedName(R, RT->getDecl()))
8649     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8650       NamedDecl *decl = (*I)->getUnderlyingDecl();
8651       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8652         Results.insert(FK);
8653     }
8654   return Results;
8655 }
8656 
8657 /// Check if we could call '.c_str()' on an object.
8658 ///
8659 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8660 /// allow the call, or if it would be ambiguous).
8661 bool Sema::hasCStrMethod(const Expr *E) {
8662   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8663 
8664   MethodSet Results =
8665       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8666   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8667        MI != ME; ++MI)
8668     if ((*MI)->getMinRequiredArguments() == 0)
8669       return true;
8670   return false;
8671 }
8672 
8673 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8674 // better diagnostic if so. AT is assumed to be valid.
8675 // Returns true when a c_str() conversion method is found.
8676 bool CheckPrintfHandler::checkForCStrMembers(
8677     const analyze_printf::ArgType &AT, const Expr *E) {
8678   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8679 
8680   MethodSet Results =
8681       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8682 
8683   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8684        MI != ME; ++MI) {
8685     const CXXMethodDecl *Method = *MI;
8686     if (Method->getMinRequiredArguments() == 0 &&
8687         AT.matchesType(S.Context, Method->getReturnType())) {
8688       // FIXME: Suggest parens if the expression needs them.
8689       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8690       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8691           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8692       return true;
8693     }
8694   }
8695 
8696   return false;
8697 }
8698 
8699 bool
8700 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8701                                             &FS,
8702                                           const char *startSpecifier,
8703                                           unsigned specifierLen) {
8704   using namespace analyze_format_string;
8705   using namespace analyze_printf;
8706 
8707   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8708 
8709   if (FS.consumesDataArgument()) {
8710     if (atFirstArg) {
8711         atFirstArg = false;
8712         usesPositionalArgs = FS.usesPositionalArg();
8713     }
8714     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8715       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8716                                         startSpecifier, specifierLen);
8717       return false;
8718     }
8719   }
8720 
8721   // First check if the field width, precision, and conversion specifier
8722   // have matching data arguments.
8723   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8724                     startSpecifier, specifierLen)) {
8725     return false;
8726   }
8727 
8728   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8729                     startSpecifier, specifierLen)) {
8730     return false;
8731   }
8732 
8733   if (!CS.consumesDataArgument()) {
8734     // FIXME: Technically specifying a precision or field width here
8735     // makes no sense.  Worth issuing a warning at some point.
8736     return true;
8737   }
8738 
8739   // Consume the argument.
8740   unsigned argIndex = FS.getArgIndex();
8741   if (argIndex < NumDataArgs) {
8742     // The check to see if the argIndex is valid will come later.
8743     // We set the bit here because we may exit early from this
8744     // function if we encounter some other error.
8745     CoveredArgs.set(argIndex);
8746   }
8747 
8748   // FreeBSD kernel extensions.
8749   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8750       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8751     // We need at least two arguments.
8752     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8753       return false;
8754 
8755     // Claim the second argument.
8756     CoveredArgs.set(argIndex + 1);
8757 
8758     // Type check the first argument (int for %b, pointer for %D)
8759     const Expr *Ex = getDataArg(argIndex);
8760     const analyze_printf::ArgType &AT =
8761       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8762         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8763     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8764       EmitFormatDiagnostic(
8765           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8766               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8767               << false << Ex->getSourceRange(),
8768           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8769           getSpecifierRange(startSpecifier, specifierLen));
8770 
8771     // Type check the second argument (char * for both %b and %D)
8772     Ex = getDataArg(argIndex + 1);
8773     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8774     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8775       EmitFormatDiagnostic(
8776           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8777               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8778               << false << Ex->getSourceRange(),
8779           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8780           getSpecifierRange(startSpecifier, specifierLen));
8781 
8782      return true;
8783   }
8784 
8785   // Check for using an Objective-C specific conversion specifier
8786   // in a non-ObjC literal.
8787   if (!allowsObjCArg() && CS.isObjCArg()) {
8788     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8789                                                   specifierLen);
8790   }
8791 
8792   // %P can only be used with os_log.
8793   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8794     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8795                                                   specifierLen);
8796   }
8797 
8798   // %n is not allowed with os_log.
8799   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8800     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8801                          getLocationOfByte(CS.getStart()),
8802                          /*IsStringLocation*/ false,
8803                          getSpecifierRange(startSpecifier, specifierLen));
8804 
8805     return true;
8806   }
8807 
8808   // Only scalars are allowed for os_trace.
8809   if (FSType == Sema::FST_OSTrace &&
8810       (CS.getKind() == ConversionSpecifier::PArg ||
8811        CS.getKind() == ConversionSpecifier::sArg ||
8812        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8813     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8814                                                   specifierLen);
8815   }
8816 
8817   // Check for use of public/private annotation outside of os_log().
8818   if (FSType != Sema::FST_OSLog) {
8819     if (FS.isPublic().isSet()) {
8820       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8821                                << "public",
8822                            getLocationOfByte(FS.isPublic().getPosition()),
8823                            /*IsStringLocation*/ false,
8824                            getSpecifierRange(startSpecifier, specifierLen));
8825     }
8826     if (FS.isPrivate().isSet()) {
8827       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8828                                << "private",
8829                            getLocationOfByte(FS.isPrivate().getPosition()),
8830                            /*IsStringLocation*/ false,
8831                            getSpecifierRange(startSpecifier, specifierLen));
8832     }
8833   }
8834 
8835   // Check for invalid use of field width
8836   if (!FS.hasValidFieldWidth()) {
8837     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8838         startSpecifier, specifierLen);
8839   }
8840 
8841   // Check for invalid use of precision
8842   if (!FS.hasValidPrecision()) {
8843     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8844         startSpecifier, specifierLen);
8845   }
8846 
8847   // Precision is mandatory for %P specifier.
8848   if (CS.getKind() == ConversionSpecifier::PArg &&
8849       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8850     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8851                          getLocationOfByte(startSpecifier),
8852                          /*IsStringLocation*/ false,
8853                          getSpecifierRange(startSpecifier, specifierLen));
8854   }
8855 
8856   // Check each flag does not conflict with any other component.
8857   if (!FS.hasValidThousandsGroupingPrefix())
8858     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8859   if (!FS.hasValidLeadingZeros())
8860     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8861   if (!FS.hasValidPlusPrefix())
8862     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8863   if (!FS.hasValidSpacePrefix())
8864     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8865   if (!FS.hasValidAlternativeForm())
8866     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8867   if (!FS.hasValidLeftJustified())
8868     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8869 
8870   // Check that flags are not ignored by another flag
8871   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8872     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8873         startSpecifier, specifierLen);
8874   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8875     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8876             startSpecifier, specifierLen);
8877 
8878   // Check the length modifier is valid with the given conversion specifier.
8879   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8880                                  S.getLangOpts()))
8881     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8882                                 diag::warn_format_nonsensical_length);
8883   else if (!FS.hasStandardLengthModifier())
8884     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8885   else if (!FS.hasStandardLengthConversionCombination())
8886     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8887                                 diag::warn_format_non_standard_conversion_spec);
8888 
8889   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8890     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8891 
8892   // The remaining checks depend on the data arguments.
8893   if (HasVAListArg)
8894     return true;
8895 
8896   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8897     return false;
8898 
8899   const Expr *Arg = getDataArg(argIndex);
8900   if (!Arg)
8901     return true;
8902 
8903   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8904 }
8905 
8906 static bool requiresParensToAddCast(const Expr *E) {
8907   // FIXME: We should have a general way to reason about operator
8908   // precedence and whether parens are actually needed here.
8909   // Take care of a few common cases where they aren't.
8910   const Expr *Inside = E->IgnoreImpCasts();
8911   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8912     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8913 
8914   switch (Inside->getStmtClass()) {
8915   case Stmt::ArraySubscriptExprClass:
8916   case Stmt::CallExprClass:
8917   case Stmt::CharacterLiteralClass:
8918   case Stmt::CXXBoolLiteralExprClass:
8919   case Stmt::DeclRefExprClass:
8920   case Stmt::FloatingLiteralClass:
8921   case Stmt::IntegerLiteralClass:
8922   case Stmt::MemberExprClass:
8923   case Stmt::ObjCArrayLiteralClass:
8924   case Stmt::ObjCBoolLiteralExprClass:
8925   case Stmt::ObjCBoxedExprClass:
8926   case Stmt::ObjCDictionaryLiteralClass:
8927   case Stmt::ObjCEncodeExprClass:
8928   case Stmt::ObjCIvarRefExprClass:
8929   case Stmt::ObjCMessageExprClass:
8930   case Stmt::ObjCPropertyRefExprClass:
8931   case Stmt::ObjCStringLiteralClass:
8932   case Stmt::ObjCSubscriptRefExprClass:
8933   case Stmt::ParenExprClass:
8934   case Stmt::StringLiteralClass:
8935   case Stmt::UnaryOperatorClass:
8936     return false;
8937   default:
8938     return true;
8939   }
8940 }
8941 
8942 static std::pair<QualType, StringRef>
8943 shouldNotPrintDirectly(const ASTContext &Context,
8944                        QualType IntendedTy,
8945                        const Expr *E) {
8946   // Use a 'while' to peel off layers of typedefs.
8947   QualType TyTy = IntendedTy;
8948   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8949     StringRef Name = UserTy->getDecl()->getName();
8950     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8951       .Case("CFIndex", Context.getNSIntegerType())
8952       .Case("NSInteger", Context.getNSIntegerType())
8953       .Case("NSUInteger", Context.getNSUIntegerType())
8954       .Case("SInt32", Context.IntTy)
8955       .Case("UInt32", Context.UnsignedIntTy)
8956       .Default(QualType());
8957 
8958     if (!CastTy.isNull())
8959       return std::make_pair(CastTy, Name);
8960 
8961     TyTy = UserTy->desugar();
8962   }
8963 
8964   // Strip parens if necessary.
8965   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8966     return shouldNotPrintDirectly(Context,
8967                                   PE->getSubExpr()->getType(),
8968                                   PE->getSubExpr());
8969 
8970   // If this is a conditional expression, then its result type is constructed
8971   // via usual arithmetic conversions and thus there might be no necessary
8972   // typedef sugar there.  Recurse to operands to check for NSInteger &
8973   // Co. usage condition.
8974   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8975     QualType TrueTy, FalseTy;
8976     StringRef TrueName, FalseName;
8977 
8978     std::tie(TrueTy, TrueName) =
8979       shouldNotPrintDirectly(Context,
8980                              CO->getTrueExpr()->getType(),
8981                              CO->getTrueExpr());
8982     std::tie(FalseTy, FalseName) =
8983       shouldNotPrintDirectly(Context,
8984                              CO->getFalseExpr()->getType(),
8985                              CO->getFalseExpr());
8986 
8987     if (TrueTy == FalseTy)
8988       return std::make_pair(TrueTy, TrueName);
8989     else if (TrueTy.isNull())
8990       return std::make_pair(FalseTy, FalseName);
8991     else if (FalseTy.isNull())
8992       return std::make_pair(TrueTy, TrueName);
8993   }
8994 
8995   return std::make_pair(QualType(), StringRef());
8996 }
8997 
8998 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8999 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9000 /// type do not count.
9001 static bool
9002 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9003   QualType From = ICE->getSubExpr()->getType();
9004   QualType To = ICE->getType();
9005   // It's an integer promotion if the destination type is the promoted
9006   // source type.
9007   if (ICE->getCastKind() == CK_IntegralCast &&
9008       From->isPromotableIntegerType() &&
9009       S.Context.getPromotedIntegerType(From) == To)
9010     return true;
9011   // Look through vector types, since we do default argument promotion for
9012   // those in OpenCL.
9013   if (const auto *VecTy = From->getAs<ExtVectorType>())
9014     From = VecTy->getElementType();
9015   if (const auto *VecTy = To->getAs<ExtVectorType>())
9016     To = VecTy->getElementType();
9017   // It's a floating promotion if the source type is a lower rank.
9018   return ICE->getCastKind() == CK_FloatingCast &&
9019          S.Context.getFloatingTypeOrder(From, To) < 0;
9020 }
9021 
9022 bool
9023 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9024                                     const char *StartSpecifier,
9025                                     unsigned SpecifierLen,
9026                                     const Expr *E) {
9027   using namespace analyze_format_string;
9028   using namespace analyze_printf;
9029 
9030   // Now type check the data expression that matches the
9031   // format specifier.
9032   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9033   if (!AT.isValid())
9034     return true;
9035 
9036   QualType ExprTy = E->getType();
9037   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9038     ExprTy = TET->getUnderlyingExpr()->getType();
9039   }
9040 
9041   // Diagnose attempts to print a boolean value as a character. Unlike other
9042   // -Wformat diagnostics, this is fine from a type perspective, but it still
9043   // doesn't make sense.
9044   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9045       E->isKnownToHaveBooleanValue()) {
9046     const CharSourceRange &CSR =
9047         getSpecifierRange(StartSpecifier, SpecifierLen);
9048     SmallString<4> FSString;
9049     llvm::raw_svector_ostream os(FSString);
9050     FS.toString(os);
9051     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9052                              << FSString,
9053                          E->getExprLoc(), false, CSR);
9054     return true;
9055   }
9056 
9057   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9058   if (Match == analyze_printf::ArgType::Match)
9059     return true;
9060 
9061   // Look through argument promotions for our error message's reported type.
9062   // This includes the integral and floating promotions, but excludes array
9063   // and function pointer decay (seeing that an argument intended to be a
9064   // string has type 'char [6]' is probably more confusing than 'char *') and
9065   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9066   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9067     if (isArithmeticArgumentPromotion(S, ICE)) {
9068       E = ICE->getSubExpr();
9069       ExprTy = E->getType();
9070 
9071       // Check if we didn't match because of an implicit cast from a 'char'
9072       // or 'short' to an 'int'.  This is done because printf is a varargs
9073       // function.
9074       if (ICE->getType() == S.Context.IntTy ||
9075           ICE->getType() == S.Context.UnsignedIntTy) {
9076         // All further checking is done on the subexpression
9077         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9078             AT.matchesType(S.Context, ExprTy);
9079         if (ImplicitMatch == analyze_printf::ArgType::Match)
9080           return true;
9081         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9082             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9083           Match = ImplicitMatch;
9084       }
9085     }
9086   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9087     // Special case for 'a', which has type 'int' in C.
9088     // Note, however, that we do /not/ want to treat multibyte constants like
9089     // 'MooV' as characters! This form is deprecated but still exists. In
9090     // addition, don't treat expressions as of type 'char' if one byte length
9091     // modifier is provided.
9092     if (ExprTy == S.Context.IntTy &&
9093         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9094       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9095         ExprTy = S.Context.CharTy;
9096   }
9097 
9098   // Look through enums to their underlying type.
9099   bool IsEnum = false;
9100   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9101     ExprTy = EnumTy->getDecl()->getIntegerType();
9102     IsEnum = true;
9103   }
9104 
9105   // %C in an Objective-C context prints a unichar, not a wchar_t.
9106   // If the argument is an integer of some kind, believe the %C and suggest
9107   // a cast instead of changing the conversion specifier.
9108   QualType IntendedTy = ExprTy;
9109   if (isObjCContext() &&
9110       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9111     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9112         !ExprTy->isCharType()) {
9113       // 'unichar' is defined as a typedef of unsigned short, but we should
9114       // prefer using the typedef if it is visible.
9115       IntendedTy = S.Context.UnsignedShortTy;
9116 
9117       // While we are here, check if the value is an IntegerLiteral that happens
9118       // to be within the valid range.
9119       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9120         const llvm::APInt &V = IL->getValue();
9121         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9122           return true;
9123       }
9124 
9125       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9126                           Sema::LookupOrdinaryName);
9127       if (S.LookupName(Result, S.getCurScope())) {
9128         NamedDecl *ND = Result.getFoundDecl();
9129         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9130           if (TD->getUnderlyingType() == IntendedTy)
9131             IntendedTy = S.Context.getTypedefType(TD);
9132       }
9133     }
9134   }
9135 
9136   // Special-case some of Darwin's platform-independence types by suggesting
9137   // casts to primitive types that are known to be large enough.
9138   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9139   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9140     QualType CastTy;
9141     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9142     if (!CastTy.isNull()) {
9143       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9144       // (long in ASTContext). Only complain to pedants.
9145       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9146           (AT.isSizeT() || AT.isPtrdiffT()) &&
9147           AT.matchesType(S.Context, CastTy))
9148         Match = ArgType::NoMatchPedantic;
9149       IntendedTy = CastTy;
9150       ShouldNotPrintDirectly = true;
9151     }
9152   }
9153 
9154   // We may be able to offer a FixItHint if it is a supported type.
9155   PrintfSpecifier fixedFS = FS;
9156   bool Success =
9157       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9158 
9159   if (Success) {
9160     // Get the fix string from the fixed format specifier
9161     SmallString<16> buf;
9162     llvm::raw_svector_ostream os(buf);
9163     fixedFS.toString(os);
9164 
9165     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9166 
9167     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9168       unsigned Diag;
9169       switch (Match) {
9170       case ArgType::Match: llvm_unreachable("expected non-matching");
9171       case ArgType::NoMatchPedantic:
9172         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9173         break;
9174       case ArgType::NoMatchTypeConfusion:
9175         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9176         break;
9177       case ArgType::NoMatch:
9178         Diag = diag::warn_format_conversion_argument_type_mismatch;
9179         break;
9180       }
9181 
9182       // In this case, the specifier is wrong and should be changed to match
9183       // the argument.
9184       EmitFormatDiagnostic(S.PDiag(Diag)
9185                                << AT.getRepresentativeTypeName(S.Context)
9186                                << IntendedTy << IsEnum << E->getSourceRange(),
9187                            E->getBeginLoc(),
9188                            /*IsStringLocation*/ false, SpecRange,
9189                            FixItHint::CreateReplacement(SpecRange, os.str()));
9190     } else {
9191       // The canonical type for formatting this value is different from the
9192       // actual type of the expression. (This occurs, for example, with Darwin's
9193       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9194       // should be printed as 'long' for 64-bit compatibility.)
9195       // Rather than emitting a normal format/argument mismatch, we want to
9196       // add a cast to the recommended type (and correct the format string
9197       // if necessary).
9198       SmallString<16> CastBuf;
9199       llvm::raw_svector_ostream CastFix(CastBuf);
9200       CastFix << "(";
9201       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9202       CastFix << ")";
9203 
9204       SmallVector<FixItHint,4> Hints;
9205       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9206         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9207 
9208       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9209         // If there's already a cast present, just replace it.
9210         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9211         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9212 
9213       } else if (!requiresParensToAddCast(E)) {
9214         // If the expression has high enough precedence,
9215         // just write the C-style cast.
9216         Hints.push_back(
9217             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9218       } else {
9219         // Otherwise, add parens around the expression as well as the cast.
9220         CastFix << "(";
9221         Hints.push_back(
9222             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9223 
9224         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9225         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9226       }
9227 
9228       if (ShouldNotPrintDirectly) {
9229         // The expression has a type that should not be printed directly.
9230         // We extract the name from the typedef because we don't want to show
9231         // the underlying type in the diagnostic.
9232         StringRef Name;
9233         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9234           Name = TypedefTy->getDecl()->getName();
9235         else
9236           Name = CastTyName;
9237         unsigned Diag = Match == ArgType::NoMatchPedantic
9238                             ? diag::warn_format_argument_needs_cast_pedantic
9239                             : diag::warn_format_argument_needs_cast;
9240         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9241                                            << E->getSourceRange(),
9242                              E->getBeginLoc(), /*IsStringLocation=*/false,
9243                              SpecRange, Hints);
9244       } else {
9245         // In this case, the expression could be printed using a different
9246         // specifier, but we've decided that the specifier is probably correct
9247         // and we should cast instead. Just use the normal warning message.
9248         EmitFormatDiagnostic(
9249             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9250                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9251                 << E->getSourceRange(),
9252             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9253       }
9254     }
9255   } else {
9256     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9257                                                    SpecifierLen);
9258     // Since the warning for passing non-POD types to variadic functions
9259     // was deferred until now, we emit a warning for non-POD
9260     // arguments here.
9261     switch (S.isValidVarArgType(ExprTy)) {
9262     case Sema::VAK_Valid:
9263     case Sema::VAK_ValidInCXX11: {
9264       unsigned Diag;
9265       switch (Match) {
9266       case ArgType::Match: llvm_unreachable("expected non-matching");
9267       case ArgType::NoMatchPedantic:
9268         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9269         break;
9270       case ArgType::NoMatchTypeConfusion:
9271         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9272         break;
9273       case ArgType::NoMatch:
9274         Diag = diag::warn_format_conversion_argument_type_mismatch;
9275         break;
9276       }
9277 
9278       EmitFormatDiagnostic(
9279           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9280                         << IsEnum << CSR << E->getSourceRange(),
9281           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9282       break;
9283     }
9284     case Sema::VAK_Undefined:
9285     case Sema::VAK_MSVCUndefined:
9286       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9287                                << S.getLangOpts().CPlusPlus11 << ExprTy
9288                                << CallType
9289                                << AT.getRepresentativeTypeName(S.Context) << CSR
9290                                << E->getSourceRange(),
9291                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9292       checkForCStrMembers(AT, E);
9293       break;
9294 
9295     case Sema::VAK_Invalid:
9296       if (ExprTy->isObjCObjectType())
9297         EmitFormatDiagnostic(
9298             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9299                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9300                 << AT.getRepresentativeTypeName(S.Context) << CSR
9301                 << E->getSourceRange(),
9302             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9303       else
9304         // FIXME: If this is an initializer list, suggest removing the braces
9305         // or inserting a cast to the target type.
9306         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9307             << isa<InitListExpr>(E) << ExprTy << CallType
9308             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9309       break;
9310     }
9311 
9312     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9313            "format string specifier index out of range");
9314     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9315   }
9316 
9317   return true;
9318 }
9319 
9320 //===--- CHECK: Scanf format string checking ------------------------------===//
9321 
9322 namespace {
9323 
9324 class CheckScanfHandler : public CheckFormatHandler {
9325 public:
9326   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9327                     const Expr *origFormatExpr, Sema::FormatStringType type,
9328                     unsigned firstDataArg, unsigned numDataArgs,
9329                     const char *beg, bool hasVAListArg,
9330                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9331                     bool inFunctionCall, Sema::VariadicCallType CallType,
9332                     llvm::SmallBitVector &CheckedVarArgs,
9333                     UncoveredArgHandler &UncoveredArg)
9334       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9335                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9336                            inFunctionCall, CallType, CheckedVarArgs,
9337                            UncoveredArg) {}
9338 
9339   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9340                             const char *startSpecifier,
9341                             unsigned specifierLen) override;
9342 
9343   bool HandleInvalidScanfConversionSpecifier(
9344           const analyze_scanf::ScanfSpecifier &FS,
9345           const char *startSpecifier,
9346           unsigned specifierLen) override;
9347 
9348   void HandleIncompleteScanList(const char *start, const char *end) override;
9349 };
9350 
9351 } // namespace
9352 
9353 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9354                                                  const char *end) {
9355   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9356                        getLocationOfByte(end), /*IsStringLocation*/true,
9357                        getSpecifierRange(start, end - start));
9358 }
9359 
9360 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9361                                         const analyze_scanf::ScanfSpecifier &FS,
9362                                         const char *startSpecifier,
9363                                         unsigned specifierLen) {
9364   const analyze_scanf::ScanfConversionSpecifier &CS =
9365     FS.getConversionSpecifier();
9366 
9367   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9368                                           getLocationOfByte(CS.getStart()),
9369                                           startSpecifier, specifierLen,
9370                                           CS.getStart(), CS.getLength());
9371 }
9372 
9373 bool CheckScanfHandler::HandleScanfSpecifier(
9374                                        const analyze_scanf::ScanfSpecifier &FS,
9375                                        const char *startSpecifier,
9376                                        unsigned specifierLen) {
9377   using namespace analyze_scanf;
9378   using namespace analyze_format_string;
9379 
9380   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9381 
9382   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9383   // be used to decide if we are using positional arguments consistently.
9384   if (FS.consumesDataArgument()) {
9385     if (atFirstArg) {
9386       atFirstArg = false;
9387       usesPositionalArgs = FS.usesPositionalArg();
9388     }
9389     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9390       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9391                                         startSpecifier, specifierLen);
9392       return false;
9393     }
9394   }
9395 
9396   // Check if the field with is non-zero.
9397   const OptionalAmount &Amt = FS.getFieldWidth();
9398   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9399     if (Amt.getConstantAmount() == 0) {
9400       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9401                                                    Amt.getConstantLength());
9402       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9403                            getLocationOfByte(Amt.getStart()),
9404                            /*IsStringLocation*/true, R,
9405                            FixItHint::CreateRemoval(R));
9406     }
9407   }
9408 
9409   if (!FS.consumesDataArgument()) {
9410     // FIXME: Technically specifying a precision or field width here
9411     // makes no sense.  Worth issuing a warning at some point.
9412     return true;
9413   }
9414 
9415   // Consume the argument.
9416   unsigned argIndex = FS.getArgIndex();
9417   if (argIndex < NumDataArgs) {
9418       // The check to see if the argIndex is valid will come later.
9419       // We set the bit here because we may exit early from this
9420       // function if we encounter some other error.
9421     CoveredArgs.set(argIndex);
9422   }
9423 
9424   // Check the length modifier is valid with the given conversion specifier.
9425   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9426                                  S.getLangOpts()))
9427     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9428                                 diag::warn_format_nonsensical_length);
9429   else if (!FS.hasStandardLengthModifier())
9430     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9431   else if (!FS.hasStandardLengthConversionCombination())
9432     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9433                                 diag::warn_format_non_standard_conversion_spec);
9434 
9435   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9436     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9437 
9438   // The remaining checks depend on the data arguments.
9439   if (HasVAListArg)
9440     return true;
9441 
9442   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9443     return false;
9444 
9445   // Check that the argument type matches the format specifier.
9446   const Expr *Ex = getDataArg(argIndex);
9447   if (!Ex)
9448     return true;
9449 
9450   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9451 
9452   if (!AT.isValid()) {
9453     return true;
9454   }
9455 
9456   analyze_format_string::ArgType::MatchKind Match =
9457       AT.matchesType(S.Context, Ex->getType());
9458   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9459   if (Match == analyze_format_string::ArgType::Match)
9460     return true;
9461 
9462   ScanfSpecifier fixedFS = FS;
9463   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9464                                  S.getLangOpts(), S.Context);
9465 
9466   unsigned Diag =
9467       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9468                : diag::warn_format_conversion_argument_type_mismatch;
9469 
9470   if (Success) {
9471     // Get the fix string from the fixed format specifier.
9472     SmallString<128> buf;
9473     llvm::raw_svector_ostream os(buf);
9474     fixedFS.toString(os);
9475 
9476     EmitFormatDiagnostic(
9477         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9478                       << Ex->getType() << false << Ex->getSourceRange(),
9479         Ex->getBeginLoc(),
9480         /*IsStringLocation*/ false,
9481         getSpecifierRange(startSpecifier, specifierLen),
9482         FixItHint::CreateReplacement(
9483             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9484   } else {
9485     EmitFormatDiagnostic(S.PDiag(Diag)
9486                              << AT.getRepresentativeTypeName(S.Context)
9487                              << Ex->getType() << false << Ex->getSourceRange(),
9488                          Ex->getBeginLoc(),
9489                          /*IsStringLocation*/ false,
9490                          getSpecifierRange(startSpecifier, specifierLen));
9491   }
9492 
9493   return true;
9494 }
9495 
9496 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9497                               const Expr *OrigFormatExpr,
9498                               ArrayRef<const Expr *> Args,
9499                               bool HasVAListArg, unsigned format_idx,
9500                               unsigned firstDataArg,
9501                               Sema::FormatStringType Type,
9502                               bool inFunctionCall,
9503                               Sema::VariadicCallType CallType,
9504                               llvm::SmallBitVector &CheckedVarArgs,
9505                               UncoveredArgHandler &UncoveredArg,
9506                               bool IgnoreStringsWithoutSpecifiers) {
9507   // CHECK: is the format string a wide literal?
9508   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9509     CheckFormatHandler::EmitFormatDiagnostic(
9510         S, inFunctionCall, Args[format_idx],
9511         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9512         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9513     return;
9514   }
9515 
9516   // Str - The format string.  NOTE: this is NOT null-terminated!
9517   StringRef StrRef = FExpr->getString();
9518   const char *Str = StrRef.data();
9519   // Account for cases where the string literal is truncated in a declaration.
9520   const ConstantArrayType *T =
9521     S.Context.getAsConstantArrayType(FExpr->getType());
9522   assert(T && "String literal not of constant array type!");
9523   size_t TypeSize = T->getSize().getZExtValue();
9524   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9525   const unsigned numDataArgs = Args.size() - firstDataArg;
9526 
9527   if (IgnoreStringsWithoutSpecifiers &&
9528       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9529           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9530     return;
9531 
9532   // Emit a warning if the string literal is truncated and does not contain an
9533   // embedded null character.
9534   if (TypeSize <= StrRef.size() &&
9535       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9536     CheckFormatHandler::EmitFormatDiagnostic(
9537         S, inFunctionCall, Args[format_idx],
9538         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9539         FExpr->getBeginLoc(),
9540         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9541     return;
9542   }
9543 
9544   // CHECK: empty format string?
9545   if (StrLen == 0 && numDataArgs > 0) {
9546     CheckFormatHandler::EmitFormatDiagnostic(
9547         S, inFunctionCall, Args[format_idx],
9548         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9549         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9550     return;
9551   }
9552 
9553   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9554       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9555       Type == Sema::FST_OSTrace) {
9556     CheckPrintfHandler H(
9557         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9558         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9559         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9560         CheckedVarArgs, UncoveredArg);
9561 
9562     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9563                                                   S.getLangOpts(),
9564                                                   S.Context.getTargetInfo(),
9565                                             Type == Sema::FST_FreeBSDKPrintf))
9566       H.DoneProcessing();
9567   } else if (Type == Sema::FST_Scanf) {
9568     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9569                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9570                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9571 
9572     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9573                                                  S.getLangOpts(),
9574                                                  S.Context.getTargetInfo()))
9575       H.DoneProcessing();
9576   } // TODO: handle other formats
9577 }
9578 
9579 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9580   // Str - The format string.  NOTE: this is NOT null-terminated!
9581   StringRef StrRef = FExpr->getString();
9582   const char *Str = StrRef.data();
9583   // Account for cases where the string literal is truncated in a declaration.
9584   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9585   assert(T && "String literal not of constant array type!");
9586   size_t TypeSize = T->getSize().getZExtValue();
9587   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9588   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9589                                                          getLangOpts(),
9590                                                          Context.getTargetInfo());
9591 }
9592 
9593 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9594 
9595 // Returns the related absolute value function that is larger, of 0 if one
9596 // does not exist.
9597 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9598   switch (AbsFunction) {
9599   default:
9600     return 0;
9601 
9602   case Builtin::BI__builtin_abs:
9603     return Builtin::BI__builtin_labs;
9604   case Builtin::BI__builtin_labs:
9605     return Builtin::BI__builtin_llabs;
9606   case Builtin::BI__builtin_llabs:
9607     return 0;
9608 
9609   case Builtin::BI__builtin_fabsf:
9610     return Builtin::BI__builtin_fabs;
9611   case Builtin::BI__builtin_fabs:
9612     return Builtin::BI__builtin_fabsl;
9613   case Builtin::BI__builtin_fabsl:
9614     return 0;
9615 
9616   case Builtin::BI__builtin_cabsf:
9617     return Builtin::BI__builtin_cabs;
9618   case Builtin::BI__builtin_cabs:
9619     return Builtin::BI__builtin_cabsl;
9620   case Builtin::BI__builtin_cabsl:
9621     return 0;
9622 
9623   case Builtin::BIabs:
9624     return Builtin::BIlabs;
9625   case Builtin::BIlabs:
9626     return Builtin::BIllabs;
9627   case Builtin::BIllabs:
9628     return 0;
9629 
9630   case Builtin::BIfabsf:
9631     return Builtin::BIfabs;
9632   case Builtin::BIfabs:
9633     return Builtin::BIfabsl;
9634   case Builtin::BIfabsl:
9635     return 0;
9636 
9637   case Builtin::BIcabsf:
9638    return Builtin::BIcabs;
9639   case Builtin::BIcabs:
9640     return Builtin::BIcabsl;
9641   case Builtin::BIcabsl:
9642     return 0;
9643   }
9644 }
9645 
9646 // Returns the argument type of the absolute value function.
9647 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9648                                              unsigned AbsType) {
9649   if (AbsType == 0)
9650     return QualType();
9651 
9652   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9653   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9654   if (Error != ASTContext::GE_None)
9655     return QualType();
9656 
9657   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9658   if (!FT)
9659     return QualType();
9660 
9661   if (FT->getNumParams() != 1)
9662     return QualType();
9663 
9664   return FT->getParamType(0);
9665 }
9666 
9667 // Returns the best absolute value function, or zero, based on type and
9668 // current absolute value function.
9669 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9670                                    unsigned AbsFunctionKind) {
9671   unsigned BestKind = 0;
9672   uint64_t ArgSize = Context.getTypeSize(ArgType);
9673   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9674        Kind = getLargerAbsoluteValueFunction(Kind)) {
9675     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9676     if (Context.getTypeSize(ParamType) >= ArgSize) {
9677       if (BestKind == 0)
9678         BestKind = Kind;
9679       else if (Context.hasSameType(ParamType, ArgType)) {
9680         BestKind = Kind;
9681         break;
9682       }
9683     }
9684   }
9685   return BestKind;
9686 }
9687 
9688 enum AbsoluteValueKind {
9689   AVK_Integer,
9690   AVK_Floating,
9691   AVK_Complex
9692 };
9693 
9694 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9695   if (T->isIntegralOrEnumerationType())
9696     return AVK_Integer;
9697   if (T->isRealFloatingType())
9698     return AVK_Floating;
9699   if (T->isAnyComplexType())
9700     return AVK_Complex;
9701 
9702   llvm_unreachable("Type not integer, floating, or complex");
9703 }
9704 
9705 // Changes the absolute value function to a different type.  Preserves whether
9706 // the function is a builtin.
9707 static unsigned changeAbsFunction(unsigned AbsKind,
9708                                   AbsoluteValueKind ValueKind) {
9709   switch (ValueKind) {
9710   case AVK_Integer:
9711     switch (AbsKind) {
9712     default:
9713       return 0;
9714     case Builtin::BI__builtin_fabsf:
9715     case Builtin::BI__builtin_fabs:
9716     case Builtin::BI__builtin_fabsl:
9717     case Builtin::BI__builtin_cabsf:
9718     case Builtin::BI__builtin_cabs:
9719     case Builtin::BI__builtin_cabsl:
9720       return Builtin::BI__builtin_abs;
9721     case Builtin::BIfabsf:
9722     case Builtin::BIfabs:
9723     case Builtin::BIfabsl:
9724     case Builtin::BIcabsf:
9725     case Builtin::BIcabs:
9726     case Builtin::BIcabsl:
9727       return Builtin::BIabs;
9728     }
9729   case AVK_Floating:
9730     switch (AbsKind) {
9731     default:
9732       return 0;
9733     case Builtin::BI__builtin_abs:
9734     case Builtin::BI__builtin_labs:
9735     case Builtin::BI__builtin_llabs:
9736     case Builtin::BI__builtin_cabsf:
9737     case Builtin::BI__builtin_cabs:
9738     case Builtin::BI__builtin_cabsl:
9739       return Builtin::BI__builtin_fabsf;
9740     case Builtin::BIabs:
9741     case Builtin::BIlabs:
9742     case Builtin::BIllabs:
9743     case Builtin::BIcabsf:
9744     case Builtin::BIcabs:
9745     case Builtin::BIcabsl:
9746       return Builtin::BIfabsf;
9747     }
9748   case AVK_Complex:
9749     switch (AbsKind) {
9750     default:
9751       return 0;
9752     case Builtin::BI__builtin_abs:
9753     case Builtin::BI__builtin_labs:
9754     case Builtin::BI__builtin_llabs:
9755     case Builtin::BI__builtin_fabsf:
9756     case Builtin::BI__builtin_fabs:
9757     case Builtin::BI__builtin_fabsl:
9758       return Builtin::BI__builtin_cabsf;
9759     case Builtin::BIabs:
9760     case Builtin::BIlabs:
9761     case Builtin::BIllabs:
9762     case Builtin::BIfabsf:
9763     case Builtin::BIfabs:
9764     case Builtin::BIfabsl:
9765       return Builtin::BIcabsf;
9766     }
9767   }
9768   llvm_unreachable("Unable to convert function");
9769 }
9770 
9771 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9772   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9773   if (!FnInfo)
9774     return 0;
9775 
9776   switch (FDecl->getBuiltinID()) {
9777   default:
9778     return 0;
9779   case Builtin::BI__builtin_abs:
9780   case Builtin::BI__builtin_fabs:
9781   case Builtin::BI__builtin_fabsf:
9782   case Builtin::BI__builtin_fabsl:
9783   case Builtin::BI__builtin_labs:
9784   case Builtin::BI__builtin_llabs:
9785   case Builtin::BI__builtin_cabs:
9786   case Builtin::BI__builtin_cabsf:
9787   case Builtin::BI__builtin_cabsl:
9788   case Builtin::BIabs:
9789   case Builtin::BIlabs:
9790   case Builtin::BIllabs:
9791   case Builtin::BIfabs:
9792   case Builtin::BIfabsf:
9793   case Builtin::BIfabsl:
9794   case Builtin::BIcabs:
9795   case Builtin::BIcabsf:
9796   case Builtin::BIcabsl:
9797     return FDecl->getBuiltinID();
9798   }
9799   llvm_unreachable("Unknown Builtin type");
9800 }
9801 
9802 // If the replacement is valid, emit a note with replacement function.
9803 // Additionally, suggest including the proper header if not already included.
9804 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9805                             unsigned AbsKind, QualType ArgType) {
9806   bool EmitHeaderHint = true;
9807   const char *HeaderName = nullptr;
9808   const char *FunctionName = nullptr;
9809   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9810     FunctionName = "std::abs";
9811     if (ArgType->isIntegralOrEnumerationType()) {
9812       HeaderName = "cstdlib";
9813     } else if (ArgType->isRealFloatingType()) {
9814       HeaderName = "cmath";
9815     } else {
9816       llvm_unreachable("Invalid Type");
9817     }
9818 
9819     // Lookup all std::abs
9820     if (NamespaceDecl *Std = S.getStdNamespace()) {
9821       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9822       R.suppressDiagnostics();
9823       S.LookupQualifiedName(R, Std);
9824 
9825       for (const auto *I : R) {
9826         const FunctionDecl *FDecl = nullptr;
9827         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9828           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9829         } else {
9830           FDecl = dyn_cast<FunctionDecl>(I);
9831         }
9832         if (!FDecl)
9833           continue;
9834 
9835         // Found std::abs(), check that they are the right ones.
9836         if (FDecl->getNumParams() != 1)
9837           continue;
9838 
9839         // Check that the parameter type can handle the argument.
9840         QualType ParamType = FDecl->getParamDecl(0)->getType();
9841         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9842             S.Context.getTypeSize(ArgType) <=
9843                 S.Context.getTypeSize(ParamType)) {
9844           // Found a function, don't need the header hint.
9845           EmitHeaderHint = false;
9846           break;
9847         }
9848       }
9849     }
9850   } else {
9851     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9852     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9853 
9854     if (HeaderName) {
9855       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9856       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9857       R.suppressDiagnostics();
9858       S.LookupName(R, S.getCurScope());
9859 
9860       if (R.isSingleResult()) {
9861         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9862         if (FD && FD->getBuiltinID() == AbsKind) {
9863           EmitHeaderHint = false;
9864         } else {
9865           return;
9866         }
9867       } else if (!R.empty()) {
9868         return;
9869       }
9870     }
9871   }
9872 
9873   S.Diag(Loc, diag::note_replace_abs_function)
9874       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9875 
9876   if (!HeaderName)
9877     return;
9878 
9879   if (!EmitHeaderHint)
9880     return;
9881 
9882   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9883                                                     << FunctionName;
9884 }
9885 
9886 template <std::size_t StrLen>
9887 static bool IsStdFunction(const FunctionDecl *FDecl,
9888                           const char (&Str)[StrLen]) {
9889   if (!FDecl)
9890     return false;
9891   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9892     return false;
9893   if (!FDecl->isInStdNamespace())
9894     return false;
9895 
9896   return true;
9897 }
9898 
9899 // Warn when using the wrong abs() function.
9900 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9901                                       const FunctionDecl *FDecl) {
9902   if (Call->getNumArgs() != 1)
9903     return;
9904 
9905   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9906   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9907   if (AbsKind == 0 && !IsStdAbs)
9908     return;
9909 
9910   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9911   QualType ParamType = Call->getArg(0)->getType();
9912 
9913   // Unsigned types cannot be negative.  Suggest removing the absolute value
9914   // function call.
9915   if (ArgType->isUnsignedIntegerType()) {
9916     const char *FunctionName =
9917         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9918     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9919     Diag(Call->getExprLoc(), diag::note_remove_abs)
9920         << FunctionName
9921         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9922     return;
9923   }
9924 
9925   // Taking the absolute value of a pointer is very suspicious, they probably
9926   // wanted to index into an array, dereference a pointer, call a function, etc.
9927   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9928     unsigned DiagType = 0;
9929     if (ArgType->isFunctionType())
9930       DiagType = 1;
9931     else if (ArgType->isArrayType())
9932       DiagType = 2;
9933 
9934     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9935     return;
9936   }
9937 
9938   // std::abs has overloads which prevent most of the absolute value problems
9939   // from occurring.
9940   if (IsStdAbs)
9941     return;
9942 
9943   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9944   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9945 
9946   // The argument and parameter are the same kind.  Check if they are the right
9947   // size.
9948   if (ArgValueKind == ParamValueKind) {
9949     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9950       return;
9951 
9952     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9953     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9954         << FDecl << ArgType << ParamType;
9955 
9956     if (NewAbsKind == 0)
9957       return;
9958 
9959     emitReplacement(*this, Call->getExprLoc(),
9960                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9961     return;
9962   }
9963 
9964   // ArgValueKind != ParamValueKind
9965   // The wrong type of absolute value function was used.  Attempt to find the
9966   // proper one.
9967   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9968   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9969   if (NewAbsKind == 0)
9970     return;
9971 
9972   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9973       << FDecl << ParamValueKind << ArgValueKind;
9974 
9975   emitReplacement(*this, Call->getExprLoc(),
9976                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9977 }
9978 
9979 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9980 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9981                                 const FunctionDecl *FDecl) {
9982   if (!Call || !FDecl) return;
9983 
9984   // Ignore template specializations and macros.
9985   if (inTemplateInstantiation()) return;
9986   if (Call->getExprLoc().isMacroID()) return;
9987 
9988   // Only care about the one template argument, two function parameter std::max
9989   if (Call->getNumArgs() != 2) return;
9990   if (!IsStdFunction(FDecl, "max")) return;
9991   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9992   if (!ArgList) return;
9993   if (ArgList->size() != 1) return;
9994 
9995   // Check that template type argument is unsigned integer.
9996   const auto& TA = ArgList->get(0);
9997   if (TA.getKind() != TemplateArgument::Type) return;
9998   QualType ArgType = TA.getAsType();
9999   if (!ArgType->isUnsignedIntegerType()) return;
10000 
10001   // See if either argument is a literal zero.
10002   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10003     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10004     if (!MTE) return false;
10005     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10006     if (!Num) return false;
10007     if (Num->getValue() != 0) return false;
10008     return true;
10009   };
10010 
10011   const Expr *FirstArg = Call->getArg(0);
10012   const Expr *SecondArg = Call->getArg(1);
10013   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10014   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10015 
10016   // Only warn when exactly one argument is zero.
10017   if (IsFirstArgZero == IsSecondArgZero) return;
10018 
10019   SourceRange FirstRange = FirstArg->getSourceRange();
10020   SourceRange SecondRange = SecondArg->getSourceRange();
10021 
10022   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10023 
10024   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10025       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10026 
10027   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10028   SourceRange RemovalRange;
10029   if (IsFirstArgZero) {
10030     RemovalRange = SourceRange(FirstRange.getBegin(),
10031                                SecondRange.getBegin().getLocWithOffset(-1));
10032   } else {
10033     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10034                                SecondRange.getEnd());
10035   }
10036 
10037   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10038         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10039         << FixItHint::CreateRemoval(RemovalRange);
10040 }
10041 
10042 //===--- CHECK: Standard memory functions ---------------------------------===//
10043 
10044 /// Takes the expression passed to the size_t parameter of functions
10045 /// such as memcmp, strncat, etc and warns if it's a comparison.
10046 ///
10047 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10048 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10049                                            IdentifierInfo *FnName,
10050                                            SourceLocation FnLoc,
10051                                            SourceLocation RParenLoc) {
10052   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10053   if (!Size)
10054     return false;
10055 
10056   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10057   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10058     return false;
10059 
10060   SourceRange SizeRange = Size->getSourceRange();
10061   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10062       << SizeRange << FnName;
10063   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10064       << FnName
10065       << FixItHint::CreateInsertion(
10066              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10067       << FixItHint::CreateRemoval(RParenLoc);
10068   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10069       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10070       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10071                                     ")");
10072 
10073   return true;
10074 }
10075 
10076 /// Determine whether the given type is or contains a dynamic class type
10077 /// (e.g., whether it has a vtable).
10078 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10079                                                      bool &IsContained) {
10080   // Look through array types while ignoring qualifiers.
10081   const Type *Ty = T->getBaseElementTypeUnsafe();
10082   IsContained = false;
10083 
10084   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10085   RD = RD ? RD->getDefinition() : nullptr;
10086   if (!RD || RD->isInvalidDecl())
10087     return nullptr;
10088 
10089   if (RD->isDynamicClass())
10090     return RD;
10091 
10092   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10093   // It's impossible for a class to transitively contain itself by value, so
10094   // infinite recursion is impossible.
10095   for (auto *FD : RD->fields()) {
10096     bool SubContained;
10097     if (const CXXRecordDecl *ContainedRD =
10098             getContainedDynamicClass(FD->getType(), SubContained)) {
10099       IsContained = true;
10100       return ContainedRD;
10101     }
10102   }
10103 
10104   return nullptr;
10105 }
10106 
10107 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10108   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10109     if (Unary->getKind() == UETT_SizeOf)
10110       return Unary;
10111   return nullptr;
10112 }
10113 
10114 /// If E is a sizeof expression, returns its argument expression,
10115 /// otherwise returns NULL.
10116 static const Expr *getSizeOfExprArg(const Expr *E) {
10117   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10118     if (!SizeOf->isArgumentType())
10119       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10120   return nullptr;
10121 }
10122 
10123 /// If E is a sizeof expression, returns its argument type.
10124 static QualType getSizeOfArgType(const Expr *E) {
10125   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10126     return SizeOf->getTypeOfArgument();
10127   return QualType();
10128 }
10129 
10130 namespace {
10131 
10132 struct SearchNonTrivialToInitializeField
10133     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10134   using Super =
10135       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10136 
10137   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10138 
10139   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10140                      SourceLocation SL) {
10141     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10142       asDerived().visitArray(PDIK, AT, SL);
10143       return;
10144     }
10145 
10146     Super::visitWithKind(PDIK, FT, SL);
10147   }
10148 
10149   void visitARCStrong(QualType FT, SourceLocation SL) {
10150     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10151   }
10152   void visitARCWeak(QualType FT, SourceLocation SL) {
10153     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10154   }
10155   void visitStruct(QualType FT, SourceLocation SL) {
10156     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10157       visit(FD->getType(), FD->getLocation());
10158   }
10159   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10160                   const ArrayType *AT, SourceLocation SL) {
10161     visit(getContext().getBaseElementType(AT), SL);
10162   }
10163   void visitTrivial(QualType FT, SourceLocation SL) {}
10164 
10165   static void diag(QualType RT, const Expr *E, Sema &S) {
10166     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10167   }
10168 
10169   ASTContext &getContext() { return S.getASTContext(); }
10170 
10171   const Expr *E;
10172   Sema &S;
10173 };
10174 
10175 struct SearchNonTrivialToCopyField
10176     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10177   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10178 
10179   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10180 
10181   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10182                      SourceLocation SL) {
10183     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10184       asDerived().visitArray(PCK, AT, SL);
10185       return;
10186     }
10187 
10188     Super::visitWithKind(PCK, FT, SL);
10189   }
10190 
10191   void visitARCStrong(QualType FT, SourceLocation SL) {
10192     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10193   }
10194   void visitARCWeak(QualType FT, SourceLocation SL) {
10195     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10196   }
10197   void visitStruct(QualType FT, SourceLocation SL) {
10198     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10199       visit(FD->getType(), FD->getLocation());
10200   }
10201   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10202                   SourceLocation SL) {
10203     visit(getContext().getBaseElementType(AT), SL);
10204   }
10205   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10206                 SourceLocation SL) {}
10207   void visitTrivial(QualType FT, SourceLocation SL) {}
10208   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10209 
10210   static void diag(QualType RT, const Expr *E, Sema &S) {
10211     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10212   }
10213 
10214   ASTContext &getContext() { return S.getASTContext(); }
10215 
10216   const Expr *E;
10217   Sema &S;
10218 };
10219 
10220 }
10221 
10222 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10223 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10224   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10225 
10226   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10227     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10228       return false;
10229 
10230     return doesExprLikelyComputeSize(BO->getLHS()) ||
10231            doesExprLikelyComputeSize(BO->getRHS());
10232   }
10233 
10234   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10235 }
10236 
10237 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10238 ///
10239 /// \code
10240 ///   #define MACRO 0
10241 ///   foo(MACRO);
10242 ///   foo(0);
10243 /// \endcode
10244 ///
10245 /// This should return true for the first call to foo, but not for the second
10246 /// (regardless of whether foo is a macro or function).
10247 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10248                                         SourceLocation CallLoc,
10249                                         SourceLocation ArgLoc) {
10250   if (!CallLoc.isMacroID())
10251     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10252 
10253   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10254          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10255 }
10256 
10257 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10258 /// last two arguments transposed.
10259 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10260   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10261     return;
10262 
10263   const Expr *SizeArg =
10264     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10265 
10266   auto isLiteralZero = [](const Expr *E) {
10267     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10268   };
10269 
10270   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10271   SourceLocation CallLoc = Call->getRParenLoc();
10272   SourceManager &SM = S.getSourceManager();
10273   if (isLiteralZero(SizeArg) &&
10274       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10275 
10276     SourceLocation DiagLoc = SizeArg->getExprLoc();
10277 
10278     // Some platforms #define bzero to __builtin_memset. See if this is the
10279     // case, and if so, emit a better diagnostic.
10280     if (BId == Builtin::BIbzero ||
10281         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10282                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10283       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10284       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10285     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10286       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10287       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10288     }
10289     return;
10290   }
10291 
10292   // If the second argument to a memset is a sizeof expression and the third
10293   // isn't, this is also likely an error. This should catch
10294   // 'memset(buf, sizeof(buf), 0xff)'.
10295   if (BId == Builtin::BImemset &&
10296       doesExprLikelyComputeSize(Call->getArg(1)) &&
10297       !doesExprLikelyComputeSize(Call->getArg(2))) {
10298     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10299     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10300     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10301     return;
10302   }
10303 }
10304 
10305 /// Check for dangerous or invalid arguments to memset().
10306 ///
10307 /// This issues warnings on known problematic, dangerous or unspecified
10308 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10309 /// function calls.
10310 ///
10311 /// \param Call The call expression to diagnose.
10312 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10313                                    unsigned BId,
10314                                    IdentifierInfo *FnName) {
10315   assert(BId != 0);
10316 
10317   // It is possible to have a non-standard definition of memset.  Validate
10318   // we have enough arguments, and if not, abort further checking.
10319   unsigned ExpectedNumArgs =
10320       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10321   if (Call->getNumArgs() < ExpectedNumArgs)
10322     return;
10323 
10324   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10325                       BId == Builtin::BIstrndup ? 1 : 2);
10326   unsigned LenArg =
10327       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10328   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10329 
10330   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10331                                      Call->getBeginLoc(), Call->getRParenLoc()))
10332     return;
10333 
10334   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10335   CheckMemaccessSize(*this, BId, Call);
10336 
10337   // We have special checking when the length is a sizeof expression.
10338   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10339   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10340   llvm::FoldingSetNodeID SizeOfArgID;
10341 
10342   // Although widely used, 'bzero' is not a standard function. Be more strict
10343   // with the argument types before allowing diagnostics and only allow the
10344   // form bzero(ptr, sizeof(...)).
10345   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10346   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10347     return;
10348 
10349   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10350     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10351     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10352 
10353     QualType DestTy = Dest->getType();
10354     QualType PointeeTy;
10355     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10356       PointeeTy = DestPtrTy->getPointeeType();
10357 
10358       // Never warn about void type pointers. This can be used to suppress
10359       // false positives.
10360       if (PointeeTy->isVoidType())
10361         continue;
10362 
10363       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10364       // actually comparing the expressions for equality. Because computing the
10365       // expression IDs can be expensive, we only do this if the diagnostic is
10366       // enabled.
10367       if (SizeOfArg &&
10368           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10369                            SizeOfArg->getExprLoc())) {
10370         // We only compute IDs for expressions if the warning is enabled, and
10371         // cache the sizeof arg's ID.
10372         if (SizeOfArgID == llvm::FoldingSetNodeID())
10373           SizeOfArg->Profile(SizeOfArgID, Context, true);
10374         llvm::FoldingSetNodeID DestID;
10375         Dest->Profile(DestID, Context, true);
10376         if (DestID == SizeOfArgID) {
10377           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10378           //       over sizeof(src) as well.
10379           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10380           StringRef ReadableName = FnName->getName();
10381 
10382           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10383             if (UnaryOp->getOpcode() == UO_AddrOf)
10384               ActionIdx = 1; // If its an address-of operator, just remove it.
10385           if (!PointeeTy->isIncompleteType() &&
10386               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10387             ActionIdx = 2; // If the pointee's size is sizeof(char),
10388                            // suggest an explicit length.
10389 
10390           // If the function is defined as a builtin macro, do not show macro
10391           // expansion.
10392           SourceLocation SL = SizeOfArg->getExprLoc();
10393           SourceRange DSR = Dest->getSourceRange();
10394           SourceRange SSR = SizeOfArg->getSourceRange();
10395           SourceManager &SM = getSourceManager();
10396 
10397           if (SM.isMacroArgExpansion(SL)) {
10398             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10399             SL = SM.getSpellingLoc(SL);
10400             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10401                              SM.getSpellingLoc(DSR.getEnd()));
10402             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10403                              SM.getSpellingLoc(SSR.getEnd()));
10404           }
10405 
10406           DiagRuntimeBehavior(SL, SizeOfArg,
10407                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10408                                 << ReadableName
10409                                 << PointeeTy
10410                                 << DestTy
10411                                 << DSR
10412                                 << SSR);
10413           DiagRuntimeBehavior(SL, SizeOfArg,
10414                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10415                                 << ActionIdx
10416                                 << SSR);
10417 
10418           break;
10419         }
10420       }
10421 
10422       // Also check for cases where the sizeof argument is the exact same
10423       // type as the memory argument, and where it points to a user-defined
10424       // record type.
10425       if (SizeOfArgTy != QualType()) {
10426         if (PointeeTy->isRecordType() &&
10427             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10428           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10429                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10430                                 << FnName << SizeOfArgTy << ArgIdx
10431                                 << PointeeTy << Dest->getSourceRange()
10432                                 << LenExpr->getSourceRange());
10433           break;
10434         }
10435       }
10436     } else if (DestTy->isArrayType()) {
10437       PointeeTy = DestTy;
10438     }
10439 
10440     if (PointeeTy == QualType())
10441       continue;
10442 
10443     // Always complain about dynamic classes.
10444     bool IsContained;
10445     if (const CXXRecordDecl *ContainedRD =
10446             getContainedDynamicClass(PointeeTy, IsContained)) {
10447 
10448       unsigned OperationType = 0;
10449       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10450       // "overwritten" if we're warning about the destination for any call
10451       // but memcmp; otherwise a verb appropriate to the call.
10452       if (ArgIdx != 0 || IsCmp) {
10453         if (BId == Builtin::BImemcpy)
10454           OperationType = 1;
10455         else if(BId == Builtin::BImemmove)
10456           OperationType = 2;
10457         else if (IsCmp)
10458           OperationType = 3;
10459       }
10460 
10461       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10462                           PDiag(diag::warn_dyn_class_memaccess)
10463                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10464                               << IsContained << ContainedRD << OperationType
10465                               << Call->getCallee()->getSourceRange());
10466     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10467              BId != Builtin::BImemset)
10468       DiagRuntimeBehavior(
10469         Dest->getExprLoc(), Dest,
10470         PDiag(diag::warn_arc_object_memaccess)
10471           << ArgIdx << FnName << PointeeTy
10472           << Call->getCallee()->getSourceRange());
10473     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10474       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10475           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10476         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10477                             PDiag(diag::warn_cstruct_memaccess)
10478                                 << ArgIdx << FnName << PointeeTy << 0);
10479         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10480       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10481                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10482         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10483                             PDiag(diag::warn_cstruct_memaccess)
10484                                 << ArgIdx << FnName << PointeeTy << 1);
10485         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10486       } else {
10487         continue;
10488       }
10489     } else
10490       continue;
10491 
10492     DiagRuntimeBehavior(
10493       Dest->getExprLoc(), Dest,
10494       PDiag(diag::note_bad_memaccess_silence)
10495         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10496     break;
10497   }
10498 }
10499 
10500 // A little helper routine: ignore addition and subtraction of integer literals.
10501 // This intentionally does not ignore all integer constant expressions because
10502 // we don't want to remove sizeof().
10503 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10504   Ex = Ex->IgnoreParenCasts();
10505 
10506   while (true) {
10507     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10508     if (!BO || !BO->isAdditiveOp())
10509       break;
10510 
10511     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10512     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10513 
10514     if (isa<IntegerLiteral>(RHS))
10515       Ex = LHS;
10516     else if (isa<IntegerLiteral>(LHS))
10517       Ex = RHS;
10518     else
10519       break;
10520   }
10521 
10522   return Ex;
10523 }
10524 
10525 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10526                                                       ASTContext &Context) {
10527   // Only handle constant-sized or VLAs, but not flexible members.
10528   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10529     // Only issue the FIXIT for arrays of size > 1.
10530     if (CAT->getSize().getSExtValue() <= 1)
10531       return false;
10532   } else if (!Ty->isVariableArrayType()) {
10533     return false;
10534   }
10535   return true;
10536 }
10537 
10538 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10539 // be the size of the source, instead of the destination.
10540 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10541                                     IdentifierInfo *FnName) {
10542 
10543   // Don't crash if the user has the wrong number of arguments
10544   unsigned NumArgs = Call->getNumArgs();
10545   if ((NumArgs != 3) && (NumArgs != 4))
10546     return;
10547 
10548   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10549   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10550   const Expr *CompareWithSrc = nullptr;
10551 
10552   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10553                                      Call->getBeginLoc(), Call->getRParenLoc()))
10554     return;
10555 
10556   // Look for 'strlcpy(dst, x, sizeof(x))'
10557   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10558     CompareWithSrc = Ex;
10559   else {
10560     // Look for 'strlcpy(dst, x, strlen(x))'
10561     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10562       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10563           SizeCall->getNumArgs() == 1)
10564         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10565     }
10566   }
10567 
10568   if (!CompareWithSrc)
10569     return;
10570 
10571   // Determine if the argument to sizeof/strlen is equal to the source
10572   // argument.  In principle there's all kinds of things you could do
10573   // here, for instance creating an == expression and evaluating it with
10574   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10575   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10576   if (!SrcArgDRE)
10577     return;
10578 
10579   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10580   if (!CompareWithSrcDRE ||
10581       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10582     return;
10583 
10584   const Expr *OriginalSizeArg = Call->getArg(2);
10585   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10586       << OriginalSizeArg->getSourceRange() << FnName;
10587 
10588   // Output a FIXIT hint if the destination is an array (rather than a
10589   // pointer to an array).  This could be enhanced to handle some
10590   // pointers if we know the actual size, like if DstArg is 'array+2'
10591   // we could say 'sizeof(array)-2'.
10592   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10593   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10594     return;
10595 
10596   SmallString<128> sizeString;
10597   llvm::raw_svector_ostream OS(sizeString);
10598   OS << "sizeof(";
10599   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10600   OS << ")";
10601 
10602   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10603       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10604                                       OS.str());
10605 }
10606 
10607 /// Check if two expressions refer to the same declaration.
10608 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10609   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10610     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10611       return D1->getDecl() == D2->getDecl();
10612   return false;
10613 }
10614 
10615 static const Expr *getStrlenExprArg(const Expr *E) {
10616   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10617     const FunctionDecl *FD = CE->getDirectCallee();
10618     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10619       return nullptr;
10620     return CE->getArg(0)->IgnoreParenCasts();
10621   }
10622   return nullptr;
10623 }
10624 
10625 // Warn on anti-patterns as the 'size' argument to strncat.
10626 // The correct size argument should look like following:
10627 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10628 void Sema::CheckStrncatArguments(const CallExpr *CE,
10629                                  IdentifierInfo *FnName) {
10630   // Don't crash if the user has the wrong number of arguments.
10631   if (CE->getNumArgs() < 3)
10632     return;
10633   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10634   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10635   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10636 
10637   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10638                                      CE->getRParenLoc()))
10639     return;
10640 
10641   // Identify common expressions, which are wrongly used as the size argument
10642   // to strncat and may lead to buffer overflows.
10643   unsigned PatternType = 0;
10644   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10645     // - sizeof(dst)
10646     if (referToTheSameDecl(SizeOfArg, DstArg))
10647       PatternType = 1;
10648     // - sizeof(src)
10649     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10650       PatternType = 2;
10651   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10652     if (BE->getOpcode() == BO_Sub) {
10653       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10654       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10655       // - sizeof(dst) - strlen(dst)
10656       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10657           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10658         PatternType = 1;
10659       // - sizeof(src) - (anything)
10660       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10661         PatternType = 2;
10662     }
10663   }
10664 
10665   if (PatternType == 0)
10666     return;
10667 
10668   // Generate the diagnostic.
10669   SourceLocation SL = LenArg->getBeginLoc();
10670   SourceRange SR = LenArg->getSourceRange();
10671   SourceManager &SM = getSourceManager();
10672 
10673   // If the function is defined as a builtin macro, do not show macro expansion.
10674   if (SM.isMacroArgExpansion(SL)) {
10675     SL = SM.getSpellingLoc(SL);
10676     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10677                      SM.getSpellingLoc(SR.getEnd()));
10678   }
10679 
10680   // Check if the destination is an array (rather than a pointer to an array).
10681   QualType DstTy = DstArg->getType();
10682   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10683                                                                     Context);
10684   if (!isKnownSizeArray) {
10685     if (PatternType == 1)
10686       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10687     else
10688       Diag(SL, diag::warn_strncat_src_size) << SR;
10689     return;
10690   }
10691 
10692   if (PatternType == 1)
10693     Diag(SL, diag::warn_strncat_large_size) << SR;
10694   else
10695     Diag(SL, diag::warn_strncat_src_size) << SR;
10696 
10697   SmallString<128> sizeString;
10698   llvm::raw_svector_ostream OS(sizeString);
10699   OS << "sizeof(";
10700   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10701   OS << ") - ";
10702   OS << "strlen(";
10703   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10704   OS << ") - 1";
10705 
10706   Diag(SL, diag::note_strncat_wrong_size)
10707     << FixItHint::CreateReplacement(SR, OS.str());
10708 }
10709 
10710 namespace {
10711 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10712                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10713   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10714     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10715         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10716     return;
10717   }
10718 }
10719 
10720 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10721                                  const UnaryOperator *UnaryExpr) {
10722   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10723     const Decl *D = Lvalue->getDecl();
10724     if (isa<VarDecl, FunctionDecl>(D))
10725       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10726   }
10727 
10728   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10729     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10730                                       Lvalue->getMemberDecl());
10731 }
10732 
10733 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10734                             const UnaryOperator *UnaryExpr) {
10735   const auto *Lambda = dyn_cast<LambdaExpr>(
10736       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10737   if (!Lambda)
10738     return;
10739 
10740   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10741       << CalleeName << 2 /*object: lambda expression*/;
10742 }
10743 
10744 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10745                                   const DeclRefExpr *Lvalue) {
10746   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10747   if (Var == nullptr)
10748     return;
10749 
10750   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10751       << CalleeName << 0 /*object: */ << Var;
10752 }
10753 
10754 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10755                             const CastExpr *Cast) {
10756   SmallString<128> SizeString;
10757   llvm::raw_svector_ostream OS(SizeString);
10758 
10759   clang::CastKind Kind = Cast->getCastKind();
10760   if (Kind == clang::CK_BitCast &&
10761       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10762     return;
10763   if (Kind == clang::CK_IntegralToPointer &&
10764       !isa<IntegerLiteral>(
10765           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10766     return;
10767 
10768   switch (Cast->getCastKind()) {
10769   case clang::CK_BitCast:
10770   case clang::CK_IntegralToPointer:
10771   case clang::CK_FunctionToPointerDecay:
10772     OS << '\'';
10773     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10774     OS << '\'';
10775     break;
10776   default:
10777     return;
10778   }
10779 
10780   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10781       << CalleeName << 0 /*object: */ << OS.str();
10782 }
10783 } // namespace
10784 
10785 /// Alerts the user that they are attempting to free a non-malloc'd object.
10786 void Sema::CheckFreeArguments(const CallExpr *E) {
10787   const std::string CalleeName =
10788       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10789 
10790   { // Prefer something that doesn't involve a cast to make things simpler.
10791     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10792     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10793       switch (UnaryExpr->getOpcode()) {
10794       case UnaryOperator::Opcode::UO_AddrOf:
10795         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10796       case UnaryOperator::Opcode::UO_Plus:
10797         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10798       default:
10799         break;
10800       }
10801 
10802     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10803       if (Lvalue->getType()->isArrayType())
10804         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10805 
10806     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10807       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10808           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10809       return;
10810     }
10811 
10812     if (isa<BlockExpr>(Arg)) {
10813       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10814           << CalleeName << 1 /*object: block*/;
10815       return;
10816     }
10817   }
10818   // Maybe the cast was important, check after the other cases.
10819   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10820     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10821 }
10822 
10823 void
10824 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10825                          SourceLocation ReturnLoc,
10826                          bool isObjCMethod,
10827                          const AttrVec *Attrs,
10828                          const FunctionDecl *FD) {
10829   // Check if the return value is null but should not be.
10830   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10831        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10832       CheckNonNullExpr(*this, RetValExp))
10833     Diag(ReturnLoc, diag::warn_null_ret)
10834       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10835 
10836   // C++11 [basic.stc.dynamic.allocation]p4:
10837   //   If an allocation function declared with a non-throwing
10838   //   exception-specification fails to allocate storage, it shall return
10839   //   a null pointer. Any other allocation function that fails to allocate
10840   //   storage shall indicate failure only by throwing an exception [...]
10841   if (FD) {
10842     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10843     if (Op == OO_New || Op == OO_Array_New) {
10844       const FunctionProtoType *Proto
10845         = FD->getType()->castAs<FunctionProtoType>();
10846       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10847           CheckNonNullExpr(*this, RetValExp))
10848         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10849           << FD << getLangOpts().CPlusPlus11;
10850     }
10851   }
10852 
10853   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10854   // here prevent the user from using a PPC MMA type as trailing return type.
10855   if (Context.getTargetInfo().getTriple().isPPC64())
10856     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10857 }
10858 
10859 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10860 
10861 /// Check for comparisons of floating point operands using != and ==.
10862 /// Issue a warning if these are no self-comparisons, as they are not likely
10863 /// to do what the programmer intended.
10864 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10865   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10866   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10867 
10868   // Special case: check for x == x (which is OK).
10869   // Do not emit warnings for such cases.
10870   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10871     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10872       if (DRL->getDecl() == DRR->getDecl())
10873         return;
10874 
10875   // Special case: check for comparisons against literals that can be exactly
10876   //  represented by APFloat.  In such cases, do not emit a warning.  This
10877   //  is a heuristic: often comparison against such literals are used to
10878   //  detect if a value in a variable has not changed.  This clearly can
10879   //  lead to false negatives.
10880   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10881     if (FLL->isExact())
10882       return;
10883   } else
10884     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10885       if (FLR->isExact())
10886         return;
10887 
10888   // Check for comparisons with builtin types.
10889   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10890     if (CL->getBuiltinCallee())
10891       return;
10892 
10893   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10894     if (CR->getBuiltinCallee())
10895       return;
10896 
10897   // Emit the diagnostic.
10898   Diag(Loc, diag::warn_floatingpoint_eq)
10899     << LHS->getSourceRange() << RHS->getSourceRange();
10900 }
10901 
10902 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10903 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10904 
10905 namespace {
10906 
10907 /// Structure recording the 'active' range of an integer-valued
10908 /// expression.
10909 struct IntRange {
10910   /// The number of bits active in the int. Note that this includes exactly one
10911   /// sign bit if !NonNegative.
10912   unsigned Width;
10913 
10914   /// True if the int is known not to have negative values. If so, all leading
10915   /// bits before Width are known zero, otherwise they are known to be the
10916   /// same as the MSB within Width.
10917   bool NonNegative;
10918 
10919   IntRange(unsigned Width, bool NonNegative)
10920       : Width(Width), NonNegative(NonNegative) {}
10921 
10922   /// Number of bits excluding the sign bit.
10923   unsigned valueBits() const {
10924     return NonNegative ? Width : Width - 1;
10925   }
10926 
10927   /// Returns the range of the bool type.
10928   static IntRange forBoolType() {
10929     return IntRange(1, true);
10930   }
10931 
10932   /// Returns the range of an opaque value of the given integral type.
10933   static IntRange forValueOfType(ASTContext &C, QualType T) {
10934     return forValueOfCanonicalType(C,
10935                           T->getCanonicalTypeInternal().getTypePtr());
10936   }
10937 
10938   /// Returns the range of an opaque value of a canonical integral type.
10939   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10940     assert(T->isCanonicalUnqualified());
10941 
10942     if (const VectorType *VT = dyn_cast<VectorType>(T))
10943       T = VT->getElementType().getTypePtr();
10944     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10945       T = CT->getElementType().getTypePtr();
10946     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10947       T = AT->getValueType().getTypePtr();
10948 
10949     if (!C.getLangOpts().CPlusPlus) {
10950       // For enum types in C code, use the underlying datatype.
10951       if (const EnumType *ET = dyn_cast<EnumType>(T))
10952         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10953     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10954       // For enum types in C++, use the known bit width of the enumerators.
10955       EnumDecl *Enum = ET->getDecl();
10956       // In C++11, enums can have a fixed underlying type. Use this type to
10957       // compute the range.
10958       if (Enum->isFixed()) {
10959         return IntRange(C.getIntWidth(QualType(T, 0)),
10960                         !ET->isSignedIntegerOrEnumerationType());
10961       }
10962 
10963       unsigned NumPositive = Enum->getNumPositiveBits();
10964       unsigned NumNegative = Enum->getNumNegativeBits();
10965 
10966       if (NumNegative == 0)
10967         return IntRange(NumPositive, true/*NonNegative*/);
10968       else
10969         return IntRange(std::max(NumPositive + 1, NumNegative),
10970                         false/*NonNegative*/);
10971     }
10972 
10973     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10974       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10975 
10976     const BuiltinType *BT = cast<BuiltinType>(T);
10977     assert(BT->isInteger());
10978 
10979     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10980   }
10981 
10982   /// Returns the "target" range of a canonical integral type, i.e.
10983   /// the range of values expressible in the type.
10984   ///
10985   /// This matches forValueOfCanonicalType except that enums have the
10986   /// full range of their type, not the range of their enumerators.
10987   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10988     assert(T->isCanonicalUnqualified());
10989 
10990     if (const VectorType *VT = dyn_cast<VectorType>(T))
10991       T = VT->getElementType().getTypePtr();
10992     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10993       T = CT->getElementType().getTypePtr();
10994     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10995       T = AT->getValueType().getTypePtr();
10996     if (const EnumType *ET = dyn_cast<EnumType>(T))
10997       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10998 
10999     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11000       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11001 
11002     const BuiltinType *BT = cast<BuiltinType>(T);
11003     assert(BT->isInteger());
11004 
11005     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11006   }
11007 
11008   /// Returns the supremum of two ranges: i.e. their conservative merge.
11009   static IntRange join(IntRange L, IntRange R) {
11010     bool Unsigned = L.NonNegative && R.NonNegative;
11011     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11012                     L.NonNegative && R.NonNegative);
11013   }
11014 
11015   /// Return the range of a bitwise-AND of the two ranges.
11016   static IntRange bit_and(IntRange L, IntRange R) {
11017     unsigned Bits = std::max(L.Width, R.Width);
11018     bool NonNegative = false;
11019     if (L.NonNegative) {
11020       Bits = std::min(Bits, L.Width);
11021       NonNegative = true;
11022     }
11023     if (R.NonNegative) {
11024       Bits = std::min(Bits, R.Width);
11025       NonNegative = true;
11026     }
11027     return IntRange(Bits, NonNegative);
11028   }
11029 
11030   /// Return the range of a sum of the two ranges.
11031   static IntRange sum(IntRange L, IntRange R) {
11032     bool Unsigned = L.NonNegative && R.NonNegative;
11033     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11034                     Unsigned);
11035   }
11036 
11037   /// Return the range of a difference of the two ranges.
11038   static IntRange difference(IntRange L, IntRange R) {
11039     // We need a 1-bit-wider range if:
11040     //   1) LHS can be negative: least value can be reduced.
11041     //   2) RHS can be negative: greatest value can be increased.
11042     bool CanWiden = !L.NonNegative || !R.NonNegative;
11043     bool Unsigned = L.NonNegative && R.Width == 0;
11044     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11045                         !Unsigned,
11046                     Unsigned);
11047   }
11048 
11049   /// Return the range of a product of the two ranges.
11050   static IntRange product(IntRange L, IntRange R) {
11051     // If both LHS and RHS can be negative, we can form
11052     //   -2^L * -2^R = 2^(L + R)
11053     // which requires L + R + 1 value bits to represent.
11054     bool CanWiden = !L.NonNegative && !R.NonNegative;
11055     bool Unsigned = L.NonNegative && R.NonNegative;
11056     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11057                     Unsigned);
11058   }
11059 
11060   /// Return the range of a remainder operation between the two ranges.
11061   static IntRange rem(IntRange L, IntRange R) {
11062     // The result of a remainder can't be larger than the result of
11063     // either side. The sign of the result is the sign of the LHS.
11064     bool Unsigned = L.NonNegative;
11065     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11066                     Unsigned);
11067   }
11068 };
11069 
11070 } // namespace
11071 
11072 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11073                               unsigned MaxWidth) {
11074   if (value.isSigned() && value.isNegative())
11075     return IntRange(value.getMinSignedBits(), false);
11076 
11077   if (value.getBitWidth() > MaxWidth)
11078     value = value.trunc(MaxWidth);
11079 
11080   // isNonNegative() just checks the sign bit without considering
11081   // signedness.
11082   return IntRange(value.getActiveBits(), true);
11083 }
11084 
11085 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11086                               unsigned MaxWidth) {
11087   if (result.isInt())
11088     return GetValueRange(C, result.getInt(), MaxWidth);
11089 
11090   if (result.isVector()) {
11091     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11092     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11093       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11094       R = IntRange::join(R, El);
11095     }
11096     return R;
11097   }
11098 
11099   if (result.isComplexInt()) {
11100     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11101     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11102     return IntRange::join(R, I);
11103   }
11104 
11105   // This can happen with lossless casts to intptr_t of "based" lvalues.
11106   // Assume it might use arbitrary bits.
11107   // FIXME: The only reason we need to pass the type in here is to get
11108   // the sign right on this one case.  It would be nice if APValue
11109   // preserved this.
11110   assert(result.isLValue() || result.isAddrLabelDiff());
11111   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11112 }
11113 
11114 static QualType GetExprType(const Expr *E) {
11115   QualType Ty = E->getType();
11116   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11117     Ty = AtomicRHS->getValueType();
11118   return Ty;
11119 }
11120 
11121 /// Pseudo-evaluate the given integer expression, estimating the
11122 /// range of values it might take.
11123 ///
11124 /// \param MaxWidth The width to which the value will be truncated.
11125 /// \param Approximate If \c true, return a likely range for the result: in
11126 ///        particular, assume that aritmetic on narrower types doesn't leave
11127 ///        those types. If \c false, return a range including all possible
11128 ///        result values.
11129 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11130                              bool InConstantContext, bool Approximate) {
11131   E = E->IgnoreParens();
11132 
11133   // Try a full evaluation first.
11134   Expr::EvalResult result;
11135   if (E->EvaluateAsRValue(result, C, InConstantContext))
11136     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11137 
11138   // I think we only want to look through implicit casts here; if the
11139   // user has an explicit widening cast, we should treat the value as
11140   // being of the new, wider type.
11141   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11142     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11143       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11144                           Approximate);
11145 
11146     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11147 
11148     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11149                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11150 
11151     // Assume that non-integer casts can span the full range of the type.
11152     if (!isIntegerCast)
11153       return OutputTypeRange;
11154 
11155     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11156                                      std::min(MaxWidth, OutputTypeRange.Width),
11157                                      InConstantContext, Approximate);
11158 
11159     // Bail out if the subexpr's range is as wide as the cast type.
11160     if (SubRange.Width >= OutputTypeRange.Width)
11161       return OutputTypeRange;
11162 
11163     // Otherwise, we take the smaller width, and we're non-negative if
11164     // either the output type or the subexpr is.
11165     return IntRange(SubRange.Width,
11166                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11167   }
11168 
11169   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11170     // If we can fold the condition, just take that operand.
11171     bool CondResult;
11172     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11173       return GetExprRange(C,
11174                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11175                           MaxWidth, InConstantContext, Approximate);
11176 
11177     // Otherwise, conservatively merge.
11178     // GetExprRange requires an integer expression, but a throw expression
11179     // results in a void type.
11180     Expr *E = CO->getTrueExpr();
11181     IntRange L = E->getType()->isVoidType()
11182                      ? IntRange{0, true}
11183                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11184     E = CO->getFalseExpr();
11185     IntRange R = E->getType()->isVoidType()
11186                      ? IntRange{0, true}
11187                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11188     return IntRange::join(L, R);
11189   }
11190 
11191   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11192     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11193 
11194     switch (BO->getOpcode()) {
11195     case BO_Cmp:
11196       llvm_unreachable("builtin <=> should have class type");
11197 
11198     // Boolean-valued operations are single-bit and positive.
11199     case BO_LAnd:
11200     case BO_LOr:
11201     case BO_LT:
11202     case BO_GT:
11203     case BO_LE:
11204     case BO_GE:
11205     case BO_EQ:
11206     case BO_NE:
11207       return IntRange::forBoolType();
11208 
11209     // The type of the assignments is the type of the LHS, so the RHS
11210     // is not necessarily the same type.
11211     case BO_MulAssign:
11212     case BO_DivAssign:
11213     case BO_RemAssign:
11214     case BO_AddAssign:
11215     case BO_SubAssign:
11216     case BO_XorAssign:
11217     case BO_OrAssign:
11218       // TODO: bitfields?
11219       return IntRange::forValueOfType(C, GetExprType(E));
11220 
11221     // Simple assignments just pass through the RHS, which will have
11222     // been coerced to the LHS type.
11223     case BO_Assign:
11224       // TODO: bitfields?
11225       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11226                           Approximate);
11227 
11228     // Operations with opaque sources are black-listed.
11229     case BO_PtrMemD:
11230     case BO_PtrMemI:
11231       return IntRange::forValueOfType(C, GetExprType(E));
11232 
11233     // Bitwise-and uses the *infinum* of the two source ranges.
11234     case BO_And:
11235     case BO_AndAssign:
11236       Combine = IntRange::bit_and;
11237       break;
11238 
11239     // Left shift gets black-listed based on a judgement call.
11240     case BO_Shl:
11241       // ...except that we want to treat '1 << (blah)' as logically
11242       // positive.  It's an important idiom.
11243       if (IntegerLiteral *I
11244             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11245         if (I->getValue() == 1) {
11246           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11247           return IntRange(R.Width, /*NonNegative*/ true);
11248         }
11249       }
11250       LLVM_FALLTHROUGH;
11251 
11252     case BO_ShlAssign:
11253       return IntRange::forValueOfType(C, GetExprType(E));
11254 
11255     // Right shift by a constant can narrow its left argument.
11256     case BO_Shr:
11257     case BO_ShrAssign: {
11258       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11259                                 Approximate);
11260 
11261       // If the shift amount is a positive constant, drop the width by
11262       // that much.
11263       if (Optional<llvm::APSInt> shift =
11264               BO->getRHS()->getIntegerConstantExpr(C)) {
11265         if (shift->isNonNegative()) {
11266           unsigned zext = shift->getZExtValue();
11267           if (zext >= L.Width)
11268             L.Width = (L.NonNegative ? 0 : 1);
11269           else
11270             L.Width -= zext;
11271         }
11272       }
11273 
11274       return L;
11275     }
11276 
11277     // Comma acts as its right operand.
11278     case BO_Comma:
11279       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11280                           Approximate);
11281 
11282     case BO_Add:
11283       if (!Approximate)
11284         Combine = IntRange::sum;
11285       break;
11286 
11287     case BO_Sub:
11288       if (BO->getLHS()->getType()->isPointerType())
11289         return IntRange::forValueOfType(C, GetExprType(E));
11290       if (!Approximate)
11291         Combine = IntRange::difference;
11292       break;
11293 
11294     case BO_Mul:
11295       if (!Approximate)
11296         Combine = IntRange::product;
11297       break;
11298 
11299     // The width of a division result is mostly determined by the size
11300     // of the LHS.
11301     case BO_Div: {
11302       // Don't 'pre-truncate' the operands.
11303       unsigned opWidth = C.getIntWidth(GetExprType(E));
11304       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11305                                 Approximate);
11306 
11307       // If the divisor is constant, use that.
11308       if (Optional<llvm::APSInt> divisor =
11309               BO->getRHS()->getIntegerConstantExpr(C)) {
11310         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11311         if (log2 >= L.Width)
11312           L.Width = (L.NonNegative ? 0 : 1);
11313         else
11314           L.Width = std::min(L.Width - log2, MaxWidth);
11315         return L;
11316       }
11317 
11318       // Otherwise, just use the LHS's width.
11319       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11320       // could be -1.
11321       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11322                                 Approximate);
11323       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11324     }
11325 
11326     case BO_Rem:
11327       Combine = IntRange::rem;
11328       break;
11329 
11330     // The default behavior is okay for these.
11331     case BO_Xor:
11332     case BO_Or:
11333       break;
11334     }
11335 
11336     // Combine the two ranges, but limit the result to the type in which we
11337     // performed the computation.
11338     QualType T = GetExprType(E);
11339     unsigned opWidth = C.getIntWidth(T);
11340     IntRange L =
11341         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11342     IntRange R =
11343         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11344     IntRange C = Combine(L, R);
11345     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11346     C.Width = std::min(C.Width, MaxWidth);
11347     return C;
11348   }
11349 
11350   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11351     switch (UO->getOpcode()) {
11352     // Boolean-valued operations are white-listed.
11353     case UO_LNot:
11354       return IntRange::forBoolType();
11355 
11356     // Operations with opaque sources are black-listed.
11357     case UO_Deref:
11358     case UO_AddrOf: // should be impossible
11359       return IntRange::forValueOfType(C, GetExprType(E));
11360 
11361     default:
11362       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11363                           Approximate);
11364     }
11365   }
11366 
11367   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11368     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11369                         Approximate);
11370 
11371   if (const auto *BitField = E->getSourceBitField())
11372     return IntRange(BitField->getBitWidthValue(C),
11373                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11374 
11375   return IntRange::forValueOfType(C, GetExprType(E));
11376 }
11377 
11378 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11379                              bool InConstantContext, bool Approximate) {
11380   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11381                       Approximate);
11382 }
11383 
11384 /// Checks whether the given value, which currently has the given
11385 /// source semantics, has the same value when coerced through the
11386 /// target semantics.
11387 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11388                                  const llvm::fltSemantics &Src,
11389                                  const llvm::fltSemantics &Tgt) {
11390   llvm::APFloat truncated = value;
11391 
11392   bool ignored;
11393   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11394   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11395 
11396   return truncated.bitwiseIsEqual(value);
11397 }
11398 
11399 /// Checks whether the given value, which currently has the given
11400 /// source semantics, has the same value when coerced through the
11401 /// target semantics.
11402 ///
11403 /// The value might be a vector of floats (or a complex number).
11404 static bool IsSameFloatAfterCast(const APValue &value,
11405                                  const llvm::fltSemantics &Src,
11406                                  const llvm::fltSemantics &Tgt) {
11407   if (value.isFloat())
11408     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11409 
11410   if (value.isVector()) {
11411     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11412       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11413         return false;
11414     return true;
11415   }
11416 
11417   assert(value.isComplexFloat());
11418   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11419           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11420 }
11421 
11422 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11423                                        bool IsListInit = false);
11424 
11425 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11426   // Suppress cases where we are comparing against an enum constant.
11427   if (const DeclRefExpr *DR =
11428       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11429     if (isa<EnumConstantDecl>(DR->getDecl()))
11430       return true;
11431 
11432   // Suppress cases where the value is expanded from a macro, unless that macro
11433   // is how a language represents a boolean literal. This is the case in both C
11434   // and Objective-C.
11435   SourceLocation BeginLoc = E->getBeginLoc();
11436   if (BeginLoc.isMacroID()) {
11437     StringRef MacroName = Lexer::getImmediateMacroName(
11438         BeginLoc, S.getSourceManager(), S.getLangOpts());
11439     return MacroName != "YES" && MacroName != "NO" &&
11440            MacroName != "true" && MacroName != "false";
11441   }
11442 
11443   return false;
11444 }
11445 
11446 static bool isKnownToHaveUnsignedValue(Expr *E) {
11447   return E->getType()->isIntegerType() &&
11448          (!E->getType()->isSignedIntegerType() ||
11449           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11450 }
11451 
11452 namespace {
11453 /// The promoted range of values of a type. In general this has the
11454 /// following structure:
11455 ///
11456 ///     |-----------| . . . |-----------|
11457 ///     ^           ^       ^           ^
11458 ///    Min       HoleMin  HoleMax      Max
11459 ///
11460 /// ... where there is only a hole if a signed type is promoted to unsigned
11461 /// (in which case Min and Max are the smallest and largest representable
11462 /// values).
11463 struct PromotedRange {
11464   // Min, or HoleMax if there is a hole.
11465   llvm::APSInt PromotedMin;
11466   // Max, or HoleMin if there is a hole.
11467   llvm::APSInt PromotedMax;
11468 
11469   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11470     if (R.Width == 0)
11471       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11472     else if (R.Width >= BitWidth && !Unsigned) {
11473       // Promotion made the type *narrower*. This happens when promoting
11474       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11475       // Treat all values of 'signed int' as being in range for now.
11476       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11477       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11478     } else {
11479       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11480                         .extOrTrunc(BitWidth);
11481       PromotedMin.setIsUnsigned(Unsigned);
11482 
11483       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11484                         .extOrTrunc(BitWidth);
11485       PromotedMax.setIsUnsigned(Unsigned);
11486     }
11487   }
11488 
11489   // Determine whether this range is contiguous (has no hole).
11490   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11491 
11492   // Where a constant value is within the range.
11493   enum ComparisonResult {
11494     LT = 0x1,
11495     LE = 0x2,
11496     GT = 0x4,
11497     GE = 0x8,
11498     EQ = 0x10,
11499     NE = 0x20,
11500     InRangeFlag = 0x40,
11501 
11502     Less = LE | LT | NE,
11503     Min = LE | InRangeFlag,
11504     InRange = InRangeFlag,
11505     Max = GE | InRangeFlag,
11506     Greater = GE | GT | NE,
11507 
11508     OnlyValue = LE | GE | EQ | InRangeFlag,
11509     InHole = NE
11510   };
11511 
11512   ComparisonResult compare(const llvm::APSInt &Value) const {
11513     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11514            Value.isUnsigned() == PromotedMin.isUnsigned());
11515     if (!isContiguous()) {
11516       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11517       if (Value.isMinValue()) return Min;
11518       if (Value.isMaxValue()) return Max;
11519       if (Value >= PromotedMin) return InRange;
11520       if (Value <= PromotedMax) return InRange;
11521       return InHole;
11522     }
11523 
11524     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11525     case -1: return Less;
11526     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11527     case 1:
11528       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11529       case -1: return InRange;
11530       case 0: return Max;
11531       case 1: return Greater;
11532       }
11533     }
11534 
11535     llvm_unreachable("impossible compare result");
11536   }
11537 
11538   static llvm::Optional<StringRef>
11539   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11540     if (Op == BO_Cmp) {
11541       ComparisonResult LTFlag = LT, GTFlag = GT;
11542       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11543 
11544       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11545       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11546       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11547       return llvm::None;
11548     }
11549 
11550     ComparisonResult TrueFlag, FalseFlag;
11551     if (Op == BO_EQ) {
11552       TrueFlag = EQ;
11553       FalseFlag = NE;
11554     } else if (Op == BO_NE) {
11555       TrueFlag = NE;
11556       FalseFlag = EQ;
11557     } else {
11558       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11559         TrueFlag = LT;
11560         FalseFlag = GE;
11561       } else {
11562         TrueFlag = GT;
11563         FalseFlag = LE;
11564       }
11565       if (Op == BO_GE || Op == BO_LE)
11566         std::swap(TrueFlag, FalseFlag);
11567     }
11568     if (R & TrueFlag)
11569       return StringRef("true");
11570     if (R & FalseFlag)
11571       return StringRef("false");
11572     return llvm::None;
11573   }
11574 };
11575 }
11576 
11577 static bool HasEnumType(Expr *E) {
11578   // Strip off implicit integral promotions.
11579   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11580     if (ICE->getCastKind() != CK_IntegralCast &&
11581         ICE->getCastKind() != CK_NoOp)
11582       break;
11583     E = ICE->getSubExpr();
11584   }
11585 
11586   return E->getType()->isEnumeralType();
11587 }
11588 
11589 static int classifyConstantValue(Expr *Constant) {
11590   // The values of this enumeration are used in the diagnostics
11591   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11592   enum ConstantValueKind {
11593     Miscellaneous = 0,
11594     LiteralTrue,
11595     LiteralFalse
11596   };
11597   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11598     return BL->getValue() ? ConstantValueKind::LiteralTrue
11599                           : ConstantValueKind::LiteralFalse;
11600   return ConstantValueKind::Miscellaneous;
11601 }
11602 
11603 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11604                                         Expr *Constant, Expr *Other,
11605                                         const llvm::APSInt &Value,
11606                                         bool RhsConstant) {
11607   if (S.inTemplateInstantiation())
11608     return false;
11609 
11610   Expr *OriginalOther = Other;
11611 
11612   Constant = Constant->IgnoreParenImpCasts();
11613   Other = Other->IgnoreParenImpCasts();
11614 
11615   // Suppress warnings on tautological comparisons between values of the same
11616   // enumeration type. There are only two ways we could warn on this:
11617   //  - If the constant is outside the range of representable values of
11618   //    the enumeration. In such a case, we should warn about the cast
11619   //    to enumeration type, not about the comparison.
11620   //  - If the constant is the maximum / minimum in-range value. For an
11621   //    enumeratin type, such comparisons can be meaningful and useful.
11622   if (Constant->getType()->isEnumeralType() &&
11623       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11624     return false;
11625 
11626   IntRange OtherValueRange = GetExprRange(
11627       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11628 
11629   QualType OtherT = Other->getType();
11630   if (const auto *AT = OtherT->getAs<AtomicType>())
11631     OtherT = AT->getValueType();
11632   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11633 
11634   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11635   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11636   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11637                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11638                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11639 
11640   // Whether we're treating Other as being a bool because of the form of
11641   // expression despite it having another type (typically 'int' in C).
11642   bool OtherIsBooleanDespiteType =
11643       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11644   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11645     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11646 
11647   // Check if all values in the range of possible values of this expression
11648   // lead to the same comparison outcome.
11649   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11650                                         Value.isUnsigned());
11651   auto Cmp = OtherPromotedValueRange.compare(Value);
11652   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11653   if (!Result)
11654     return false;
11655 
11656   // Also consider the range determined by the type alone. This allows us to
11657   // classify the warning under the proper diagnostic group.
11658   bool TautologicalTypeCompare = false;
11659   {
11660     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11661                                          Value.isUnsigned());
11662     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11663     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11664                                                        RhsConstant)) {
11665       TautologicalTypeCompare = true;
11666       Cmp = TypeCmp;
11667       Result = TypeResult;
11668     }
11669   }
11670 
11671   // Don't warn if the non-constant operand actually always evaluates to the
11672   // same value.
11673   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11674     return false;
11675 
11676   // Suppress the diagnostic for an in-range comparison if the constant comes
11677   // from a macro or enumerator. We don't want to diagnose
11678   //
11679   //   some_long_value <= INT_MAX
11680   //
11681   // when sizeof(int) == sizeof(long).
11682   bool InRange = Cmp & PromotedRange::InRangeFlag;
11683   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11684     return false;
11685 
11686   // A comparison of an unsigned bit-field against 0 is really a type problem,
11687   // even though at the type level the bit-field might promote to 'signed int'.
11688   if (Other->refersToBitField() && InRange && Value == 0 &&
11689       Other->getType()->isUnsignedIntegerOrEnumerationType())
11690     TautologicalTypeCompare = true;
11691 
11692   // If this is a comparison to an enum constant, include that
11693   // constant in the diagnostic.
11694   const EnumConstantDecl *ED = nullptr;
11695   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11696     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11697 
11698   // Should be enough for uint128 (39 decimal digits)
11699   SmallString<64> PrettySourceValue;
11700   llvm::raw_svector_ostream OS(PrettySourceValue);
11701   if (ED) {
11702     OS << '\'' << *ED << "' (" << Value << ")";
11703   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11704                Constant->IgnoreParenImpCasts())) {
11705     OS << (BL->getValue() ? "YES" : "NO");
11706   } else {
11707     OS << Value;
11708   }
11709 
11710   if (!TautologicalTypeCompare) {
11711     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11712         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11713         << E->getOpcodeStr() << OS.str() << *Result
11714         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11715     return true;
11716   }
11717 
11718   if (IsObjCSignedCharBool) {
11719     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11720                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11721                               << OS.str() << *Result);
11722     return true;
11723   }
11724 
11725   // FIXME: We use a somewhat different formatting for the in-range cases and
11726   // cases involving boolean values for historical reasons. We should pick a
11727   // consistent way of presenting these diagnostics.
11728   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11729 
11730     S.DiagRuntimeBehavior(
11731         E->getOperatorLoc(), E,
11732         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11733                          : diag::warn_tautological_bool_compare)
11734             << OS.str() << classifyConstantValue(Constant) << OtherT
11735             << OtherIsBooleanDespiteType << *Result
11736             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11737   } else {
11738     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11739     unsigned Diag =
11740         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11741             ? (HasEnumType(OriginalOther)
11742                    ? diag::warn_unsigned_enum_always_true_comparison
11743                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11744                               : diag::warn_unsigned_always_true_comparison)
11745             : diag::warn_tautological_constant_compare;
11746 
11747     S.Diag(E->getOperatorLoc(), Diag)
11748         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11749         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11750   }
11751 
11752   return true;
11753 }
11754 
11755 /// Analyze the operands of the given comparison.  Implements the
11756 /// fallback case from AnalyzeComparison.
11757 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11758   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11759   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11760 }
11761 
11762 /// Implements -Wsign-compare.
11763 ///
11764 /// \param E the binary operator to check for warnings
11765 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11766   // The type the comparison is being performed in.
11767   QualType T = E->getLHS()->getType();
11768 
11769   // Only analyze comparison operators where both sides have been converted to
11770   // the same type.
11771   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11772     return AnalyzeImpConvsInComparison(S, E);
11773 
11774   // Don't analyze value-dependent comparisons directly.
11775   if (E->isValueDependent())
11776     return AnalyzeImpConvsInComparison(S, E);
11777 
11778   Expr *LHS = E->getLHS();
11779   Expr *RHS = E->getRHS();
11780 
11781   if (T->isIntegralType(S.Context)) {
11782     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11783     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11784 
11785     // We don't care about expressions whose result is a constant.
11786     if (RHSValue && LHSValue)
11787       return AnalyzeImpConvsInComparison(S, E);
11788 
11789     // We only care about expressions where just one side is literal
11790     if ((bool)RHSValue ^ (bool)LHSValue) {
11791       // Is the constant on the RHS or LHS?
11792       const bool RhsConstant = (bool)RHSValue;
11793       Expr *Const = RhsConstant ? RHS : LHS;
11794       Expr *Other = RhsConstant ? LHS : RHS;
11795       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11796 
11797       // Check whether an integer constant comparison results in a value
11798       // of 'true' or 'false'.
11799       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11800         return AnalyzeImpConvsInComparison(S, E);
11801     }
11802   }
11803 
11804   if (!T->hasUnsignedIntegerRepresentation()) {
11805     // We don't do anything special if this isn't an unsigned integral
11806     // comparison:  we're only interested in integral comparisons, and
11807     // signed comparisons only happen in cases we don't care to warn about.
11808     return AnalyzeImpConvsInComparison(S, E);
11809   }
11810 
11811   LHS = LHS->IgnoreParenImpCasts();
11812   RHS = RHS->IgnoreParenImpCasts();
11813 
11814   if (!S.getLangOpts().CPlusPlus) {
11815     // Avoid warning about comparison of integers with different signs when
11816     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11817     // the type of `E`.
11818     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11819       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11820     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11821       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11822   }
11823 
11824   // Check to see if one of the (unmodified) operands is of different
11825   // signedness.
11826   Expr *signedOperand, *unsignedOperand;
11827   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11828     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11829            "unsigned comparison between two signed integer expressions?");
11830     signedOperand = LHS;
11831     unsignedOperand = RHS;
11832   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11833     signedOperand = RHS;
11834     unsignedOperand = LHS;
11835   } else {
11836     return AnalyzeImpConvsInComparison(S, E);
11837   }
11838 
11839   // Otherwise, calculate the effective range of the signed operand.
11840   IntRange signedRange = GetExprRange(
11841       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11842 
11843   // Go ahead and analyze implicit conversions in the operands.  Note
11844   // that we skip the implicit conversions on both sides.
11845   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11846   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11847 
11848   // If the signed range is non-negative, -Wsign-compare won't fire.
11849   if (signedRange.NonNegative)
11850     return;
11851 
11852   // For (in)equality comparisons, if the unsigned operand is a
11853   // constant which cannot collide with a overflowed signed operand,
11854   // then reinterpreting the signed operand as unsigned will not
11855   // change the result of the comparison.
11856   if (E->isEqualityOp()) {
11857     unsigned comparisonWidth = S.Context.getIntWidth(T);
11858     IntRange unsignedRange =
11859         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11860                      /*Approximate*/ true);
11861 
11862     // We should never be unable to prove that the unsigned operand is
11863     // non-negative.
11864     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11865 
11866     if (unsignedRange.Width < comparisonWidth)
11867       return;
11868   }
11869 
11870   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11871                         S.PDiag(diag::warn_mixed_sign_comparison)
11872                             << LHS->getType() << RHS->getType()
11873                             << LHS->getSourceRange() << RHS->getSourceRange());
11874 }
11875 
11876 /// Analyzes an attempt to assign the given value to a bitfield.
11877 ///
11878 /// Returns true if there was something fishy about the attempt.
11879 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11880                                       SourceLocation InitLoc) {
11881   assert(Bitfield->isBitField());
11882   if (Bitfield->isInvalidDecl())
11883     return false;
11884 
11885   // White-list bool bitfields.
11886   QualType BitfieldType = Bitfield->getType();
11887   if (BitfieldType->isBooleanType())
11888      return false;
11889 
11890   if (BitfieldType->isEnumeralType()) {
11891     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11892     // If the underlying enum type was not explicitly specified as an unsigned
11893     // type and the enum contain only positive values, MSVC++ will cause an
11894     // inconsistency by storing this as a signed type.
11895     if (S.getLangOpts().CPlusPlus11 &&
11896         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11897         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11898         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11899       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11900           << BitfieldEnumDecl;
11901     }
11902   }
11903 
11904   if (Bitfield->getType()->isBooleanType())
11905     return false;
11906 
11907   // Ignore value- or type-dependent expressions.
11908   if (Bitfield->getBitWidth()->isValueDependent() ||
11909       Bitfield->getBitWidth()->isTypeDependent() ||
11910       Init->isValueDependent() ||
11911       Init->isTypeDependent())
11912     return false;
11913 
11914   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11915   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11916 
11917   Expr::EvalResult Result;
11918   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11919                                    Expr::SE_AllowSideEffects)) {
11920     // The RHS is not constant.  If the RHS has an enum type, make sure the
11921     // bitfield is wide enough to hold all the values of the enum without
11922     // truncation.
11923     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11924       EnumDecl *ED = EnumTy->getDecl();
11925       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11926 
11927       // Enum types are implicitly signed on Windows, so check if there are any
11928       // negative enumerators to see if the enum was intended to be signed or
11929       // not.
11930       bool SignedEnum = ED->getNumNegativeBits() > 0;
11931 
11932       // Check for surprising sign changes when assigning enum values to a
11933       // bitfield of different signedness.  If the bitfield is signed and we
11934       // have exactly the right number of bits to store this unsigned enum,
11935       // suggest changing the enum to an unsigned type. This typically happens
11936       // on Windows where unfixed enums always use an underlying type of 'int'.
11937       unsigned DiagID = 0;
11938       if (SignedEnum && !SignedBitfield) {
11939         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11940       } else if (SignedBitfield && !SignedEnum &&
11941                  ED->getNumPositiveBits() == FieldWidth) {
11942         DiagID = diag::warn_signed_bitfield_enum_conversion;
11943       }
11944 
11945       if (DiagID) {
11946         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11947         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11948         SourceRange TypeRange =
11949             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11950         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11951             << SignedEnum << TypeRange;
11952       }
11953 
11954       // Compute the required bitwidth. If the enum has negative values, we need
11955       // one more bit than the normal number of positive bits to represent the
11956       // sign bit.
11957       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11958                                                   ED->getNumNegativeBits())
11959                                        : ED->getNumPositiveBits();
11960 
11961       // Check the bitwidth.
11962       if (BitsNeeded > FieldWidth) {
11963         Expr *WidthExpr = Bitfield->getBitWidth();
11964         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11965             << Bitfield << ED;
11966         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11967             << BitsNeeded << ED << WidthExpr->getSourceRange();
11968       }
11969     }
11970 
11971     return false;
11972   }
11973 
11974   llvm::APSInt Value = Result.Val.getInt();
11975 
11976   unsigned OriginalWidth = Value.getBitWidth();
11977 
11978   if (!Value.isSigned() || Value.isNegative())
11979     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11980       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11981         OriginalWidth = Value.getMinSignedBits();
11982 
11983   if (OriginalWidth <= FieldWidth)
11984     return false;
11985 
11986   // Compute the value which the bitfield will contain.
11987   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11988   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11989 
11990   // Check whether the stored value is equal to the original value.
11991   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11992   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11993     return false;
11994 
11995   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11996   // therefore don't strictly fit into a signed bitfield of width 1.
11997   if (FieldWidth == 1 && Value == 1)
11998     return false;
11999 
12000   std::string PrettyValue = toString(Value, 10);
12001   std::string PrettyTrunc = toString(TruncatedValue, 10);
12002 
12003   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12004     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12005     << Init->getSourceRange();
12006 
12007   return true;
12008 }
12009 
12010 /// Analyze the given simple or compound assignment for warning-worthy
12011 /// operations.
12012 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12013   // Just recurse on the LHS.
12014   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12015 
12016   // We want to recurse on the RHS as normal unless we're assigning to
12017   // a bitfield.
12018   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12019     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12020                                   E->getOperatorLoc())) {
12021       // Recurse, ignoring any implicit conversions on the RHS.
12022       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12023                                         E->getOperatorLoc());
12024     }
12025   }
12026 
12027   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12028 
12029   // Diagnose implicitly sequentially-consistent atomic assignment.
12030   if (E->getLHS()->getType()->isAtomicType())
12031     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12032 }
12033 
12034 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12035 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12036                             SourceLocation CContext, unsigned diag,
12037                             bool pruneControlFlow = false) {
12038   if (pruneControlFlow) {
12039     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12040                           S.PDiag(diag)
12041                               << SourceType << T << E->getSourceRange()
12042                               << SourceRange(CContext));
12043     return;
12044   }
12045   S.Diag(E->getExprLoc(), diag)
12046     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12047 }
12048 
12049 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12050 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12051                             SourceLocation CContext,
12052                             unsigned diag, bool pruneControlFlow = false) {
12053   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12054 }
12055 
12056 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12057   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12058       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12059 }
12060 
12061 static void adornObjCBoolConversionDiagWithTernaryFixit(
12062     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12063   Expr *Ignored = SourceExpr->IgnoreImplicit();
12064   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12065     Ignored = OVE->getSourceExpr();
12066   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12067                      isa<BinaryOperator>(Ignored) ||
12068                      isa<CXXOperatorCallExpr>(Ignored);
12069   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12070   if (NeedsParens)
12071     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12072             << FixItHint::CreateInsertion(EndLoc, ")");
12073   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12074 }
12075 
12076 /// Diagnose an implicit cast from a floating point value to an integer value.
12077 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12078                                     SourceLocation CContext) {
12079   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12080   const bool PruneWarnings = S.inTemplateInstantiation();
12081 
12082   Expr *InnerE = E->IgnoreParenImpCasts();
12083   // We also want to warn on, e.g., "int i = -1.234"
12084   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12085     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12086       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12087 
12088   const bool IsLiteral =
12089       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12090 
12091   llvm::APFloat Value(0.0);
12092   bool IsConstant =
12093     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12094   if (!IsConstant) {
12095     if (isObjCSignedCharBool(S, T)) {
12096       return adornObjCBoolConversionDiagWithTernaryFixit(
12097           S, E,
12098           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12099               << E->getType());
12100     }
12101 
12102     return DiagnoseImpCast(S, E, T, CContext,
12103                            diag::warn_impcast_float_integer, PruneWarnings);
12104   }
12105 
12106   bool isExact = false;
12107 
12108   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12109                             T->hasUnsignedIntegerRepresentation());
12110   llvm::APFloat::opStatus Result = Value.convertToInteger(
12111       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12112 
12113   // FIXME: Force the precision of the source value down so we don't print
12114   // digits which are usually useless (we don't really care here if we
12115   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12116   // would automatically print the shortest representation, but it's a bit
12117   // tricky to implement.
12118   SmallString<16> PrettySourceValue;
12119   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12120   precision = (precision * 59 + 195) / 196;
12121   Value.toString(PrettySourceValue, precision);
12122 
12123   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12124     return adornObjCBoolConversionDiagWithTernaryFixit(
12125         S, E,
12126         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12127             << PrettySourceValue);
12128   }
12129 
12130   if (Result == llvm::APFloat::opOK && isExact) {
12131     if (IsLiteral) return;
12132     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12133                            PruneWarnings);
12134   }
12135 
12136   // Conversion of a floating-point value to a non-bool integer where the
12137   // integral part cannot be represented by the integer type is undefined.
12138   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12139     return DiagnoseImpCast(
12140         S, E, T, CContext,
12141         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12142                   : diag::warn_impcast_float_to_integer_out_of_range,
12143         PruneWarnings);
12144 
12145   unsigned DiagID = 0;
12146   if (IsLiteral) {
12147     // Warn on floating point literal to integer.
12148     DiagID = diag::warn_impcast_literal_float_to_integer;
12149   } else if (IntegerValue == 0) {
12150     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12151       return DiagnoseImpCast(S, E, T, CContext,
12152                              diag::warn_impcast_float_integer, PruneWarnings);
12153     }
12154     // Warn on non-zero to zero conversion.
12155     DiagID = diag::warn_impcast_float_to_integer_zero;
12156   } else {
12157     if (IntegerValue.isUnsigned()) {
12158       if (!IntegerValue.isMaxValue()) {
12159         return DiagnoseImpCast(S, E, T, CContext,
12160                                diag::warn_impcast_float_integer, PruneWarnings);
12161       }
12162     } else {  // IntegerValue.isSigned()
12163       if (!IntegerValue.isMaxSignedValue() &&
12164           !IntegerValue.isMinSignedValue()) {
12165         return DiagnoseImpCast(S, E, T, CContext,
12166                                diag::warn_impcast_float_integer, PruneWarnings);
12167       }
12168     }
12169     // Warn on evaluatable floating point expression to integer conversion.
12170     DiagID = diag::warn_impcast_float_to_integer;
12171   }
12172 
12173   SmallString<16> PrettyTargetValue;
12174   if (IsBool)
12175     PrettyTargetValue = Value.isZero() ? "false" : "true";
12176   else
12177     IntegerValue.toString(PrettyTargetValue);
12178 
12179   if (PruneWarnings) {
12180     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12181                           S.PDiag(DiagID)
12182                               << E->getType() << T.getUnqualifiedType()
12183                               << PrettySourceValue << PrettyTargetValue
12184                               << E->getSourceRange() << SourceRange(CContext));
12185   } else {
12186     S.Diag(E->getExprLoc(), DiagID)
12187         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12188         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12189   }
12190 }
12191 
12192 /// Analyze the given compound assignment for the possible losing of
12193 /// floating-point precision.
12194 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12195   assert(isa<CompoundAssignOperator>(E) &&
12196          "Must be compound assignment operation");
12197   // Recurse on the LHS and RHS in here
12198   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12199   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12200 
12201   if (E->getLHS()->getType()->isAtomicType())
12202     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12203 
12204   // Now check the outermost expression
12205   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12206   const auto *RBT = cast<CompoundAssignOperator>(E)
12207                         ->getComputationResultType()
12208                         ->getAs<BuiltinType>();
12209 
12210   // The below checks assume source is floating point.
12211   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12212 
12213   // If source is floating point but target is an integer.
12214   if (ResultBT->isInteger())
12215     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12216                            E->getExprLoc(), diag::warn_impcast_float_integer);
12217 
12218   if (!ResultBT->isFloatingPoint())
12219     return;
12220 
12221   // If both source and target are floating points, warn about losing precision.
12222   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12223       QualType(ResultBT, 0), QualType(RBT, 0));
12224   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12225     // warn about dropping FP rank.
12226     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12227                     diag::warn_impcast_float_result_precision);
12228 }
12229 
12230 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12231                                       IntRange Range) {
12232   if (!Range.Width) return "0";
12233 
12234   llvm::APSInt ValueInRange = Value;
12235   ValueInRange.setIsSigned(!Range.NonNegative);
12236   ValueInRange = ValueInRange.trunc(Range.Width);
12237   return toString(ValueInRange, 10);
12238 }
12239 
12240 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12241   if (!isa<ImplicitCastExpr>(Ex))
12242     return false;
12243 
12244   Expr *InnerE = Ex->IgnoreParenImpCasts();
12245   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12246   const Type *Source =
12247     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12248   if (Target->isDependentType())
12249     return false;
12250 
12251   const BuiltinType *FloatCandidateBT =
12252     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12253   const Type *BoolCandidateType = ToBool ? Target : Source;
12254 
12255   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12256           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12257 }
12258 
12259 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12260                                              SourceLocation CC) {
12261   unsigned NumArgs = TheCall->getNumArgs();
12262   for (unsigned i = 0; i < NumArgs; ++i) {
12263     Expr *CurrA = TheCall->getArg(i);
12264     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12265       continue;
12266 
12267     bool IsSwapped = ((i > 0) &&
12268         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12269     IsSwapped |= ((i < (NumArgs - 1)) &&
12270         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12271     if (IsSwapped) {
12272       // Warn on this floating-point to bool conversion.
12273       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12274                       CurrA->getType(), CC,
12275                       diag::warn_impcast_floating_point_to_bool);
12276     }
12277   }
12278 }
12279 
12280 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12281                                    SourceLocation CC) {
12282   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12283                         E->getExprLoc()))
12284     return;
12285 
12286   // Don't warn on functions which have return type nullptr_t.
12287   if (isa<CallExpr>(E))
12288     return;
12289 
12290   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12291   const Expr::NullPointerConstantKind NullKind =
12292       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12293   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12294     return;
12295 
12296   // Return if target type is a safe conversion.
12297   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12298       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12299     return;
12300 
12301   SourceLocation Loc = E->getSourceRange().getBegin();
12302 
12303   // Venture through the macro stacks to get to the source of macro arguments.
12304   // The new location is a better location than the complete location that was
12305   // passed in.
12306   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12307   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12308 
12309   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12310   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12311     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12312         Loc, S.SourceMgr, S.getLangOpts());
12313     if (MacroName == "NULL")
12314       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12315   }
12316 
12317   // Only warn if the null and context location are in the same macro expansion.
12318   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12319     return;
12320 
12321   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12322       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12323       << FixItHint::CreateReplacement(Loc,
12324                                       S.getFixItZeroLiteralForType(T, Loc));
12325 }
12326 
12327 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12328                                   ObjCArrayLiteral *ArrayLiteral);
12329 
12330 static void
12331 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12332                            ObjCDictionaryLiteral *DictionaryLiteral);
12333 
12334 /// Check a single element within a collection literal against the
12335 /// target element type.
12336 static void checkObjCCollectionLiteralElement(Sema &S,
12337                                               QualType TargetElementType,
12338                                               Expr *Element,
12339                                               unsigned ElementKind) {
12340   // Skip a bitcast to 'id' or qualified 'id'.
12341   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12342     if (ICE->getCastKind() == CK_BitCast &&
12343         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12344       Element = ICE->getSubExpr();
12345   }
12346 
12347   QualType ElementType = Element->getType();
12348   ExprResult ElementResult(Element);
12349   if (ElementType->getAs<ObjCObjectPointerType>() &&
12350       S.CheckSingleAssignmentConstraints(TargetElementType,
12351                                          ElementResult,
12352                                          false, false)
12353         != Sema::Compatible) {
12354     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12355         << ElementType << ElementKind << TargetElementType
12356         << Element->getSourceRange();
12357   }
12358 
12359   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12360     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12361   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12362     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12363 }
12364 
12365 /// Check an Objective-C array literal being converted to the given
12366 /// target type.
12367 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12368                                   ObjCArrayLiteral *ArrayLiteral) {
12369   if (!S.NSArrayDecl)
12370     return;
12371 
12372   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12373   if (!TargetObjCPtr)
12374     return;
12375 
12376   if (TargetObjCPtr->isUnspecialized() ||
12377       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12378         != S.NSArrayDecl->getCanonicalDecl())
12379     return;
12380 
12381   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12382   if (TypeArgs.size() != 1)
12383     return;
12384 
12385   QualType TargetElementType = TypeArgs[0];
12386   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12387     checkObjCCollectionLiteralElement(S, TargetElementType,
12388                                       ArrayLiteral->getElement(I),
12389                                       0);
12390   }
12391 }
12392 
12393 /// Check an Objective-C dictionary literal being converted to the given
12394 /// target type.
12395 static void
12396 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12397                            ObjCDictionaryLiteral *DictionaryLiteral) {
12398   if (!S.NSDictionaryDecl)
12399     return;
12400 
12401   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12402   if (!TargetObjCPtr)
12403     return;
12404 
12405   if (TargetObjCPtr->isUnspecialized() ||
12406       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12407         != S.NSDictionaryDecl->getCanonicalDecl())
12408     return;
12409 
12410   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12411   if (TypeArgs.size() != 2)
12412     return;
12413 
12414   QualType TargetKeyType = TypeArgs[0];
12415   QualType TargetObjectType = TypeArgs[1];
12416   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12417     auto Element = DictionaryLiteral->getKeyValueElement(I);
12418     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12419     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12420   }
12421 }
12422 
12423 // Helper function to filter out cases for constant width constant conversion.
12424 // Don't warn on char array initialization or for non-decimal values.
12425 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12426                                           SourceLocation CC) {
12427   // If initializing from a constant, and the constant starts with '0',
12428   // then it is a binary, octal, or hexadecimal.  Allow these constants
12429   // to fill all the bits, even if there is a sign change.
12430   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12431     const char FirstLiteralCharacter =
12432         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12433     if (FirstLiteralCharacter == '0')
12434       return false;
12435   }
12436 
12437   // If the CC location points to a '{', and the type is char, then assume
12438   // assume it is an array initialization.
12439   if (CC.isValid() && T->isCharType()) {
12440     const char FirstContextCharacter =
12441         S.getSourceManager().getCharacterData(CC)[0];
12442     if (FirstContextCharacter == '{')
12443       return false;
12444   }
12445 
12446   return true;
12447 }
12448 
12449 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12450   const auto *IL = dyn_cast<IntegerLiteral>(E);
12451   if (!IL) {
12452     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12453       if (UO->getOpcode() == UO_Minus)
12454         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12455     }
12456   }
12457 
12458   return IL;
12459 }
12460 
12461 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12462   E = E->IgnoreParenImpCasts();
12463   SourceLocation ExprLoc = E->getExprLoc();
12464 
12465   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12466     BinaryOperator::Opcode Opc = BO->getOpcode();
12467     Expr::EvalResult Result;
12468     // Do not diagnose unsigned shifts.
12469     if (Opc == BO_Shl) {
12470       const auto *LHS = getIntegerLiteral(BO->getLHS());
12471       const auto *RHS = getIntegerLiteral(BO->getRHS());
12472       if (LHS && LHS->getValue() == 0)
12473         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12474       else if (!E->isValueDependent() && LHS && RHS &&
12475                RHS->getValue().isNonNegative() &&
12476                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12477         S.Diag(ExprLoc, diag::warn_left_shift_always)
12478             << (Result.Val.getInt() != 0);
12479       else if (E->getType()->isSignedIntegerType())
12480         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12481     }
12482   }
12483 
12484   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12485     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12486     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12487     if (!LHS || !RHS)
12488       return;
12489     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12490         (RHS->getValue() == 0 || RHS->getValue() == 1))
12491       // Do not diagnose common idioms.
12492       return;
12493     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12494       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12495   }
12496 }
12497 
12498 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12499                                     SourceLocation CC,
12500                                     bool *ICContext = nullptr,
12501                                     bool IsListInit = false) {
12502   if (E->isTypeDependent() || E->isValueDependent()) return;
12503 
12504   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12505   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12506   if (Source == Target) return;
12507   if (Target->isDependentType()) return;
12508 
12509   // If the conversion context location is invalid don't complain. We also
12510   // don't want to emit a warning if the issue occurs from the expansion of
12511   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12512   // delay this check as long as possible. Once we detect we are in that
12513   // scenario, we just return.
12514   if (CC.isInvalid())
12515     return;
12516 
12517   if (Source->isAtomicType())
12518     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12519 
12520   // Diagnose implicit casts to bool.
12521   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12522     if (isa<StringLiteral>(E))
12523       // Warn on string literal to bool.  Checks for string literals in logical
12524       // and expressions, for instance, assert(0 && "error here"), are
12525       // prevented by a check in AnalyzeImplicitConversions().
12526       return DiagnoseImpCast(S, E, T, CC,
12527                              diag::warn_impcast_string_literal_to_bool);
12528     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12529         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12530       // This covers the literal expressions that evaluate to Objective-C
12531       // objects.
12532       return DiagnoseImpCast(S, E, T, CC,
12533                              diag::warn_impcast_objective_c_literal_to_bool);
12534     }
12535     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12536       // Warn on pointer to bool conversion that is always true.
12537       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12538                                      SourceRange(CC));
12539     }
12540   }
12541 
12542   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12543   // is a typedef for signed char (macOS), then that constant value has to be 1
12544   // or 0.
12545   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12546     Expr::EvalResult Result;
12547     if (E->EvaluateAsInt(Result, S.getASTContext(),
12548                          Expr::SE_AllowSideEffects)) {
12549       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12550         adornObjCBoolConversionDiagWithTernaryFixit(
12551             S, E,
12552             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12553                 << toString(Result.Val.getInt(), 10));
12554       }
12555       return;
12556     }
12557   }
12558 
12559   // Check implicit casts from Objective-C collection literals to specialized
12560   // collection types, e.g., NSArray<NSString *> *.
12561   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12562     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12563   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12564     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12565 
12566   // Strip vector types.
12567   if (const auto *SourceVT = dyn_cast<VectorType>(Source)) {
12568     if (Target->isVLSTBuiltinType()) {
12569       auto SourceVectorKind = SourceVT->getVectorKind();
12570       if (SourceVectorKind == VectorType::SveFixedLengthDataVector ||
12571           SourceVectorKind == VectorType::SveFixedLengthPredicateVector ||
12572           (SourceVectorKind == VectorType::GenericVector &&
12573            S.Context.getTypeSize(Source) == S.getLangOpts().ArmSveVectorBits))
12574         return;
12575     }
12576 
12577     if (!isa<VectorType>(Target)) {
12578       if (S.SourceMgr.isInSystemMacro(CC))
12579         return;
12580       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12581     }
12582 
12583     // If the vector cast is cast between two vectors of the same size, it is
12584     // a bitcast, not a conversion.
12585     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12586       return;
12587 
12588     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12589     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12590   }
12591   if (auto VecTy = dyn_cast<VectorType>(Target))
12592     Target = VecTy->getElementType().getTypePtr();
12593 
12594   // Strip complex types.
12595   if (isa<ComplexType>(Source)) {
12596     if (!isa<ComplexType>(Target)) {
12597       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12598         return;
12599 
12600       return DiagnoseImpCast(S, E, T, CC,
12601                              S.getLangOpts().CPlusPlus
12602                                  ? diag::err_impcast_complex_scalar
12603                                  : diag::warn_impcast_complex_scalar);
12604     }
12605 
12606     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12607     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12608   }
12609 
12610   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12611   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12612 
12613   // If the source is floating point...
12614   if (SourceBT && SourceBT->isFloatingPoint()) {
12615     // ...and the target is floating point...
12616     if (TargetBT && TargetBT->isFloatingPoint()) {
12617       // ...then warn if we're dropping FP rank.
12618 
12619       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12620           QualType(SourceBT, 0), QualType(TargetBT, 0));
12621       if (Order > 0) {
12622         // Don't warn about float constants that are precisely
12623         // representable in the target type.
12624         Expr::EvalResult result;
12625         if (E->EvaluateAsRValue(result, S.Context)) {
12626           // Value might be a float, a float vector, or a float complex.
12627           if (IsSameFloatAfterCast(result.Val,
12628                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12629                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12630             return;
12631         }
12632 
12633         if (S.SourceMgr.isInSystemMacro(CC))
12634           return;
12635 
12636         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12637       }
12638       // ... or possibly if we're increasing rank, too
12639       else if (Order < 0) {
12640         if (S.SourceMgr.isInSystemMacro(CC))
12641           return;
12642 
12643         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12644       }
12645       return;
12646     }
12647 
12648     // If the target is integral, always warn.
12649     if (TargetBT && TargetBT->isInteger()) {
12650       if (S.SourceMgr.isInSystemMacro(CC))
12651         return;
12652 
12653       DiagnoseFloatingImpCast(S, E, T, CC);
12654     }
12655 
12656     // Detect the case where a call result is converted from floating-point to
12657     // to bool, and the final argument to the call is converted from bool, to
12658     // discover this typo:
12659     //
12660     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12661     //
12662     // FIXME: This is an incredibly special case; is there some more general
12663     // way to detect this class of misplaced-parentheses bug?
12664     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12665       // Check last argument of function call to see if it is an
12666       // implicit cast from a type matching the type the result
12667       // is being cast to.
12668       CallExpr *CEx = cast<CallExpr>(E);
12669       if (unsigned NumArgs = CEx->getNumArgs()) {
12670         Expr *LastA = CEx->getArg(NumArgs - 1);
12671         Expr *InnerE = LastA->IgnoreParenImpCasts();
12672         if (isa<ImplicitCastExpr>(LastA) &&
12673             InnerE->getType()->isBooleanType()) {
12674           // Warn on this floating-point to bool conversion
12675           DiagnoseImpCast(S, E, T, CC,
12676                           diag::warn_impcast_floating_point_to_bool);
12677         }
12678       }
12679     }
12680     return;
12681   }
12682 
12683   // Valid casts involving fixed point types should be accounted for here.
12684   if (Source->isFixedPointType()) {
12685     if (Target->isUnsaturatedFixedPointType()) {
12686       Expr::EvalResult Result;
12687       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12688                                   S.isConstantEvaluated())) {
12689         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12690         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12691         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12692         if (Value > MaxVal || Value < MinVal) {
12693           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12694                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12695                                     << Value.toString() << T
12696                                     << E->getSourceRange()
12697                                     << clang::SourceRange(CC));
12698           return;
12699         }
12700       }
12701     } else if (Target->isIntegerType()) {
12702       Expr::EvalResult Result;
12703       if (!S.isConstantEvaluated() &&
12704           E->EvaluateAsFixedPoint(Result, S.Context,
12705                                   Expr::SE_AllowSideEffects)) {
12706         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12707 
12708         bool Overflowed;
12709         llvm::APSInt IntResult = FXResult.convertToInt(
12710             S.Context.getIntWidth(T),
12711             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12712 
12713         if (Overflowed) {
12714           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12715                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12716                                     << FXResult.toString() << T
12717                                     << E->getSourceRange()
12718                                     << clang::SourceRange(CC));
12719           return;
12720         }
12721       }
12722     }
12723   } else if (Target->isUnsaturatedFixedPointType()) {
12724     if (Source->isIntegerType()) {
12725       Expr::EvalResult Result;
12726       if (!S.isConstantEvaluated() &&
12727           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12728         llvm::APSInt Value = Result.Val.getInt();
12729 
12730         bool Overflowed;
12731         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12732             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12733 
12734         if (Overflowed) {
12735           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12736                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12737                                     << toString(Value, /*Radix=*/10) << T
12738                                     << E->getSourceRange()
12739                                     << clang::SourceRange(CC));
12740           return;
12741         }
12742       }
12743     }
12744   }
12745 
12746   // If we are casting an integer type to a floating point type without
12747   // initialization-list syntax, we might lose accuracy if the floating
12748   // point type has a narrower significand than the integer type.
12749   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12750       TargetBT->isFloatingType() && !IsListInit) {
12751     // Determine the number of precision bits in the source integer type.
12752     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12753                                         /*Approximate*/ true);
12754     unsigned int SourcePrecision = SourceRange.Width;
12755 
12756     // Determine the number of precision bits in the
12757     // target floating point type.
12758     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12759         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12760 
12761     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12762         SourcePrecision > TargetPrecision) {
12763 
12764       if (Optional<llvm::APSInt> SourceInt =
12765               E->getIntegerConstantExpr(S.Context)) {
12766         // If the source integer is a constant, convert it to the target
12767         // floating point type. Issue a warning if the value changes
12768         // during the whole conversion.
12769         llvm::APFloat TargetFloatValue(
12770             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12771         llvm::APFloat::opStatus ConversionStatus =
12772             TargetFloatValue.convertFromAPInt(
12773                 *SourceInt, SourceBT->isSignedInteger(),
12774                 llvm::APFloat::rmNearestTiesToEven);
12775 
12776         if (ConversionStatus != llvm::APFloat::opOK) {
12777           SmallString<32> PrettySourceValue;
12778           SourceInt->toString(PrettySourceValue, 10);
12779           SmallString<32> PrettyTargetValue;
12780           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12781 
12782           S.DiagRuntimeBehavior(
12783               E->getExprLoc(), E,
12784               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12785                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12786                   << E->getSourceRange() << clang::SourceRange(CC));
12787         }
12788       } else {
12789         // Otherwise, the implicit conversion may lose precision.
12790         DiagnoseImpCast(S, E, T, CC,
12791                         diag::warn_impcast_integer_float_precision);
12792       }
12793     }
12794   }
12795 
12796   DiagnoseNullConversion(S, E, T, CC);
12797 
12798   S.DiscardMisalignedMemberAddress(Target, E);
12799 
12800   if (Target->isBooleanType())
12801     DiagnoseIntInBoolContext(S, E);
12802 
12803   if (!Source->isIntegerType() || !Target->isIntegerType())
12804     return;
12805 
12806   // TODO: remove this early return once the false positives for constant->bool
12807   // in templates, macros, etc, are reduced or removed.
12808   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12809     return;
12810 
12811   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12812       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12813     return adornObjCBoolConversionDiagWithTernaryFixit(
12814         S, E,
12815         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12816             << E->getType());
12817   }
12818 
12819   IntRange SourceTypeRange =
12820       IntRange::forTargetOfCanonicalType(S.Context, Source);
12821   IntRange LikelySourceRange =
12822       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12823   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12824 
12825   if (LikelySourceRange.Width > TargetRange.Width) {
12826     // If the source is a constant, use a default-on diagnostic.
12827     // TODO: this should happen for bitfield stores, too.
12828     Expr::EvalResult Result;
12829     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12830                          S.isConstantEvaluated())) {
12831       llvm::APSInt Value(32);
12832       Value = Result.Val.getInt();
12833 
12834       if (S.SourceMgr.isInSystemMacro(CC))
12835         return;
12836 
12837       std::string PrettySourceValue = toString(Value, 10);
12838       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12839 
12840       S.DiagRuntimeBehavior(
12841           E->getExprLoc(), E,
12842           S.PDiag(diag::warn_impcast_integer_precision_constant)
12843               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12844               << E->getSourceRange() << SourceRange(CC));
12845       return;
12846     }
12847 
12848     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12849     if (S.SourceMgr.isInSystemMacro(CC))
12850       return;
12851 
12852     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12853       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12854                              /* pruneControlFlow */ true);
12855     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12856   }
12857 
12858   if (TargetRange.Width > SourceTypeRange.Width) {
12859     if (auto *UO = dyn_cast<UnaryOperator>(E))
12860       if (UO->getOpcode() == UO_Minus)
12861         if (Source->isUnsignedIntegerType()) {
12862           if (Target->isUnsignedIntegerType())
12863             return DiagnoseImpCast(S, E, T, CC,
12864                                    diag::warn_impcast_high_order_zero_bits);
12865           if (Target->isSignedIntegerType())
12866             return DiagnoseImpCast(S, E, T, CC,
12867                                    diag::warn_impcast_nonnegative_result);
12868         }
12869   }
12870 
12871   if (TargetRange.Width == LikelySourceRange.Width &&
12872       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12873       Source->isSignedIntegerType()) {
12874     // Warn when doing a signed to signed conversion, warn if the positive
12875     // source value is exactly the width of the target type, which will
12876     // cause a negative value to be stored.
12877 
12878     Expr::EvalResult Result;
12879     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12880         !S.SourceMgr.isInSystemMacro(CC)) {
12881       llvm::APSInt Value = Result.Val.getInt();
12882       if (isSameWidthConstantConversion(S, E, T, CC)) {
12883         std::string PrettySourceValue = toString(Value, 10);
12884         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12885 
12886         S.DiagRuntimeBehavior(
12887             E->getExprLoc(), E,
12888             S.PDiag(diag::warn_impcast_integer_precision_constant)
12889                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12890                 << E->getSourceRange() << SourceRange(CC));
12891         return;
12892       }
12893     }
12894 
12895     // Fall through for non-constants to give a sign conversion warning.
12896   }
12897 
12898   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12899       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12900        LikelySourceRange.Width == TargetRange.Width)) {
12901     if (S.SourceMgr.isInSystemMacro(CC))
12902       return;
12903 
12904     unsigned DiagID = diag::warn_impcast_integer_sign;
12905 
12906     // Traditionally, gcc has warned about this under -Wsign-compare.
12907     // We also want to warn about it in -Wconversion.
12908     // So if -Wconversion is off, use a completely identical diagnostic
12909     // in the sign-compare group.
12910     // The conditional-checking code will
12911     if (ICContext) {
12912       DiagID = diag::warn_impcast_integer_sign_conditional;
12913       *ICContext = true;
12914     }
12915 
12916     return DiagnoseImpCast(S, E, T, CC, DiagID);
12917   }
12918 
12919   // Diagnose conversions between different enumeration types.
12920   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12921   // type, to give us better diagnostics.
12922   QualType SourceType = E->getType();
12923   if (!S.getLangOpts().CPlusPlus) {
12924     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12925       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12926         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12927         SourceType = S.Context.getTypeDeclType(Enum);
12928         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12929       }
12930   }
12931 
12932   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12933     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12934       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12935           TargetEnum->getDecl()->hasNameForLinkage() &&
12936           SourceEnum != TargetEnum) {
12937         if (S.SourceMgr.isInSystemMacro(CC))
12938           return;
12939 
12940         return DiagnoseImpCast(S, E, SourceType, T, CC,
12941                                diag::warn_impcast_different_enum_types);
12942       }
12943 }
12944 
12945 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12946                                      SourceLocation CC, QualType T);
12947 
12948 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12949                                     SourceLocation CC, bool &ICContext) {
12950   E = E->IgnoreParenImpCasts();
12951 
12952   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12953     return CheckConditionalOperator(S, CO, CC, T);
12954 
12955   AnalyzeImplicitConversions(S, E, CC);
12956   if (E->getType() != T)
12957     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12958 }
12959 
12960 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12961                                      SourceLocation CC, QualType T) {
12962   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12963 
12964   Expr *TrueExpr = E->getTrueExpr();
12965   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12966     TrueExpr = BCO->getCommon();
12967 
12968   bool Suspicious = false;
12969   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12970   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12971 
12972   if (T->isBooleanType())
12973     DiagnoseIntInBoolContext(S, E);
12974 
12975   // If -Wconversion would have warned about either of the candidates
12976   // for a signedness conversion to the context type...
12977   if (!Suspicious) return;
12978 
12979   // ...but it's currently ignored...
12980   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12981     return;
12982 
12983   // ...then check whether it would have warned about either of the
12984   // candidates for a signedness conversion to the condition type.
12985   if (E->getType() == T) return;
12986 
12987   Suspicious = false;
12988   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12989                           E->getType(), CC, &Suspicious);
12990   if (!Suspicious)
12991     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12992                             E->getType(), CC, &Suspicious);
12993 }
12994 
12995 /// Check conversion of given expression to boolean.
12996 /// Input argument E is a logical expression.
12997 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12998   if (S.getLangOpts().Bool)
12999     return;
13000   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13001     return;
13002   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13003 }
13004 
13005 namespace {
13006 struct AnalyzeImplicitConversionsWorkItem {
13007   Expr *E;
13008   SourceLocation CC;
13009   bool IsListInit;
13010 };
13011 }
13012 
13013 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13014 /// that should be visited are added to WorkList.
13015 static void AnalyzeImplicitConversions(
13016     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13017     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13018   Expr *OrigE = Item.E;
13019   SourceLocation CC = Item.CC;
13020 
13021   QualType T = OrigE->getType();
13022   Expr *E = OrigE->IgnoreParenImpCasts();
13023 
13024   // Propagate whether we are in a C++ list initialization expression.
13025   // If so, we do not issue warnings for implicit int-float conversion
13026   // precision loss, because C++11 narrowing already handles it.
13027   bool IsListInit = Item.IsListInit ||
13028                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13029 
13030   if (E->isTypeDependent() || E->isValueDependent())
13031     return;
13032 
13033   Expr *SourceExpr = E;
13034   // Examine, but don't traverse into the source expression of an
13035   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13036   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13037   // evaluate it in the context of checking the specific conversion to T though.
13038   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13039     if (auto *Src = OVE->getSourceExpr())
13040       SourceExpr = Src;
13041 
13042   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13043     if (UO->getOpcode() == UO_Not &&
13044         UO->getSubExpr()->isKnownToHaveBooleanValue())
13045       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13046           << OrigE->getSourceRange() << T->isBooleanType()
13047           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13048 
13049   // For conditional operators, we analyze the arguments as if they
13050   // were being fed directly into the output.
13051   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13052     CheckConditionalOperator(S, CO, CC, T);
13053     return;
13054   }
13055 
13056   // Check implicit argument conversions for function calls.
13057   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13058     CheckImplicitArgumentConversions(S, Call, CC);
13059 
13060   // Go ahead and check any implicit conversions we might have skipped.
13061   // The non-canonical typecheck is just an optimization;
13062   // CheckImplicitConversion will filter out dead implicit conversions.
13063   if (SourceExpr->getType() != T)
13064     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13065 
13066   // Now continue drilling into this expression.
13067 
13068   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13069     // The bound subexpressions in a PseudoObjectExpr are not reachable
13070     // as transitive children.
13071     // FIXME: Use a more uniform representation for this.
13072     for (auto *SE : POE->semantics())
13073       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13074         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13075   }
13076 
13077   // Skip past explicit casts.
13078   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13079     E = CE->getSubExpr()->IgnoreParenImpCasts();
13080     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13081       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13082     WorkList.push_back({E, CC, IsListInit});
13083     return;
13084   }
13085 
13086   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13087     // Do a somewhat different check with comparison operators.
13088     if (BO->isComparisonOp())
13089       return AnalyzeComparison(S, BO);
13090 
13091     // And with simple assignments.
13092     if (BO->getOpcode() == BO_Assign)
13093       return AnalyzeAssignment(S, BO);
13094     // And with compound assignments.
13095     if (BO->isAssignmentOp())
13096       return AnalyzeCompoundAssignment(S, BO);
13097   }
13098 
13099   // These break the otherwise-useful invariant below.  Fortunately,
13100   // we don't really need to recurse into them, because any internal
13101   // expressions should have been analyzed already when they were
13102   // built into statements.
13103   if (isa<StmtExpr>(E)) return;
13104 
13105   // Don't descend into unevaluated contexts.
13106   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13107 
13108   // Now just recurse over the expression's children.
13109   CC = E->getExprLoc();
13110   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13111   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13112   for (Stmt *SubStmt : E->children()) {
13113     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13114     if (!ChildExpr)
13115       continue;
13116 
13117     if (IsLogicalAndOperator &&
13118         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13119       // Ignore checking string literals that are in logical and operators.
13120       // This is a common pattern for asserts.
13121       continue;
13122     WorkList.push_back({ChildExpr, CC, IsListInit});
13123   }
13124 
13125   if (BO && BO->isLogicalOp()) {
13126     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13127     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13128       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13129 
13130     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13131     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13132       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13133   }
13134 
13135   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13136     if (U->getOpcode() == UO_LNot) {
13137       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13138     } else if (U->getOpcode() != UO_AddrOf) {
13139       if (U->getSubExpr()->getType()->isAtomicType())
13140         S.Diag(U->getSubExpr()->getBeginLoc(),
13141                diag::warn_atomic_implicit_seq_cst);
13142     }
13143   }
13144 }
13145 
13146 /// AnalyzeImplicitConversions - Find and report any interesting
13147 /// implicit conversions in the given expression.  There are a couple
13148 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13149 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13150                                        bool IsListInit/*= false*/) {
13151   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13152   WorkList.push_back({OrigE, CC, IsListInit});
13153   while (!WorkList.empty())
13154     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13155 }
13156 
13157 /// Diagnose integer type and any valid implicit conversion to it.
13158 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13159   // Taking into account implicit conversions,
13160   // allow any integer.
13161   if (!E->getType()->isIntegerType()) {
13162     S.Diag(E->getBeginLoc(),
13163            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13164     return true;
13165   }
13166   // Potentially emit standard warnings for implicit conversions if enabled
13167   // using -Wconversion.
13168   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13169   return false;
13170 }
13171 
13172 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13173 // Returns true when emitting a warning about taking the address of a reference.
13174 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13175                               const PartialDiagnostic &PD) {
13176   E = E->IgnoreParenImpCasts();
13177 
13178   const FunctionDecl *FD = nullptr;
13179 
13180   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13181     if (!DRE->getDecl()->getType()->isReferenceType())
13182       return false;
13183   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13184     if (!M->getMemberDecl()->getType()->isReferenceType())
13185       return false;
13186   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13187     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13188       return false;
13189     FD = Call->getDirectCallee();
13190   } else {
13191     return false;
13192   }
13193 
13194   SemaRef.Diag(E->getExprLoc(), PD);
13195 
13196   // If possible, point to location of function.
13197   if (FD) {
13198     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13199   }
13200 
13201   return true;
13202 }
13203 
13204 // Returns true if the SourceLocation is expanded from any macro body.
13205 // Returns false if the SourceLocation is invalid, is from not in a macro
13206 // expansion, or is from expanded from a top-level macro argument.
13207 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13208   if (Loc.isInvalid())
13209     return false;
13210 
13211   while (Loc.isMacroID()) {
13212     if (SM.isMacroBodyExpansion(Loc))
13213       return true;
13214     Loc = SM.getImmediateMacroCallerLoc(Loc);
13215   }
13216 
13217   return false;
13218 }
13219 
13220 /// Diagnose pointers that are always non-null.
13221 /// \param E the expression containing the pointer
13222 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13223 /// compared to a null pointer
13224 /// \param IsEqual True when the comparison is equal to a null pointer
13225 /// \param Range Extra SourceRange to highlight in the diagnostic
13226 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13227                                         Expr::NullPointerConstantKind NullKind,
13228                                         bool IsEqual, SourceRange Range) {
13229   if (!E)
13230     return;
13231 
13232   // Don't warn inside macros.
13233   if (E->getExprLoc().isMacroID()) {
13234     const SourceManager &SM = getSourceManager();
13235     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13236         IsInAnyMacroBody(SM, Range.getBegin()))
13237       return;
13238   }
13239   E = E->IgnoreImpCasts();
13240 
13241   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13242 
13243   if (isa<CXXThisExpr>(E)) {
13244     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13245                                 : diag::warn_this_bool_conversion;
13246     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13247     return;
13248   }
13249 
13250   bool IsAddressOf = false;
13251 
13252   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13253     if (UO->getOpcode() != UO_AddrOf)
13254       return;
13255     IsAddressOf = true;
13256     E = UO->getSubExpr();
13257   }
13258 
13259   if (IsAddressOf) {
13260     unsigned DiagID = IsCompare
13261                           ? diag::warn_address_of_reference_null_compare
13262                           : diag::warn_address_of_reference_bool_conversion;
13263     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13264                                          << IsEqual;
13265     if (CheckForReference(*this, E, PD)) {
13266       return;
13267     }
13268   }
13269 
13270   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13271     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13272     std::string Str;
13273     llvm::raw_string_ostream S(Str);
13274     E->printPretty(S, nullptr, getPrintingPolicy());
13275     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13276                                 : diag::warn_cast_nonnull_to_bool;
13277     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13278       << E->getSourceRange() << Range << IsEqual;
13279     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13280   };
13281 
13282   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13283   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13284     if (auto *Callee = Call->getDirectCallee()) {
13285       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13286         ComplainAboutNonnullParamOrCall(A);
13287         return;
13288       }
13289     }
13290   }
13291 
13292   // Expect to find a single Decl.  Skip anything more complicated.
13293   ValueDecl *D = nullptr;
13294   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13295     D = R->getDecl();
13296   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13297     D = M->getMemberDecl();
13298   }
13299 
13300   // Weak Decls can be null.
13301   if (!D || D->isWeak())
13302     return;
13303 
13304   // Check for parameter decl with nonnull attribute
13305   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13306     if (getCurFunction() &&
13307         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13308       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13309         ComplainAboutNonnullParamOrCall(A);
13310         return;
13311       }
13312 
13313       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13314         // Skip function template not specialized yet.
13315         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13316           return;
13317         auto ParamIter = llvm::find(FD->parameters(), PV);
13318         assert(ParamIter != FD->param_end());
13319         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13320 
13321         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13322           if (!NonNull->args_size()) {
13323               ComplainAboutNonnullParamOrCall(NonNull);
13324               return;
13325           }
13326 
13327           for (const ParamIdx &ArgNo : NonNull->args()) {
13328             if (ArgNo.getASTIndex() == ParamNo) {
13329               ComplainAboutNonnullParamOrCall(NonNull);
13330               return;
13331             }
13332           }
13333         }
13334       }
13335     }
13336   }
13337 
13338   QualType T = D->getType();
13339   const bool IsArray = T->isArrayType();
13340   const bool IsFunction = T->isFunctionType();
13341 
13342   // Address of function is used to silence the function warning.
13343   if (IsAddressOf && IsFunction) {
13344     return;
13345   }
13346 
13347   // Found nothing.
13348   if (!IsAddressOf && !IsFunction && !IsArray)
13349     return;
13350 
13351   // Pretty print the expression for the diagnostic.
13352   std::string Str;
13353   llvm::raw_string_ostream S(Str);
13354   E->printPretty(S, nullptr, getPrintingPolicy());
13355 
13356   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13357                               : diag::warn_impcast_pointer_to_bool;
13358   enum {
13359     AddressOf,
13360     FunctionPointer,
13361     ArrayPointer
13362   } DiagType;
13363   if (IsAddressOf)
13364     DiagType = AddressOf;
13365   else if (IsFunction)
13366     DiagType = FunctionPointer;
13367   else if (IsArray)
13368     DiagType = ArrayPointer;
13369   else
13370     llvm_unreachable("Could not determine diagnostic.");
13371   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13372                                 << Range << IsEqual;
13373 
13374   if (!IsFunction)
13375     return;
13376 
13377   // Suggest '&' to silence the function warning.
13378   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13379       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13380 
13381   // Check to see if '()' fixit should be emitted.
13382   QualType ReturnType;
13383   UnresolvedSet<4> NonTemplateOverloads;
13384   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13385   if (ReturnType.isNull())
13386     return;
13387 
13388   if (IsCompare) {
13389     // There are two cases here.  If there is null constant, the only suggest
13390     // for a pointer return type.  If the null is 0, then suggest if the return
13391     // type is a pointer or an integer type.
13392     if (!ReturnType->isPointerType()) {
13393       if (NullKind == Expr::NPCK_ZeroExpression ||
13394           NullKind == Expr::NPCK_ZeroLiteral) {
13395         if (!ReturnType->isIntegerType())
13396           return;
13397       } else {
13398         return;
13399       }
13400     }
13401   } else { // !IsCompare
13402     // For function to bool, only suggest if the function pointer has bool
13403     // return type.
13404     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13405       return;
13406   }
13407   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13408       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13409 }
13410 
13411 /// Diagnoses "dangerous" implicit conversions within the given
13412 /// expression (which is a full expression).  Implements -Wconversion
13413 /// and -Wsign-compare.
13414 ///
13415 /// \param CC the "context" location of the implicit conversion, i.e.
13416 ///   the most location of the syntactic entity requiring the implicit
13417 ///   conversion
13418 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13419   // Don't diagnose in unevaluated contexts.
13420   if (isUnevaluatedContext())
13421     return;
13422 
13423   // Don't diagnose for value- or type-dependent expressions.
13424   if (E->isTypeDependent() || E->isValueDependent())
13425     return;
13426 
13427   // Check for array bounds violations in cases where the check isn't triggered
13428   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13429   // ArraySubscriptExpr is on the RHS of a variable initialization.
13430   CheckArrayAccess(E);
13431 
13432   // This is not the right CC for (e.g.) a variable initialization.
13433   AnalyzeImplicitConversions(*this, E, CC);
13434 }
13435 
13436 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13437 /// Input argument E is a logical expression.
13438 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13439   ::CheckBoolLikeConversion(*this, E, CC);
13440 }
13441 
13442 /// Diagnose when expression is an integer constant expression and its evaluation
13443 /// results in integer overflow
13444 void Sema::CheckForIntOverflow (Expr *E) {
13445   // Use a work list to deal with nested struct initializers.
13446   SmallVector<Expr *, 2> Exprs(1, E);
13447 
13448   do {
13449     Expr *OriginalE = Exprs.pop_back_val();
13450     Expr *E = OriginalE->IgnoreParenCasts();
13451 
13452     if (isa<BinaryOperator>(E)) {
13453       E->EvaluateForOverflow(Context);
13454       continue;
13455     }
13456 
13457     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13458       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13459     else if (isa<ObjCBoxedExpr>(OriginalE))
13460       E->EvaluateForOverflow(Context);
13461     else if (auto Call = dyn_cast<CallExpr>(E))
13462       Exprs.append(Call->arg_begin(), Call->arg_end());
13463     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13464       Exprs.append(Message->arg_begin(), Message->arg_end());
13465   } while (!Exprs.empty());
13466 }
13467 
13468 namespace {
13469 
13470 /// Visitor for expressions which looks for unsequenced operations on the
13471 /// same object.
13472 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13473   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13474 
13475   /// A tree of sequenced regions within an expression. Two regions are
13476   /// unsequenced if one is an ancestor or a descendent of the other. When we
13477   /// finish processing an expression with sequencing, such as a comma
13478   /// expression, we fold its tree nodes into its parent, since they are
13479   /// unsequenced with respect to nodes we will visit later.
13480   class SequenceTree {
13481     struct Value {
13482       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13483       unsigned Parent : 31;
13484       unsigned Merged : 1;
13485     };
13486     SmallVector<Value, 8> Values;
13487 
13488   public:
13489     /// A region within an expression which may be sequenced with respect
13490     /// to some other region.
13491     class Seq {
13492       friend class SequenceTree;
13493 
13494       unsigned Index;
13495 
13496       explicit Seq(unsigned N) : Index(N) {}
13497 
13498     public:
13499       Seq() : Index(0) {}
13500     };
13501 
13502     SequenceTree() { Values.push_back(Value(0)); }
13503     Seq root() const { return Seq(0); }
13504 
13505     /// Create a new sequence of operations, which is an unsequenced
13506     /// subset of \p Parent. This sequence of operations is sequenced with
13507     /// respect to other children of \p Parent.
13508     Seq allocate(Seq Parent) {
13509       Values.push_back(Value(Parent.Index));
13510       return Seq(Values.size() - 1);
13511     }
13512 
13513     /// Merge a sequence of operations into its parent.
13514     void merge(Seq S) {
13515       Values[S.Index].Merged = true;
13516     }
13517 
13518     /// Determine whether two operations are unsequenced. This operation
13519     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13520     /// should have been merged into its parent as appropriate.
13521     bool isUnsequenced(Seq Cur, Seq Old) {
13522       unsigned C = representative(Cur.Index);
13523       unsigned Target = representative(Old.Index);
13524       while (C >= Target) {
13525         if (C == Target)
13526           return true;
13527         C = Values[C].Parent;
13528       }
13529       return false;
13530     }
13531 
13532   private:
13533     /// Pick a representative for a sequence.
13534     unsigned representative(unsigned K) {
13535       if (Values[K].Merged)
13536         // Perform path compression as we go.
13537         return Values[K].Parent = representative(Values[K].Parent);
13538       return K;
13539     }
13540   };
13541 
13542   /// An object for which we can track unsequenced uses.
13543   using Object = const NamedDecl *;
13544 
13545   /// Different flavors of object usage which we track. We only track the
13546   /// least-sequenced usage of each kind.
13547   enum UsageKind {
13548     /// A read of an object. Multiple unsequenced reads are OK.
13549     UK_Use,
13550 
13551     /// A modification of an object which is sequenced before the value
13552     /// computation of the expression, such as ++n in C++.
13553     UK_ModAsValue,
13554 
13555     /// A modification of an object which is not sequenced before the value
13556     /// computation of the expression, such as n++.
13557     UK_ModAsSideEffect,
13558 
13559     UK_Count = UK_ModAsSideEffect + 1
13560   };
13561 
13562   /// Bundle together a sequencing region and the expression corresponding
13563   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13564   struct Usage {
13565     const Expr *UsageExpr;
13566     SequenceTree::Seq Seq;
13567 
13568     Usage() : UsageExpr(nullptr), Seq() {}
13569   };
13570 
13571   struct UsageInfo {
13572     Usage Uses[UK_Count];
13573 
13574     /// Have we issued a diagnostic for this object already?
13575     bool Diagnosed;
13576 
13577     UsageInfo() : Uses(), Diagnosed(false) {}
13578   };
13579   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13580 
13581   Sema &SemaRef;
13582 
13583   /// Sequenced regions within the expression.
13584   SequenceTree Tree;
13585 
13586   /// Declaration modifications and references which we have seen.
13587   UsageInfoMap UsageMap;
13588 
13589   /// The region we are currently within.
13590   SequenceTree::Seq Region;
13591 
13592   /// Filled in with declarations which were modified as a side-effect
13593   /// (that is, post-increment operations).
13594   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13595 
13596   /// Expressions to check later. We defer checking these to reduce
13597   /// stack usage.
13598   SmallVectorImpl<const Expr *> &WorkList;
13599 
13600   /// RAII object wrapping the visitation of a sequenced subexpression of an
13601   /// expression. At the end of this process, the side-effects of the evaluation
13602   /// become sequenced with respect to the value computation of the result, so
13603   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13604   /// UK_ModAsValue.
13605   struct SequencedSubexpression {
13606     SequencedSubexpression(SequenceChecker &Self)
13607       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13608       Self.ModAsSideEffect = &ModAsSideEffect;
13609     }
13610 
13611     ~SequencedSubexpression() {
13612       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13613         // Add a new usage with usage kind UK_ModAsValue, and then restore
13614         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13615         // the previous one was empty).
13616         UsageInfo &UI = Self.UsageMap[M.first];
13617         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13618         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13619         SideEffectUsage = M.second;
13620       }
13621       Self.ModAsSideEffect = OldModAsSideEffect;
13622     }
13623 
13624     SequenceChecker &Self;
13625     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13626     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13627   };
13628 
13629   /// RAII object wrapping the visitation of a subexpression which we might
13630   /// choose to evaluate as a constant. If any subexpression is evaluated and
13631   /// found to be non-constant, this allows us to suppress the evaluation of
13632   /// the outer expression.
13633   class EvaluationTracker {
13634   public:
13635     EvaluationTracker(SequenceChecker &Self)
13636         : Self(Self), Prev(Self.EvalTracker) {
13637       Self.EvalTracker = this;
13638     }
13639 
13640     ~EvaluationTracker() {
13641       Self.EvalTracker = Prev;
13642       if (Prev)
13643         Prev->EvalOK &= EvalOK;
13644     }
13645 
13646     bool evaluate(const Expr *E, bool &Result) {
13647       if (!EvalOK || E->isValueDependent())
13648         return false;
13649       EvalOK = E->EvaluateAsBooleanCondition(
13650           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13651       return EvalOK;
13652     }
13653 
13654   private:
13655     SequenceChecker &Self;
13656     EvaluationTracker *Prev;
13657     bool EvalOK = true;
13658   } *EvalTracker = nullptr;
13659 
13660   /// Find the object which is produced by the specified expression,
13661   /// if any.
13662   Object getObject(const Expr *E, bool Mod) const {
13663     E = E->IgnoreParenCasts();
13664     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13665       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13666         return getObject(UO->getSubExpr(), Mod);
13667     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13668       if (BO->getOpcode() == BO_Comma)
13669         return getObject(BO->getRHS(), Mod);
13670       if (Mod && BO->isAssignmentOp())
13671         return getObject(BO->getLHS(), Mod);
13672     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13673       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13674       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13675         return ME->getMemberDecl();
13676     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13677       // FIXME: If this is a reference, map through to its value.
13678       return DRE->getDecl();
13679     return nullptr;
13680   }
13681 
13682   /// Note that an object \p O was modified or used by an expression
13683   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13684   /// the object \p O as obtained via the \p UsageMap.
13685   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13686     // Get the old usage for the given object and usage kind.
13687     Usage &U = UI.Uses[UK];
13688     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13689       // If we have a modification as side effect and are in a sequenced
13690       // subexpression, save the old Usage so that we can restore it later
13691       // in SequencedSubexpression::~SequencedSubexpression.
13692       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13693         ModAsSideEffect->push_back(std::make_pair(O, U));
13694       // Then record the new usage with the current sequencing region.
13695       U.UsageExpr = UsageExpr;
13696       U.Seq = Region;
13697     }
13698   }
13699 
13700   /// Check whether a modification or use of an object \p O in an expression
13701   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13702   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13703   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13704   /// usage and false we are checking for a mod-use unsequenced usage.
13705   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13706                   UsageKind OtherKind, bool IsModMod) {
13707     if (UI.Diagnosed)
13708       return;
13709 
13710     const Usage &U = UI.Uses[OtherKind];
13711     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13712       return;
13713 
13714     const Expr *Mod = U.UsageExpr;
13715     const Expr *ModOrUse = UsageExpr;
13716     if (OtherKind == UK_Use)
13717       std::swap(Mod, ModOrUse);
13718 
13719     SemaRef.DiagRuntimeBehavior(
13720         Mod->getExprLoc(), {Mod, ModOrUse},
13721         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13722                                : diag::warn_unsequenced_mod_use)
13723             << O << SourceRange(ModOrUse->getExprLoc()));
13724     UI.Diagnosed = true;
13725   }
13726 
13727   // A note on note{Pre, Post}{Use, Mod}:
13728   //
13729   // (It helps to follow the algorithm with an expression such as
13730   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13731   //  operations before C++17 and both are well-defined in C++17).
13732   //
13733   // When visiting a node which uses/modify an object we first call notePreUse
13734   // or notePreMod before visiting its sub-expression(s). At this point the
13735   // children of the current node have not yet been visited and so the eventual
13736   // uses/modifications resulting from the children of the current node have not
13737   // been recorded yet.
13738   //
13739   // We then visit the children of the current node. After that notePostUse or
13740   // notePostMod is called. These will 1) detect an unsequenced modification
13741   // as side effect (as in "k++ + k") and 2) add a new usage with the
13742   // appropriate usage kind.
13743   //
13744   // We also have to be careful that some operation sequences modification as
13745   // side effect as well (for example: || or ,). To account for this we wrap
13746   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13747   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13748   // which record usages which are modifications as side effect, and then
13749   // downgrade them (or more accurately restore the previous usage which was a
13750   // modification as side effect) when exiting the scope of the sequenced
13751   // subexpression.
13752 
13753   void notePreUse(Object O, const Expr *UseExpr) {
13754     UsageInfo &UI = UsageMap[O];
13755     // Uses conflict with other modifications.
13756     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13757   }
13758 
13759   void notePostUse(Object O, const Expr *UseExpr) {
13760     UsageInfo &UI = UsageMap[O];
13761     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13762                /*IsModMod=*/false);
13763     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13764   }
13765 
13766   void notePreMod(Object O, const Expr *ModExpr) {
13767     UsageInfo &UI = UsageMap[O];
13768     // Modifications conflict with other modifications and with uses.
13769     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13770     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13771   }
13772 
13773   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13774     UsageInfo &UI = UsageMap[O];
13775     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13776                /*IsModMod=*/true);
13777     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13778   }
13779 
13780 public:
13781   SequenceChecker(Sema &S, const Expr *E,
13782                   SmallVectorImpl<const Expr *> &WorkList)
13783       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13784     Visit(E);
13785     // Silence a -Wunused-private-field since WorkList is now unused.
13786     // TODO: Evaluate if it can be used, and if not remove it.
13787     (void)this->WorkList;
13788   }
13789 
13790   void VisitStmt(const Stmt *S) {
13791     // Skip all statements which aren't expressions for now.
13792   }
13793 
13794   void VisitExpr(const Expr *E) {
13795     // By default, just recurse to evaluated subexpressions.
13796     Base::VisitStmt(E);
13797   }
13798 
13799   void VisitCastExpr(const CastExpr *E) {
13800     Object O = Object();
13801     if (E->getCastKind() == CK_LValueToRValue)
13802       O = getObject(E->getSubExpr(), false);
13803 
13804     if (O)
13805       notePreUse(O, E);
13806     VisitExpr(E);
13807     if (O)
13808       notePostUse(O, E);
13809   }
13810 
13811   void VisitSequencedExpressions(const Expr *SequencedBefore,
13812                                  const Expr *SequencedAfter) {
13813     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13814     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13815     SequenceTree::Seq OldRegion = Region;
13816 
13817     {
13818       SequencedSubexpression SeqBefore(*this);
13819       Region = BeforeRegion;
13820       Visit(SequencedBefore);
13821     }
13822 
13823     Region = AfterRegion;
13824     Visit(SequencedAfter);
13825 
13826     Region = OldRegion;
13827 
13828     Tree.merge(BeforeRegion);
13829     Tree.merge(AfterRegion);
13830   }
13831 
13832   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13833     // C++17 [expr.sub]p1:
13834     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13835     //   expression E1 is sequenced before the expression E2.
13836     if (SemaRef.getLangOpts().CPlusPlus17)
13837       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13838     else {
13839       Visit(ASE->getLHS());
13840       Visit(ASE->getRHS());
13841     }
13842   }
13843 
13844   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13845   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13846   void VisitBinPtrMem(const BinaryOperator *BO) {
13847     // C++17 [expr.mptr.oper]p4:
13848     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13849     //  the expression E1 is sequenced before the expression E2.
13850     if (SemaRef.getLangOpts().CPlusPlus17)
13851       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13852     else {
13853       Visit(BO->getLHS());
13854       Visit(BO->getRHS());
13855     }
13856   }
13857 
13858   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13859   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13860   void VisitBinShlShr(const BinaryOperator *BO) {
13861     // C++17 [expr.shift]p4:
13862     //  The expression E1 is sequenced before the expression E2.
13863     if (SemaRef.getLangOpts().CPlusPlus17)
13864       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13865     else {
13866       Visit(BO->getLHS());
13867       Visit(BO->getRHS());
13868     }
13869   }
13870 
13871   void VisitBinComma(const BinaryOperator *BO) {
13872     // C++11 [expr.comma]p1:
13873     //   Every value computation and side effect associated with the left
13874     //   expression is sequenced before every value computation and side
13875     //   effect associated with the right expression.
13876     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13877   }
13878 
13879   void VisitBinAssign(const BinaryOperator *BO) {
13880     SequenceTree::Seq RHSRegion;
13881     SequenceTree::Seq LHSRegion;
13882     if (SemaRef.getLangOpts().CPlusPlus17) {
13883       RHSRegion = Tree.allocate(Region);
13884       LHSRegion = Tree.allocate(Region);
13885     } else {
13886       RHSRegion = Region;
13887       LHSRegion = Region;
13888     }
13889     SequenceTree::Seq OldRegion = Region;
13890 
13891     // C++11 [expr.ass]p1:
13892     //  [...] the assignment is sequenced after the value computation
13893     //  of the right and left operands, [...]
13894     //
13895     // so check it before inspecting the operands and update the
13896     // map afterwards.
13897     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13898     if (O)
13899       notePreMod(O, BO);
13900 
13901     if (SemaRef.getLangOpts().CPlusPlus17) {
13902       // C++17 [expr.ass]p1:
13903       //  [...] The right operand is sequenced before the left operand. [...]
13904       {
13905         SequencedSubexpression SeqBefore(*this);
13906         Region = RHSRegion;
13907         Visit(BO->getRHS());
13908       }
13909 
13910       Region = LHSRegion;
13911       Visit(BO->getLHS());
13912 
13913       if (O && isa<CompoundAssignOperator>(BO))
13914         notePostUse(O, BO);
13915 
13916     } else {
13917       // C++11 does not specify any sequencing between the LHS and RHS.
13918       Region = LHSRegion;
13919       Visit(BO->getLHS());
13920 
13921       if (O && isa<CompoundAssignOperator>(BO))
13922         notePostUse(O, BO);
13923 
13924       Region = RHSRegion;
13925       Visit(BO->getRHS());
13926     }
13927 
13928     // C++11 [expr.ass]p1:
13929     //  the assignment is sequenced [...] before the value computation of the
13930     //  assignment expression.
13931     // C11 6.5.16/3 has no such rule.
13932     Region = OldRegion;
13933     if (O)
13934       notePostMod(O, BO,
13935                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13936                                                   : UK_ModAsSideEffect);
13937     if (SemaRef.getLangOpts().CPlusPlus17) {
13938       Tree.merge(RHSRegion);
13939       Tree.merge(LHSRegion);
13940     }
13941   }
13942 
13943   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13944     VisitBinAssign(CAO);
13945   }
13946 
13947   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13948   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13949   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13950     Object O = getObject(UO->getSubExpr(), true);
13951     if (!O)
13952       return VisitExpr(UO);
13953 
13954     notePreMod(O, UO);
13955     Visit(UO->getSubExpr());
13956     // C++11 [expr.pre.incr]p1:
13957     //   the expression ++x is equivalent to x+=1
13958     notePostMod(O, UO,
13959                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13960                                                 : UK_ModAsSideEffect);
13961   }
13962 
13963   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13964   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13965   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13966     Object O = getObject(UO->getSubExpr(), true);
13967     if (!O)
13968       return VisitExpr(UO);
13969 
13970     notePreMod(O, UO);
13971     Visit(UO->getSubExpr());
13972     notePostMod(O, UO, UK_ModAsSideEffect);
13973   }
13974 
13975   void VisitBinLOr(const BinaryOperator *BO) {
13976     // C++11 [expr.log.or]p2:
13977     //  If the second expression is evaluated, every value computation and
13978     //  side effect associated with the first expression is sequenced before
13979     //  every value computation and side effect associated with the
13980     //  second expression.
13981     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13982     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13983     SequenceTree::Seq OldRegion = Region;
13984 
13985     EvaluationTracker Eval(*this);
13986     {
13987       SequencedSubexpression Sequenced(*this);
13988       Region = LHSRegion;
13989       Visit(BO->getLHS());
13990     }
13991 
13992     // C++11 [expr.log.or]p1:
13993     //  [...] the second operand is not evaluated if the first operand
13994     //  evaluates to true.
13995     bool EvalResult = false;
13996     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13997     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13998     if (ShouldVisitRHS) {
13999       Region = RHSRegion;
14000       Visit(BO->getRHS());
14001     }
14002 
14003     Region = OldRegion;
14004     Tree.merge(LHSRegion);
14005     Tree.merge(RHSRegion);
14006   }
14007 
14008   void VisitBinLAnd(const BinaryOperator *BO) {
14009     // C++11 [expr.log.and]p2:
14010     //  If the second expression is evaluated, every value computation and
14011     //  side effect associated with the first expression is sequenced before
14012     //  every value computation and side effect associated with the
14013     //  second expression.
14014     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14015     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14016     SequenceTree::Seq OldRegion = Region;
14017 
14018     EvaluationTracker Eval(*this);
14019     {
14020       SequencedSubexpression Sequenced(*this);
14021       Region = LHSRegion;
14022       Visit(BO->getLHS());
14023     }
14024 
14025     // C++11 [expr.log.and]p1:
14026     //  [...] the second operand is not evaluated if the first operand is false.
14027     bool EvalResult = false;
14028     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14029     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14030     if (ShouldVisitRHS) {
14031       Region = RHSRegion;
14032       Visit(BO->getRHS());
14033     }
14034 
14035     Region = OldRegion;
14036     Tree.merge(LHSRegion);
14037     Tree.merge(RHSRegion);
14038   }
14039 
14040   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14041     // C++11 [expr.cond]p1:
14042     //  [...] Every value computation and side effect associated with the first
14043     //  expression is sequenced before every value computation and side effect
14044     //  associated with the second or third expression.
14045     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14046 
14047     // No sequencing is specified between the true and false expression.
14048     // However since exactly one of both is going to be evaluated we can
14049     // consider them to be sequenced. This is needed to avoid warning on
14050     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14051     // both the true and false expressions because we can't evaluate x.
14052     // This will still allow us to detect an expression like (pre C++17)
14053     // "(x ? y += 1 : y += 2) = y".
14054     //
14055     // We don't wrap the visitation of the true and false expression with
14056     // SequencedSubexpression because we don't want to downgrade modifications
14057     // as side effect in the true and false expressions after the visition
14058     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14059     // not warn between the two "y++", but we should warn between the "y++"
14060     // and the "y".
14061     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14062     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14063     SequenceTree::Seq OldRegion = Region;
14064 
14065     EvaluationTracker Eval(*this);
14066     {
14067       SequencedSubexpression Sequenced(*this);
14068       Region = ConditionRegion;
14069       Visit(CO->getCond());
14070     }
14071 
14072     // C++11 [expr.cond]p1:
14073     // [...] The first expression is contextually converted to bool (Clause 4).
14074     // It is evaluated and if it is true, the result of the conditional
14075     // expression is the value of the second expression, otherwise that of the
14076     // third expression. Only one of the second and third expressions is
14077     // evaluated. [...]
14078     bool EvalResult = false;
14079     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14080     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14081     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14082     if (ShouldVisitTrueExpr) {
14083       Region = TrueRegion;
14084       Visit(CO->getTrueExpr());
14085     }
14086     if (ShouldVisitFalseExpr) {
14087       Region = FalseRegion;
14088       Visit(CO->getFalseExpr());
14089     }
14090 
14091     Region = OldRegion;
14092     Tree.merge(ConditionRegion);
14093     Tree.merge(TrueRegion);
14094     Tree.merge(FalseRegion);
14095   }
14096 
14097   void VisitCallExpr(const CallExpr *CE) {
14098     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14099 
14100     if (CE->isUnevaluatedBuiltinCall(Context))
14101       return;
14102 
14103     // C++11 [intro.execution]p15:
14104     //   When calling a function [...], every value computation and side effect
14105     //   associated with any argument expression, or with the postfix expression
14106     //   designating the called function, is sequenced before execution of every
14107     //   expression or statement in the body of the function [and thus before
14108     //   the value computation of its result].
14109     SequencedSubexpression Sequenced(*this);
14110     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14111       // C++17 [expr.call]p5
14112       //   The postfix-expression is sequenced before each expression in the
14113       //   expression-list and any default argument. [...]
14114       SequenceTree::Seq CalleeRegion;
14115       SequenceTree::Seq OtherRegion;
14116       if (SemaRef.getLangOpts().CPlusPlus17) {
14117         CalleeRegion = Tree.allocate(Region);
14118         OtherRegion = Tree.allocate(Region);
14119       } else {
14120         CalleeRegion = Region;
14121         OtherRegion = Region;
14122       }
14123       SequenceTree::Seq OldRegion = Region;
14124 
14125       // Visit the callee expression first.
14126       Region = CalleeRegion;
14127       if (SemaRef.getLangOpts().CPlusPlus17) {
14128         SequencedSubexpression Sequenced(*this);
14129         Visit(CE->getCallee());
14130       } else {
14131         Visit(CE->getCallee());
14132       }
14133 
14134       // Then visit the argument expressions.
14135       Region = OtherRegion;
14136       for (const Expr *Argument : CE->arguments())
14137         Visit(Argument);
14138 
14139       Region = OldRegion;
14140       if (SemaRef.getLangOpts().CPlusPlus17) {
14141         Tree.merge(CalleeRegion);
14142         Tree.merge(OtherRegion);
14143       }
14144     });
14145   }
14146 
14147   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14148     // C++17 [over.match.oper]p2:
14149     //   [...] the operator notation is first transformed to the equivalent
14150     //   function-call notation as summarized in Table 12 (where @ denotes one
14151     //   of the operators covered in the specified subclause). However, the
14152     //   operands are sequenced in the order prescribed for the built-in
14153     //   operator (Clause 8).
14154     //
14155     // From the above only overloaded binary operators and overloaded call
14156     // operators have sequencing rules in C++17 that we need to handle
14157     // separately.
14158     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14159         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14160       return VisitCallExpr(CXXOCE);
14161 
14162     enum {
14163       NoSequencing,
14164       LHSBeforeRHS,
14165       RHSBeforeLHS,
14166       LHSBeforeRest
14167     } SequencingKind;
14168     switch (CXXOCE->getOperator()) {
14169     case OO_Equal:
14170     case OO_PlusEqual:
14171     case OO_MinusEqual:
14172     case OO_StarEqual:
14173     case OO_SlashEqual:
14174     case OO_PercentEqual:
14175     case OO_CaretEqual:
14176     case OO_AmpEqual:
14177     case OO_PipeEqual:
14178     case OO_LessLessEqual:
14179     case OO_GreaterGreaterEqual:
14180       SequencingKind = RHSBeforeLHS;
14181       break;
14182 
14183     case OO_LessLess:
14184     case OO_GreaterGreater:
14185     case OO_AmpAmp:
14186     case OO_PipePipe:
14187     case OO_Comma:
14188     case OO_ArrowStar:
14189     case OO_Subscript:
14190       SequencingKind = LHSBeforeRHS;
14191       break;
14192 
14193     case OO_Call:
14194       SequencingKind = LHSBeforeRest;
14195       break;
14196 
14197     default:
14198       SequencingKind = NoSequencing;
14199       break;
14200     }
14201 
14202     if (SequencingKind == NoSequencing)
14203       return VisitCallExpr(CXXOCE);
14204 
14205     // This is a call, so all subexpressions are sequenced before the result.
14206     SequencedSubexpression Sequenced(*this);
14207 
14208     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14209       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14210              "Should only get there with C++17 and above!");
14211       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14212              "Should only get there with an overloaded binary operator"
14213              " or an overloaded call operator!");
14214 
14215       if (SequencingKind == LHSBeforeRest) {
14216         assert(CXXOCE->getOperator() == OO_Call &&
14217                "We should only have an overloaded call operator here!");
14218 
14219         // This is very similar to VisitCallExpr, except that we only have the
14220         // C++17 case. The postfix-expression is the first argument of the
14221         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14222         // are in the following arguments.
14223         //
14224         // Note that we intentionally do not visit the callee expression since
14225         // it is just a decayed reference to a function.
14226         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14227         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14228         SequenceTree::Seq OldRegion = Region;
14229 
14230         assert(CXXOCE->getNumArgs() >= 1 &&
14231                "An overloaded call operator must have at least one argument"
14232                " for the postfix-expression!");
14233         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14234         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14235                                           CXXOCE->getNumArgs() - 1);
14236 
14237         // Visit the postfix-expression first.
14238         {
14239           Region = PostfixExprRegion;
14240           SequencedSubexpression Sequenced(*this);
14241           Visit(PostfixExpr);
14242         }
14243 
14244         // Then visit the argument expressions.
14245         Region = ArgsRegion;
14246         for (const Expr *Arg : Args)
14247           Visit(Arg);
14248 
14249         Region = OldRegion;
14250         Tree.merge(PostfixExprRegion);
14251         Tree.merge(ArgsRegion);
14252       } else {
14253         assert(CXXOCE->getNumArgs() == 2 &&
14254                "Should only have two arguments here!");
14255         assert((SequencingKind == LHSBeforeRHS ||
14256                 SequencingKind == RHSBeforeLHS) &&
14257                "Unexpected sequencing kind!");
14258 
14259         // We do not visit the callee expression since it is just a decayed
14260         // reference to a function.
14261         const Expr *E1 = CXXOCE->getArg(0);
14262         const Expr *E2 = CXXOCE->getArg(1);
14263         if (SequencingKind == RHSBeforeLHS)
14264           std::swap(E1, E2);
14265 
14266         return VisitSequencedExpressions(E1, E2);
14267       }
14268     });
14269   }
14270 
14271   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14272     // This is a call, so all subexpressions are sequenced before the result.
14273     SequencedSubexpression Sequenced(*this);
14274 
14275     if (!CCE->isListInitialization())
14276       return VisitExpr(CCE);
14277 
14278     // In C++11, list initializations are sequenced.
14279     SmallVector<SequenceTree::Seq, 32> Elts;
14280     SequenceTree::Seq Parent = Region;
14281     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14282                                               E = CCE->arg_end();
14283          I != E; ++I) {
14284       Region = Tree.allocate(Parent);
14285       Elts.push_back(Region);
14286       Visit(*I);
14287     }
14288 
14289     // Forget that the initializers are sequenced.
14290     Region = Parent;
14291     for (unsigned I = 0; I < Elts.size(); ++I)
14292       Tree.merge(Elts[I]);
14293   }
14294 
14295   void VisitInitListExpr(const InitListExpr *ILE) {
14296     if (!SemaRef.getLangOpts().CPlusPlus11)
14297       return VisitExpr(ILE);
14298 
14299     // In C++11, list initializations are sequenced.
14300     SmallVector<SequenceTree::Seq, 32> Elts;
14301     SequenceTree::Seq Parent = Region;
14302     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14303       const Expr *E = ILE->getInit(I);
14304       if (!E)
14305         continue;
14306       Region = Tree.allocate(Parent);
14307       Elts.push_back(Region);
14308       Visit(E);
14309     }
14310 
14311     // Forget that the initializers are sequenced.
14312     Region = Parent;
14313     for (unsigned I = 0; I < Elts.size(); ++I)
14314       Tree.merge(Elts[I]);
14315   }
14316 };
14317 
14318 } // namespace
14319 
14320 void Sema::CheckUnsequencedOperations(const Expr *E) {
14321   SmallVector<const Expr *, 8> WorkList;
14322   WorkList.push_back(E);
14323   while (!WorkList.empty()) {
14324     const Expr *Item = WorkList.pop_back_val();
14325     SequenceChecker(*this, Item, WorkList);
14326   }
14327 }
14328 
14329 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14330                               bool IsConstexpr) {
14331   llvm::SaveAndRestore<bool> ConstantContext(
14332       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14333   CheckImplicitConversions(E, CheckLoc);
14334   if (!E->isInstantiationDependent())
14335     CheckUnsequencedOperations(E);
14336   if (!IsConstexpr && !E->isValueDependent())
14337     CheckForIntOverflow(E);
14338   DiagnoseMisalignedMembers();
14339 }
14340 
14341 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14342                                        FieldDecl *BitField,
14343                                        Expr *Init) {
14344   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14345 }
14346 
14347 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14348                                          SourceLocation Loc) {
14349   if (!PType->isVariablyModifiedType())
14350     return;
14351   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14352     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14353     return;
14354   }
14355   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14356     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14357     return;
14358   }
14359   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14360     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14361     return;
14362   }
14363 
14364   const ArrayType *AT = S.Context.getAsArrayType(PType);
14365   if (!AT)
14366     return;
14367 
14368   if (AT->getSizeModifier() != ArrayType::Star) {
14369     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14370     return;
14371   }
14372 
14373   S.Diag(Loc, diag::err_array_star_in_function_definition);
14374 }
14375 
14376 /// CheckParmsForFunctionDef - Check that the parameters of the given
14377 /// function are appropriate for the definition of a function. This
14378 /// takes care of any checks that cannot be performed on the
14379 /// declaration itself, e.g., that the types of each of the function
14380 /// parameters are complete.
14381 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14382                                     bool CheckParameterNames) {
14383   bool HasInvalidParm = false;
14384   for (ParmVarDecl *Param : Parameters) {
14385     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14386     // function declarator that is part of a function definition of
14387     // that function shall not have incomplete type.
14388     //
14389     // This is also C++ [dcl.fct]p6.
14390     if (!Param->isInvalidDecl() &&
14391         RequireCompleteType(Param->getLocation(), Param->getType(),
14392                             diag::err_typecheck_decl_incomplete_type)) {
14393       Param->setInvalidDecl();
14394       HasInvalidParm = true;
14395     }
14396 
14397     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14398     // declaration of each parameter shall include an identifier.
14399     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14400         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14401       // Diagnose this as an extension in C17 and earlier.
14402       if (!getLangOpts().C2x)
14403         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14404     }
14405 
14406     // C99 6.7.5.3p12:
14407     //   If the function declarator is not part of a definition of that
14408     //   function, parameters may have incomplete type and may use the [*]
14409     //   notation in their sequences of declarator specifiers to specify
14410     //   variable length array types.
14411     QualType PType = Param->getOriginalType();
14412     // FIXME: This diagnostic should point the '[*]' if source-location
14413     // information is added for it.
14414     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14415 
14416     // If the parameter is a c++ class type and it has to be destructed in the
14417     // callee function, declare the destructor so that it can be called by the
14418     // callee function. Do not perform any direct access check on the dtor here.
14419     if (!Param->isInvalidDecl()) {
14420       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14421         if (!ClassDecl->isInvalidDecl() &&
14422             !ClassDecl->hasIrrelevantDestructor() &&
14423             !ClassDecl->isDependentContext() &&
14424             ClassDecl->isParamDestroyedInCallee()) {
14425           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14426           MarkFunctionReferenced(Param->getLocation(), Destructor);
14427           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14428         }
14429       }
14430     }
14431 
14432     // Parameters with the pass_object_size attribute only need to be marked
14433     // constant at function definitions. Because we lack information about
14434     // whether we're on a declaration or definition when we're instantiating the
14435     // attribute, we need to check for constness here.
14436     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14437       if (!Param->getType().isConstQualified())
14438         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14439             << Attr->getSpelling() << 1;
14440 
14441     // Check for parameter names shadowing fields from the class.
14442     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14443       // The owning context for the parameter should be the function, but we
14444       // want to see if this function's declaration context is a record.
14445       DeclContext *DC = Param->getDeclContext();
14446       if (DC && DC->isFunctionOrMethod()) {
14447         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14448           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14449                                      RD, /*DeclIsField*/ false);
14450       }
14451     }
14452   }
14453 
14454   return HasInvalidParm;
14455 }
14456 
14457 Optional<std::pair<CharUnits, CharUnits>>
14458 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14459 
14460 /// Compute the alignment and offset of the base class object given the
14461 /// derived-to-base cast expression and the alignment and offset of the derived
14462 /// class object.
14463 static std::pair<CharUnits, CharUnits>
14464 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14465                                    CharUnits BaseAlignment, CharUnits Offset,
14466                                    ASTContext &Ctx) {
14467   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14468        ++PathI) {
14469     const CXXBaseSpecifier *Base = *PathI;
14470     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14471     if (Base->isVirtual()) {
14472       // The complete object may have a lower alignment than the non-virtual
14473       // alignment of the base, in which case the base may be misaligned. Choose
14474       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14475       // conservative lower bound of the complete object alignment.
14476       CharUnits NonVirtualAlignment =
14477           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14478       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14479       Offset = CharUnits::Zero();
14480     } else {
14481       const ASTRecordLayout &RL =
14482           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14483       Offset += RL.getBaseClassOffset(BaseDecl);
14484     }
14485     DerivedType = Base->getType();
14486   }
14487 
14488   return std::make_pair(BaseAlignment, Offset);
14489 }
14490 
14491 /// Compute the alignment and offset of a binary additive operator.
14492 static Optional<std::pair<CharUnits, CharUnits>>
14493 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14494                                      bool IsSub, ASTContext &Ctx) {
14495   QualType PointeeType = PtrE->getType()->getPointeeType();
14496 
14497   if (!PointeeType->isConstantSizeType())
14498     return llvm::None;
14499 
14500   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14501 
14502   if (!P)
14503     return llvm::None;
14504 
14505   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14506   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14507     CharUnits Offset = EltSize * IdxRes->getExtValue();
14508     if (IsSub)
14509       Offset = -Offset;
14510     return std::make_pair(P->first, P->second + Offset);
14511   }
14512 
14513   // If the integer expression isn't a constant expression, compute the lower
14514   // bound of the alignment using the alignment and offset of the pointer
14515   // expression and the element size.
14516   return std::make_pair(
14517       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14518       CharUnits::Zero());
14519 }
14520 
14521 /// This helper function takes an lvalue expression and returns the alignment of
14522 /// a VarDecl and a constant offset from the VarDecl.
14523 Optional<std::pair<CharUnits, CharUnits>>
14524 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14525   E = E->IgnoreParens();
14526   switch (E->getStmtClass()) {
14527   default:
14528     break;
14529   case Stmt::CStyleCastExprClass:
14530   case Stmt::CXXStaticCastExprClass:
14531   case Stmt::ImplicitCastExprClass: {
14532     auto *CE = cast<CastExpr>(E);
14533     const Expr *From = CE->getSubExpr();
14534     switch (CE->getCastKind()) {
14535     default:
14536       break;
14537     case CK_NoOp:
14538       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14539     case CK_UncheckedDerivedToBase:
14540     case CK_DerivedToBase: {
14541       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14542       if (!P)
14543         break;
14544       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14545                                                 P->second, Ctx);
14546     }
14547     }
14548     break;
14549   }
14550   case Stmt::ArraySubscriptExprClass: {
14551     auto *ASE = cast<ArraySubscriptExpr>(E);
14552     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14553                                                 false, Ctx);
14554   }
14555   case Stmt::DeclRefExprClass: {
14556     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14557       // FIXME: If VD is captured by copy or is an escaping __block variable,
14558       // use the alignment of VD's type.
14559       if (!VD->getType()->isReferenceType())
14560         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14561       if (VD->hasInit())
14562         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14563     }
14564     break;
14565   }
14566   case Stmt::MemberExprClass: {
14567     auto *ME = cast<MemberExpr>(E);
14568     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14569     if (!FD || FD->getType()->isReferenceType() ||
14570         FD->getParent()->isInvalidDecl())
14571       break;
14572     Optional<std::pair<CharUnits, CharUnits>> P;
14573     if (ME->isArrow())
14574       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14575     else
14576       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14577     if (!P)
14578       break;
14579     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14580     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14581     return std::make_pair(P->first,
14582                           P->second + CharUnits::fromQuantity(Offset));
14583   }
14584   case Stmt::UnaryOperatorClass: {
14585     auto *UO = cast<UnaryOperator>(E);
14586     switch (UO->getOpcode()) {
14587     default:
14588       break;
14589     case UO_Deref:
14590       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14591     }
14592     break;
14593   }
14594   case Stmt::BinaryOperatorClass: {
14595     auto *BO = cast<BinaryOperator>(E);
14596     auto Opcode = BO->getOpcode();
14597     switch (Opcode) {
14598     default:
14599       break;
14600     case BO_Comma:
14601       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14602     }
14603     break;
14604   }
14605   }
14606   return llvm::None;
14607 }
14608 
14609 /// This helper function takes a pointer expression and returns the alignment of
14610 /// a VarDecl and a constant offset from the VarDecl.
14611 Optional<std::pair<CharUnits, CharUnits>>
14612 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14613   E = E->IgnoreParens();
14614   switch (E->getStmtClass()) {
14615   default:
14616     break;
14617   case Stmt::CStyleCastExprClass:
14618   case Stmt::CXXStaticCastExprClass:
14619   case Stmt::ImplicitCastExprClass: {
14620     auto *CE = cast<CastExpr>(E);
14621     const Expr *From = CE->getSubExpr();
14622     switch (CE->getCastKind()) {
14623     default:
14624       break;
14625     case CK_NoOp:
14626       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14627     case CK_ArrayToPointerDecay:
14628       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14629     case CK_UncheckedDerivedToBase:
14630     case CK_DerivedToBase: {
14631       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14632       if (!P)
14633         break;
14634       return getDerivedToBaseAlignmentAndOffset(
14635           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14636     }
14637     }
14638     break;
14639   }
14640   case Stmt::CXXThisExprClass: {
14641     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14642     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14643     return std::make_pair(Alignment, CharUnits::Zero());
14644   }
14645   case Stmt::UnaryOperatorClass: {
14646     auto *UO = cast<UnaryOperator>(E);
14647     if (UO->getOpcode() == UO_AddrOf)
14648       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14649     break;
14650   }
14651   case Stmt::BinaryOperatorClass: {
14652     auto *BO = cast<BinaryOperator>(E);
14653     auto Opcode = BO->getOpcode();
14654     switch (Opcode) {
14655     default:
14656       break;
14657     case BO_Add:
14658     case BO_Sub: {
14659       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14660       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14661         std::swap(LHS, RHS);
14662       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14663                                                   Ctx);
14664     }
14665     case BO_Comma:
14666       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14667     }
14668     break;
14669   }
14670   }
14671   return llvm::None;
14672 }
14673 
14674 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14675   // See if we can compute the alignment of a VarDecl and an offset from it.
14676   Optional<std::pair<CharUnits, CharUnits>> P =
14677       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14678 
14679   if (P)
14680     return P->first.alignmentAtOffset(P->second);
14681 
14682   // If that failed, return the type's alignment.
14683   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14684 }
14685 
14686 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14687 /// pointer cast increases the alignment requirements.
14688 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14689   // This is actually a lot of work to potentially be doing on every
14690   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14691   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14692     return;
14693 
14694   // Ignore dependent types.
14695   if (T->isDependentType() || Op->getType()->isDependentType())
14696     return;
14697 
14698   // Require that the destination be a pointer type.
14699   const PointerType *DestPtr = T->getAs<PointerType>();
14700   if (!DestPtr) return;
14701 
14702   // If the destination has alignment 1, we're done.
14703   QualType DestPointee = DestPtr->getPointeeType();
14704   if (DestPointee->isIncompleteType()) return;
14705   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14706   if (DestAlign.isOne()) return;
14707 
14708   // Require that the source be a pointer type.
14709   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14710   if (!SrcPtr) return;
14711   QualType SrcPointee = SrcPtr->getPointeeType();
14712 
14713   // Explicitly allow casts from cv void*.  We already implicitly
14714   // allowed casts to cv void*, since they have alignment 1.
14715   // Also allow casts involving incomplete types, which implicitly
14716   // includes 'void'.
14717   if (SrcPointee->isIncompleteType()) return;
14718 
14719   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14720 
14721   if (SrcAlign >= DestAlign) return;
14722 
14723   Diag(TRange.getBegin(), diag::warn_cast_align)
14724     << Op->getType() << T
14725     << static_cast<unsigned>(SrcAlign.getQuantity())
14726     << static_cast<unsigned>(DestAlign.getQuantity())
14727     << TRange << Op->getSourceRange();
14728 }
14729 
14730 /// Check whether this array fits the idiom of a size-one tail padded
14731 /// array member of a struct.
14732 ///
14733 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14734 /// commonly used to emulate flexible arrays in C89 code.
14735 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14736                                     const NamedDecl *ND) {
14737   if (Size != 1 || !ND) return false;
14738 
14739   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14740   if (!FD) return false;
14741 
14742   // Don't consider sizes resulting from macro expansions or template argument
14743   // substitution to form C89 tail-padded arrays.
14744 
14745   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14746   while (TInfo) {
14747     TypeLoc TL = TInfo->getTypeLoc();
14748     // Look through typedefs.
14749     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14750       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14751       TInfo = TDL->getTypeSourceInfo();
14752       continue;
14753     }
14754     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14755       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14756       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14757         return false;
14758     }
14759     break;
14760   }
14761 
14762   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14763   if (!RD) return false;
14764   if (RD->isUnion()) return false;
14765   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14766     if (!CRD->isStandardLayout()) return false;
14767   }
14768 
14769   // See if this is the last field decl in the record.
14770   const Decl *D = FD;
14771   while ((D = D->getNextDeclInContext()))
14772     if (isa<FieldDecl>(D))
14773       return false;
14774   return true;
14775 }
14776 
14777 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14778                             const ArraySubscriptExpr *ASE,
14779                             bool AllowOnePastEnd, bool IndexNegated) {
14780   // Already diagnosed by the constant evaluator.
14781   if (isConstantEvaluated())
14782     return;
14783 
14784   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14785   if (IndexExpr->isValueDependent())
14786     return;
14787 
14788   const Type *EffectiveType =
14789       BaseExpr->getType()->getPointeeOrArrayElementType();
14790   BaseExpr = BaseExpr->IgnoreParenCasts();
14791   const ConstantArrayType *ArrayTy =
14792       Context.getAsConstantArrayType(BaseExpr->getType());
14793 
14794   const Type *BaseType =
14795       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14796   bool IsUnboundedArray = (BaseType == nullptr);
14797   if (EffectiveType->isDependentType() ||
14798       (!IsUnboundedArray && BaseType->isDependentType()))
14799     return;
14800 
14801   Expr::EvalResult Result;
14802   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14803     return;
14804 
14805   llvm::APSInt index = Result.Val.getInt();
14806   if (IndexNegated) {
14807     index.setIsUnsigned(false);
14808     index = -index;
14809   }
14810 
14811   const NamedDecl *ND = nullptr;
14812   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14813     ND = DRE->getDecl();
14814   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14815     ND = ME->getMemberDecl();
14816 
14817   if (IsUnboundedArray) {
14818     if (index.isUnsigned() || !index.isNegative()) {
14819       const auto &ASTC = getASTContext();
14820       unsigned AddrBits =
14821           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14822               EffectiveType->getCanonicalTypeInternal()));
14823       if (index.getBitWidth() < AddrBits)
14824         index = index.zext(AddrBits);
14825       Optional<CharUnits> ElemCharUnits =
14826           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14827       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14828       // pointer) bounds-checking isn't meaningful.
14829       if (!ElemCharUnits)
14830         return;
14831       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14832       // If index has more active bits than address space, we already know
14833       // we have a bounds violation to warn about.  Otherwise, compute
14834       // address of (index + 1)th element, and warn about bounds violation
14835       // only if that address exceeds address space.
14836       if (index.getActiveBits() <= AddrBits) {
14837         bool Overflow;
14838         llvm::APInt Product(index);
14839         Product += 1;
14840         Product = Product.umul_ov(ElemBytes, Overflow);
14841         if (!Overflow && Product.getActiveBits() <= AddrBits)
14842           return;
14843       }
14844 
14845       // Need to compute max possible elements in address space, since that
14846       // is included in diag message.
14847       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14848       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14849       MaxElems += 1;
14850       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14851       MaxElems = MaxElems.udiv(ElemBytes);
14852 
14853       unsigned DiagID =
14854           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14855               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14856 
14857       // Diag message shows element size in bits and in "bytes" (platform-
14858       // dependent CharUnits)
14859       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14860                           PDiag(DiagID)
14861                               << toString(index, 10, true) << AddrBits
14862                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14863                               << toString(ElemBytes, 10, false)
14864                               << toString(MaxElems, 10, false)
14865                               << (unsigned)MaxElems.getLimitedValue(~0U)
14866                               << IndexExpr->getSourceRange());
14867 
14868       if (!ND) {
14869         // Try harder to find a NamedDecl to point at in the note.
14870         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14871           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14872         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14873           ND = DRE->getDecl();
14874         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14875           ND = ME->getMemberDecl();
14876       }
14877 
14878       if (ND)
14879         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14880                             PDiag(diag::note_array_declared_here) << ND);
14881     }
14882     return;
14883   }
14884 
14885   if (index.isUnsigned() || !index.isNegative()) {
14886     // It is possible that the type of the base expression after
14887     // IgnoreParenCasts is incomplete, even though the type of the base
14888     // expression before IgnoreParenCasts is complete (see PR39746 for an
14889     // example). In this case we have no information about whether the array
14890     // access exceeds the array bounds. However we can still diagnose an array
14891     // access which precedes the array bounds.
14892     if (BaseType->isIncompleteType())
14893       return;
14894 
14895     llvm::APInt size = ArrayTy->getSize();
14896     if (!size.isStrictlyPositive())
14897       return;
14898 
14899     if (BaseType != EffectiveType) {
14900       // Make sure we're comparing apples to apples when comparing index to size
14901       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14902       uint64_t array_typesize = Context.getTypeSize(BaseType);
14903       // Handle ptrarith_typesize being zero, such as when casting to void*
14904       if (!ptrarith_typesize) ptrarith_typesize = 1;
14905       if (ptrarith_typesize != array_typesize) {
14906         // There's a cast to a different size type involved
14907         uint64_t ratio = array_typesize / ptrarith_typesize;
14908         // TODO: Be smarter about handling cases where array_typesize is not a
14909         // multiple of ptrarith_typesize
14910         if (ptrarith_typesize * ratio == array_typesize)
14911           size *= llvm::APInt(size.getBitWidth(), ratio);
14912       }
14913     }
14914 
14915     if (size.getBitWidth() > index.getBitWidth())
14916       index = index.zext(size.getBitWidth());
14917     else if (size.getBitWidth() < index.getBitWidth())
14918       size = size.zext(index.getBitWidth());
14919 
14920     // For array subscripting the index must be less than size, but for pointer
14921     // arithmetic also allow the index (offset) to be equal to size since
14922     // computing the next address after the end of the array is legal and
14923     // commonly done e.g. in C++ iterators and range-based for loops.
14924     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14925       return;
14926 
14927     // Also don't warn for arrays of size 1 which are members of some
14928     // structure. These are often used to approximate flexible arrays in C89
14929     // code.
14930     if (IsTailPaddedMemberArray(*this, size, ND))
14931       return;
14932 
14933     // Suppress the warning if the subscript expression (as identified by the
14934     // ']' location) and the index expression are both from macro expansions
14935     // within a system header.
14936     if (ASE) {
14937       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14938           ASE->getRBracketLoc());
14939       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14940         SourceLocation IndexLoc =
14941             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14942         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14943           return;
14944       }
14945     }
14946 
14947     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
14948                           : diag::warn_ptr_arith_exceeds_bounds;
14949 
14950     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14951                         PDiag(DiagID) << toString(index, 10, true)
14952                                       << toString(size, 10, true)
14953                                       << (unsigned)size.getLimitedValue(~0U)
14954                                       << IndexExpr->getSourceRange());
14955   } else {
14956     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14957     if (!ASE) {
14958       DiagID = diag::warn_ptr_arith_precedes_bounds;
14959       if (index.isNegative()) index = -index;
14960     }
14961 
14962     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14963                         PDiag(DiagID) << toString(index, 10, true)
14964                                       << IndexExpr->getSourceRange());
14965   }
14966 
14967   if (!ND) {
14968     // Try harder to find a NamedDecl to point at in the note.
14969     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14970       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14971     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14972       ND = DRE->getDecl();
14973     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14974       ND = ME->getMemberDecl();
14975   }
14976 
14977   if (ND)
14978     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14979                         PDiag(diag::note_array_declared_here) << ND);
14980 }
14981 
14982 void Sema::CheckArrayAccess(const Expr *expr) {
14983   int AllowOnePastEnd = 0;
14984   while (expr) {
14985     expr = expr->IgnoreParenImpCasts();
14986     switch (expr->getStmtClass()) {
14987       case Stmt::ArraySubscriptExprClass: {
14988         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14989         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14990                          AllowOnePastEnd > 0);
14991         expr = ASE->getBase();
14992         break;
14993       }
14994       case Stmt::MemberExprClass: {
14995         expr = cast<MemberExpr>(expr)->getBase();
14996         break;
14997       }
14998       case Stmt::OMPArraySectionExprClass: {
14999         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15000         if (ASE->getLowerBound())
15001           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15002                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15003         return;
15004       }
15005       case Stmt::UnaryOperatorClass: {
15006         // Only unwrap the * and & unary operators
15007         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15008         expr = UO->getSubExpr();
15009         switch (UO->getOpcode()) {
15010           case UO_AddrOf:
15011             AllowOnePastEnd++;
15012             break;
15013           case UO_Deref:
15014             AllowOnePastEnd--;
15015             break;
15016           default:
15017             return;
15018         }
15019         break;
15020       }
15021       case Stmt::ConditionalOperatorClass: {
15022         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15023         if (const Expr *lhs = cond->getLHS())
15024           CheckArrayAccess(lhs);
15025         if (const Expr *rhs = cond->getRHS())
15026           CheckArrayAccess(rhs);
15027         return;
15028       }
15029       case Stmt::CXXOperatorCallExprClass: {
15030         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15031         for (const auto *Arg : OCE->arguments())
15032           CheckArrayAccess(Arg);
15033         return;
15034       }
15035       default:
15036         return;
15037     }
15038   }
15039 }
15040 
15041 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15042 
15043 namespace {
15044 
15045 struct RetainCycleOwner {
15046   VarDecl *Variable = nullptr;
15047   SourceRange Range;
15048   SourceLocation Loc;
15049   bool Indirect = false;
15050 
15051   RetainCycleOwner() = default;
15052 
15053   void setLocsFrom(Expr *e) {
15054     Loc = e->getExprLoc();
15055     Range = e->getSourceRange();
15056   }
15057 };
15058 
15059 } // namespace
15060 
15061 /// Consider whether capturing the given variable can possibly lead to
15062 /// a retain cycle.
15063 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15064   // In ARC, it's captured strongly iff the variable has __strong
15065   // lifetime.  In MRR, it's captured strongly if the variable is
15066   // __block and has an appropriate type.
15067   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15068     return false;
15069 
15070   owner.Variable = var;
15071   if (ref)
15072     owner.setLocsFrom(ref);
15073   return true;
15074 }
15075 
15076 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15077   while (true) {
15078     e = e->IgnoreParens();
15079     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15080       switch (cast->getCastKind()) {
15081       case CK_BitCast:
15082       case CK_LValueBitCast:
15083       case CK_LValueToRValue:
15084       case CK_ARCReclaimReturnedObject:
15085         e = cast->getSubExpr();
15086         continue;
15087 
15088       default:
15089         return false;
15090       }
15091     }
15092 
15093     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15094       ObjCIvarDecl *ivar = ref->getDecl();
15095       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15096         return false;
15097 
15098       // Try to find a retain cycle in the base.
15099       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15100         return false;
15101 
15102       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15103       owner.Indirect = true;
15104       return true;
15105     }
15106 
15107     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15108       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15109       if (!var) return false;
15110       return considerVariable(var, ref, owner);
15111     }
15112 
15113     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15114       if (member->isArrow()) return false;
15115 
15116       // Don't count this as an indirect ownership.
15117       e = member->getBase();
15118       continue;
15119     }
15120 
15121     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15122       // Only pay attention to pseudo-objects on property references.
15123       ObjCPropertyRefExpr *pre
15124         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15125                                               ->IgnoreParens());
15126       if (!pre) return false;
15127       if (pre->isImplicitProperty()) return false;
15128       ObjCPropertyDecl *property = pre->getExplicitProperty();
15129       if (!property->isRetaining() &&
15130           !(property->getPropertyIvarDecl() &&
15131             property->getPropertyIvarDecl()->getType()
15132               .getObjCLifetime() == Qualifiers::OCL_Strong))
15133           return false;
15134 
15135       owner.Indirect = true;
15136       if (pre->isSuperReceiver()) {
15137         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15138         if (!owner.Variable)
15139           return false;
15140         owner.Loc = pre->getLocation();
15141         owner.Range = pre->getSourceRange();
15142         return true;
15143       }
15144       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15145                               ->getSourceExpr());
15146       continue;
15147     }
15148 
15149     // Array ivars?
15150 
15151     return false;
15152   }
15153 }
15154 
15155 namespace {
15156 
15157   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15158     ASTContext &Context;
15159     VarDecl *Variable;
15160     Expr *Capturer = nullptr;
15161     bool VarWillBeReased = false;
15162 
15163     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15164         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15165           Context(Context), Variable(variable) {}
15166 
15167     void VisitDeclRefExpr(DeclRefExpr *ref) {
15168       if (ref->getDecl() == Variable && !Capturer)
15169         Capturer = ref;
15170     }
15171 
15172     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15173       if (Capturer) return;
15174       Visit(ref->getBase());
15175       if (Capturer && ref->isFreeIvar())
15176         Capturer = ref;
15177     }
15178 
15179     void VisitBlockExpr(BlockExpr *block) {
15180       // Look inside nested blocks
15181       if (block->getBlockDecl()->capturesVariable(Variable))
15182         Visit(block->getBlockDecl()->getBody());
15183     }
15184 
15185     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15186       if (Capturer) return;
15187       if (OVE->getSourceExpr())
15188         Visit(OVE->getSourceExpr());
15189     }
15190 
15191     void VisitBinaryOperator(BinaryOperator *BinOp) {
15192       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15193         return;
15194       Expr *LHS = BinOp->getLHS();
15195       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15196         if (DRE->getDecl() != Variable)
15197           return;
15198         if (Expr *RHS = BinOp->getRHS()) {
15199           RHS = RHS->IgnoreParenCasts();
15200           Optional<llvm::APSInt> Value;
15201           VarWillBeReased =
15202               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15203                *Value == 0);
15204         }
15205       }
15206     }
15207   };
15208 
15209 } // namespace
15210 
15211 /// Check whether the given argument is a block which captures a
15212 /// variable.
15213 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15214   assert(owner.Variable && owner.Loc.isValid());
15215 
15216   e = e->IgnoreParenCasts();
15217 
15218   // Look through [^{...} copy] and Block_copy(^{...}).
15219   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15220     Selector Cmd = ME->getSelector();
15221     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15222       e = ME->getInstanceReceiver();
15223       if (!e)
15224         return nullptr;
15225       e = e->IgnoreParenCasts();
15226     }
15227   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15228     if (CE->getNumArgs() == 1) {
15229       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15230       if (Fn) {
15231         const IdentifierInfo *FnI = Fn->getIdentifier();
15232         if (FnI && FnI->isStr("_Block_copy")) {
15233           e = CE->getArg(0)->IgnoreParenCasts();
15234         }
15235       }
15236     }
15237   }
15238 
15239   BlockExpr *block = dyn_cast<BlockExpr>(e);
15240   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15241     return nullptr;
15242 
15243   FindCaptureVisitor visitor(S.Context, owner.Variable);
15244   visitor.Visit(block->getBlockDecl()->getBody());
15245   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15246 }
15247 
15248 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15249                                 RetainCycleOwner &owner) {
15250   assert(capturer);
15251   assert(owner.Variable && owner.Loc.isValid());
15252 
15253   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15254     << owner.Variable << capturer->getSourceRange();
15255   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15256     << owner.Indirect << owner.Range;
15257 }
15258 
15259 /// Check for a keyword selector that starts with the word 'add' or
15260 /// 'set'.
15261 static bool isSetterLikeSelector(Selector sel) {
15262   if (sel.isUnarySelector()) return false;
15263 
15264   StringRef str = sel.getNameForSlot(0);
15265   while (!str.empty() && str.front() == '_') str = str.substr(1);
15266   if (str.startswith("set"))
15267     str = str.substr(3);
15268   else if (str.startswith("add")) {
15269     // Specially allow 'addOperationWithBlock:'.
15270     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15271       return false;
15272     str = str.substr(3);
15273   }
15274   else
15275     return false;
15276 
15277   if (str.empty()) return true;
15278   return !isLowercase(str.front());
15279 }
15280 
15281 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15282                                                     ObjCMessageExpr *Message) {
15283   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15284                                                 Message->getReceiverInterface(),
15285                                                 NSAPI::ClassId_NSMutableArray);
15286   if (!IsMutableArray) {
15287     return None;
15288   }
15289 
15290   Selector Sel = Message->getSelector();
15291 
15292   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15293     S.NSAPIObj->getNSArrayMethodKind(Sel);
15294   if (!MKOpt) {
15295     return None;
15296   }
15297 
15298   NSAPI::NSArrayMethodKind MK = *MKOpt;
15299 
15300   switch (MK) {
15301     case NSAPI::NSMutableArr_addObject:
15302     case NSAPI::NSMutableArr_insertObjectAtIndex:
15303     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15304       return 0;
15305     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15306       return 1;
15307 
15308     default:
15309       return None;
15310   }
15311 
15312   return None;
15313 }
15314 
15315 static
15316 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15317                                                   ObjCMessageExpr *Message) {
15318   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15319                                             Message->getReceiverInterface(),
15320                                             NSAPI::ClassId_NSMutableDictionary);
15321   if (!IsMutableDictionary) {
15322     return None;
15323   }
15324 
15325   Selector Sel = Message->getSelector();
15326 
15327   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15328     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15329   if (!MKOpt) {
15330     return None;
15331   }
15332 
15333   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15334 
15335   switch (MK) {
15336     case NSAPI::NSMutableDict_setObjectForKey:
15337     case NSAPI::NSMutableDict_setValueForKey:
15338     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15339       return 0;
15340 
15341     default:
15342       return None;
15343   }
15344 
15345   return None;
15346 }
15347 
15348 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15349   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15350                                                 Message->getReceiverInterface(),
15351                                                 NSAPI::ClassId_NSMutableSet);
15352 
15353   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15354                                             Message->getReceiverInterface(),
15355                                             NSAPI::ClassId_NSMutableOrderedSet);
15356   if (!IsMutableSet && !IsMutableOrderedSet) {
15357     return None;
15358   }
15359 
15360   Selector Sel = Message->getSelector();
15361 
15362   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15363   if (!MKOpt) {
15364     return None;
15365   }
15366 
15367   NSAPI::NSSetMethodKind MK = *MKOpt;
15368 
15369   switch (MK) {
15370     case NSAPI::NSMutableSet_addObject:
15371     case NSAPI::NSOrderedSet_setObjectAtIndex:
15372     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15373     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15374       return 0;
15375     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15376       return 1;
15377   }
15378 
15379   return None;
15380 }
15381 
15382 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15383   if (!Message->isInstanceMessage()) {
15384     return;
15385   }
15386 
15387   Optional<int> ArgOpt;
15388 
15389   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15390       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15391       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15392     return;
15393   }
15394 
15395   int ArgIndex = *ArgOpt;
15396 
15397   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15398   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15399     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15400   }
15401 
15402   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15403     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15404       if (ArgRE->isObjCSelfExpr()) {
15405         Diag(Message->getSourceRange().getBegin(),
15406              diag::warn_objc_circular_container)
15407           << ArgRE->getDecl() << StringRef("'super'");
15408       }
15409     }
15410   } else {
15411     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15412 
15413     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15414       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15415     }
15416 
15417     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15418       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15419         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15420           ValueDecl *Decl = ReceiverRE->getDecl();
15421           Diag(Message->getSourceRange().getBegin(),
15422                diag::warn_objc_circular_container)
15423             << Decl << Decl;
15424           if (!ArgRE->isObjCSelfExpr()) {
15425             Diag(Decl->getLocation(),
15426                  diag::note_objc_circular_container_declared_here)
15427               << Decl;
15428           }
15429         }
15430       }
15431     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15432       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15433         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15434           ObjCIvarDecl *Decl = IvarRE->getDecl();
15435           Diag(Message->getSourceRange().getBegin(),
15436                diag::warn_objc_circular_container)
15437             << Decl << Decl;
15438           Diag(Decl->getLocation(),
15439                diag::note_objc_circular_container_declared_here)
15440             << Decl;
15441         }
15442       }
15443     }
15444   }
15445 }
15446 
15447 /// Check a message send to see if it's likely to cause a retain cycle.
15448 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15449   // Only check instance methods whose selector looks like a setter.
15450   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15451     return;
15452 
15453   // Try to find a variable that the receiver is strongly owned by.
15454   RetainCycleOwner owner;
15455   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15456     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15457       return;
15458   } else {
15459     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15460     owner.Variable = getCurMethodDecl()->getSelfDecl();
15461     owner.Loc = msg->getSuperLoc();
15462     owner.Range = msg->getSuperLoc();
15463   }
15464 
15465   // Check whether the receiver is captured by any of the arguments.
15466   const ObjCMethodDecl *MD = msg->getMethodDecl();
15467   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15468     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15469       // noescape blocks should not be retained by the method.
15470       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15471         continue;
15472       return diagnoseRetainCycle(*this, capturer, owner);
15473     }
15474   }
15475 }
15476 
15477 /// Check a property assign to see if it's likely to cause a retain cycle.
15478 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15479   RetainCycleOwner owner;
15480   if (!findRetainCycleOwner(*this, receiver, owner))
15481     return;
15482 
15483   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15484     diagnoseRetainCycle(*this, capturer, owner);
15485 }
15486 
15487 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15488   RetainCycleOwner Owner;
15489   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15490     return;
15491 
15492   // Because we don't have an expression for the variable, we have to set the
15493   // location explicitly here.
15494   Owner.Loc = Var->getLocation();
15495   Owner.Range = Var->getSourceRange();
15496 
15497   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15498     diagnoseRetainCycle(*this, Capturer, Owner);
15499 }
15500 
15501 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15502                                      Expr *RHS, bool isProperty) {
15503   // Check if RHS is an Objective-C object literal, which also can get
15504   // immediately zapped in a weak reference.  Note that we explicitly
15505   // allow ObjCStringLiterals, since those are designed to never really die.
15506   RHS = RHS->IgnoreParenImpCasts();
15507 
15508   // This enum needs to match with the 'select' in
15509   // warn_objc_arc_literal_assign (off-by-1).
15510   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15511   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15512     return false;
15513 
15514   S.Diag(Loc, diag::warn_arc_literal_assign)
15515     << (unsigned) Kind
15516     << (isProperty ? 0 : 1)
15517     << RHS->getSourceRange();
15518 
15519   return true;
15520 }
15521 
15522 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15523                                     Qualifiers::ObjCLifetime LT,
15524                                     Expr *RHS, bool isProperty) {
15525   // Strip off any implicit cast added to get to the one ARC-specific.
15526   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15527     if (cast->getCastKind() == CK_ARCConsumeObject) {
15528       S.Diag(Loc, diag::warn_arc_retained_assign)
15529         << (LT == Qualifiers::OCL_ExplicitNone)
15530         << (isProperty ? 0 : 1)
15531         << RHS->getSourceRange();
15532       return true;
15533     }
15534     RHS = cast->getSubExpr();
15535   }
15536 
15537   if (LT == Qualifiers::OCL_Weak &&
15538       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15539     return true;
15540 
15541   return false;
15542 }
15543 
15544 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15545                               QualType LHS, Expr *RHS) {
15546   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15547 
15548   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15549     return false;
15550 
15551   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15552     return true;
15553 
15554   return false;
15555 }
15556 
15557 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15558                               Expr *LHS, Expr *RHS) {
15559   QualType LHSType;
15560   // PropertyRef on LHS type need be directly obtained from
15561   // its declaration as it has a PseudoType.
15562   ObjCPropertyRefExpr *PRE
15563     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15564   if (PRE && !PRE->isImplicitProperty()) {
15565     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15566     if (PD)
15567       LHSType = PD->getType();
15568   }
15569 
15570   if (LHSType.isNull())
15571     LHSType = LHS->getType();
15572 
15573   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15574 
15575   if (LT == Qualifiers::OCL_Weak) {
15576     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15577       getCurFunction()->markSafeWeakUse(LHS);
15578   }
15579 
15580   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15581     return;
15582 
15583   // FIXME. Check for other life times.
15584   if (LT != Qualifiers::OCL_None)
15585     return;
15586 
15587   if (PRE) {
15588     if (PRE->isImplicitProperty())
15589       return;
15590     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15591     if (!PD)
15592       return;
15593 
15594     unsigned Attributes = PD->getPropertyAttributes();
15595     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15596       // when 'assign' attribute was not explicitly specified
15597       // by user, ignore it and rely on property type itself
15598       // for lifetime info.
15599       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15600       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15601           LHSType->isObjCRetainableType())
15602         return;
15603 
15604       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15605         if (cast->getCastKind() == CK_ARCConsumeObject) {
15606           Diag(Loc, diag::warn_arc_retained_property_assign)
15607           << RHS->getSourceRange();
15608           return;
15609         }
15610         RHS = cast->getSubExpr();
15611       }
15612     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15613       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15614         return;
15615     }
15616   }
15617 }
15618 
15619 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15620 
15621 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15622                                         SourceLocation StmtLoc,
15623                                         const NullStmt *Body) {
15624   // Do not warn if the body is a macro that expands to nothing, e.g:
15625   //
15626   // #define CALL(x)
15627   // if (condition)
15628   //   CALL(0);
15629   if (Body->hasLeadingEmptyMacro())
15630     return false;
15631 
15632   // Get line numbers of statement and body.
15633   bool StmtLineInvalid;
15634   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15635                                                       &StmtLineInvalid);
15636   if (StmtLineInvalid)
15637     return false;
15638 
15639   bool BodyLineInvalid;
15640   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15641                                                       &BodyLineInvalid);
15642   if (BodyLineInvalid)
15643     return false;
15644 
15645   // Warn if null statement and body are on the same line.
15646   if (StmtLine != BodyLine)
15647     return false;
15648 
15649   return true;
15650 }
15651 
15652 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15653                                  const Stmt *Body,
15654                                  unsigned DiagID) {
15655   // Since this is a syntactic check, don't emit diagnostic for template
15656   // instantiations, this just adds noise.
15657   if (CurrentInstantiationScope)
15658     return;
15659 
15660   // The body should be a null statement.
15661   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15662   if (!NBody)
15663     return;
15664 
15665   // Do the usual checks.
15666   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15667     return;
15668 
15669   Diag(NBody->getSemiLoc(), DiagID);
15670   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15671 }
15672 
15673 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15674                                  const Stmt *PossibleBody) {
15675   assert(!CurrentInstantiationScope); // Ensured by caller
15676 
15677   SourceLocation StmtLoc;
15678   const Stmt *Body;
15679   unsigned DiagID;
15680   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15681     StmtLoc = FS->getRParenLoc();
15682     Body = FS->getBody();
15683     DiagID = diag::warn_empty_for_body;
15684   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15685     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15686     Body = WS->getBody();
15687     DiagID = diag::warn_empty_while_body;
15688   } else
15689     return; // Neither `for' nor `while'.
15690 
15691   // The body should be a null statement.
15692   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15693   if (!NBody)
15694     return;
15695 
15696   // Skip expensive checks if diagnostic is disabled.
15697   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15698     return;
15699 
15700   // Do the usual checks.
15701   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15702     return;
15703 
15704   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15705   // noise level low, emit diagnostics only if for/while is followed by a
15706   // CompoundStmt, e.g.:
15707   //    for (int i = 0; i < n; i++);
15708   //    {
15709   //      a(i);
15710   //    }
15711   // or if for/while is followed by a statement with more indentation
15712   // than for/while itself:
15713   //    for (int i = 0; i < n; i++);
15714   //      a(i);
15715   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15716   if (!ProbableTypo) {
15717     bool BodyColInvalid;
15718     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15719         PossibleBody->getBeginLoc(), &BodyColInvalid);
15720     if (BodyColInvalid)
15721       return;
15722 
15723     bool StmtColInvalid;
15724     unsigned StmtCol =
15725         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15726     if (StmtColInvalid)
15727       return;
15728 
15729     if (BodyCol > StmtCol)
15730       ProbableTypo = true;
15731   }
15732 
15733   if (ProbableTypo) {
15734     Diag(NBody->getSemiLoc(), DiagID);
15735     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15736   }
15737 }
15738 
15739 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15740 
15741 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15742 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15743                              SourceLocation OpLoc) {
15744   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15745     return;
15746 
15747   if (inTemplateInstantiation())
15748     return;
15749 
15750   // Strip parens and casts away.
15751   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15752   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15753 
15754   // Check for a call expression
15755   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15756   if (!CE || CE->getNumArgs() != 1)
15757     return;
15758 
15759   // Check for a call to std::move
15760   if (!CE->isCallToStdMove())
15761     return;
15762 
15763   // Get argument from std::move
15764   RHSExpr = CE->getArg(0);
15765 
15766   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15767   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15768 
15769   // Two DeclRefExpr's, check that the decls are the same.
15770   if (LHSDeclRef && RHSDeclRef) {
15771     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15772       return;
15773     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15774         RHSDeclRef->getDecl()->getCanonicalDecl())
15775       return;
15776 
15777     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15778                                         << LHSExpr->getSourceRange()
15779                                         << RHSExpr->getSourceRange();
15780     return;
15781   }
15782 
15783   // Member variables require a different approach to check for self moves.
15784   // MemberExpr's are the same if every nested MemberExpr refers to the same
15785   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15786   // the base Expr's are CXXThisExpr's.
15787   const Expr *LHSBase = LHSExpr;
15788   const Expr *RHSBase = RHSExpr;
15789   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15790   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15791   if (!LHSME || !RHSME)
15792     return;
15793 
15794   while (LHSME && RHSME) {
15795     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15796         RHSME->getMemberDecl()->getCanonicalDecl())
15797       return;
15798 
15799     LHSBase = LHSME->getBase();
15800     RHSBase = RHSME->getBase();
15801     LHSME = dyn_cast<MemberExpr>(LHSBase);
15802     RHSME = dyn_cast<MemberExpr>(RHSBase);
15803   }
15804 
15805   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15806   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15807   if (LHSDeclRef && RHSDeclRef) {
15808     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15809       return;
15810     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15811         RHSDeclRef->getDecl()->getCanonicalDecl())
15812       return;
15813 
15814     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15815                                         << LHSExpr->getSourceRange()
15816                                         << RHSExpr->getSourceRange();
15817     return;
15818   }
15819 
15820   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15821     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15822                                         << LHSExpr->getSourceRange()
15823                                         << RHSExpr->getSourceRange();
15824 }
15825 
15826 //===--- Layout compatibility ----------------------------------------------//
15827 
15828 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15829 
15830 /// Check if two enumeration types are layout-compatible.
15831 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15832   // C++11 [dcl.enum] p8:
15833   // Two enumeration types are layout-compatible if they have the same
15834   // underlying type.
15835   return ED1->isComplete() && ED2->isComplete() &&
15836          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15837 }
15838 
15839 /// Check if two fields are layout-compatible.
15840 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15841                                FieldDecl *Field2) {
15842   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15843     return false;
15844 
15845   if (Field1->isBitField() != Field2->isBitField())
15846     return false;
15847 
15848   if (Field1->isBitField()) {
15849     // Make sure that the bit-fields are the same length.
15850     unsigned Bits1 = Field1->getBitWidthValue(C);
15851     unsigned Bits2 = Field2->getBitWidthValue(C);
15852 
15853     if (Bits1 != Bits2)
15854       return false;
15855   }
15856 
15857   return true;
15858 }
15859 
15860 /// Check if two standard-layout structs are layout-compatible.
15861 /// (C++11 [class.mem] p17)
15862 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15863                                      RecordDecl *RD2) {
15864   // If both records are C++ classes, check that base classes match.
15865   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15866     // If one of records is a CXXRecordDecl we are in C++ mode,
15867     // thus the other one is a CXXRecordDecl, too.
15868     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15869     // Check number of base classes.
15870     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15871       return false;
15872 
15873     // Check the base classes.
15874     for (CXXRecordDecl::base_class_const_iterator
15875                Base1 = D1CXX->bases_begin(),
15876            BaseEnd1 = D1CXX->bases_end(),
15877               Base2 = D2CXX->bases_begin();
15878          Base1 != BaseEnd1;
15879          ++Base1, ++Base2) {
15880       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15881         return false;
15882     }
15883   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15884     // If only RD2 is a C++ class, it should have zero base classes.
15885     if (D2CXX->getNumBases() > 0)
15886       return false;
15887   }
15888 
15889   // Check the fields.
15890   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15891                              Field2End = RD2->field_end(),
15892                              Field1 = RD1->field_begin(),
15893                              Field1End = RD1->field_end();
15894   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15895     if (!isLayoutCompatible(C, *Field1, *Field2))
15896       return false;
15897   }
15898   if (Field1 != Field1End || Field2 != Field2End)
15899     return false;
15900 
15901   return true;
15902 }
15903 
15904 /// Check if two standard-layout unions are layout-compatible.
15905 /// (C++11 [class.mem] p18)
15906 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15907                                     RecordDecl *RD2) {
15908   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15909   for (auto *Field2 : RD2->fields())
15910     UnmatchedFields.insert(Field2);
15911 
15912   for (auto *Field1 : RD1->fields()) {
15913     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15914         I = UnmatchedFields.begin(),
15915         E = UnmatchedFields.end();
15916 
15917     for ( ; I != E; ++I) {
15918       if (isLayoutCompatible(C, Field1, *I)) {
15919         bool Result = UnmatchedFields.erase(*I);
15920         (void) Result;
15921         assert(Result);
15922         break;
15923       }
15924     }
15925     if (I == E)
15926       return false;
15927   }
15928 
15929   return UnmatchedFields.empty();
15930 }
15931 
15932 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15933                                RecordDecl *RD2) {
15934   if (RD1->isUnion() != RD2->isUnion())
15935     return false;
15936 
15937   if (RD1->isUnion())
15938     return isLayoutCompatibleUnion(C, RD1, RD2);
15939   else
15940     return isLayoutCompatibleStruct(C, RD1, RD2);
15941 }
15942 
15943 /// Check if two types are layout-compatible in C++11 sense.
15944 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15945   if (T1.isNull() || T2.isNull())
15946     return false;
15947 
15948   // C++11 [basic.types] p11:
15949   // If two types T1 and T2 are the same type, then T1 and T2 are
15950   // layout-compatible types.
15951   if (C.hasSameType(T1, T2))
15952     return true;
15953 
15954   T1 = T1.getCanonicalType().getUnqualifiedType();
15955   T2 = T2.getCanonicalType().getUnqualifiedType();
15956 
15957   const Type::TypeClass TC1 = T1->getTypeClass();
15958   const Type::TypeClass TC2 = T2->getTypeClass();
15959 
15960   if (TC1 != TC2)
15961     return false;
15962 
15963   if (TC1 == Type::Enum) {
15964     return isLayoutCompatible(C,
15965                               cast<EnumType>(T1)->getDecl(),
15966                               cast<EnumType>(T2)->getDecl());
15967   } else if (TC1 == Type::Record) {
15968     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15969       return false;
15970 
15971     return isLayoutCompatible(C,
15972                               cast<RecordType>(T1)->getDecl(),
15973                               cast<RecordType>(T2)->getDecl());
15974   }
15975 
15976   return false;
15977 }
15978 
15979 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15980 
15981 /// Given a type tag expression find the type tag itself.
15982 ///
15983 /// \param TypeExpr Type tag expression, as it appears in user's code.
15984 ///
15985 /// \param VD Declaration of an identifier that appears in a type tag.
15986 ///
15987 /// \param MagicValue Type tag magic value.
15988 ///
15989 /// \param isConstantEvaluated wether the evalaution should be performed in
15990 
15991 /// constant context.
15992 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15993                             const ValueDecl **VD, uint64_t *MagicValue,
15994                             bool isConstantEvaluated) {
15995   while(true) {
15996     if (!TypeExpr)
15997       return false;
15998 
15999     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16000 
16001     switch (TypeExpr->getStmtClass()) {
16002     case Stmt::UnaryOperatorClass: {
16003       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16004       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16005         TypeExpr = UO->getSubExpr();
16006         continue;
16007       }
16008       return false;
16009     }
16010 
16011     case Stmt::DeclRefExprClass: {
16012       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16013       *VD = DRE->getDecl();
16014       return true;
16015     }
16016 
16017     case Stmt::IntegerLiteralClass: {
16018       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16019       llvm::APInt MagicValueAPInt = IL->getValue();
16020       if (MagicValueAPInt.getActiveBits() <= 64) {
16021         *MagicValue = MagicValueAPInt.getZExtValue();
16022         return true;
16023       } else
16024         return false;
16025     }
16026 
16027     case Stmt::BinaryConditionalOperatorClass:
16028     case Stmt::ConditionalOperatorClass: {
16029       const AbstractConditionalOperator *ACO =
16030           cast<AbstractConditionalOperator>(TypeExpr);
16031       bool Result;
16032       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16033                                                      isConstantEvaluated)) {
16034         if (Result)
16035           TypeExpr = ACO->getTrueExpr();
16036         else
16037           TypeExpr = ACO->getFalseExpr();
16038         continue;
16039       }
16040       return false;
16041     }
16042 
16043     case Stmt::BinaryOperatorClass: {
16044       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16045       if (BO->getOpcode() == BO_Comma) {
16046         TypeExpr = BO->getRHS();
16047         continue;
16048       }
16049       return false;
16050     }
16051 
16052     default:
16053       return false;
16054     }
16055   }
16056 }
16057 
16058 /// Retrieve the C type corresponding to type tag TypeExpr.
16059 ///
16060 /// \param TypeExpr Expression that specifies a type tag.
16061 ///
16062 /// \param MagicValues Registered magic values.
16063 ///
16064 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16065 ///        kind.
16066 ///
16067 /// \param TypeInfo Information about the corresponding C type.
16068 ///
16069 /// \param isConstantEvaluated wether the evalaution should be performed in
16070 /// constant context.
16071 ///
16072 /// \returns true if the corresponding C type was found.
16073 static bool GetMatchingCType(
16074     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16075     const ASTContext &Ctx,
16076     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16077         *MagicValues,
16078     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16079     bool isConstantEvaluated) {
16080   FoundWrongKind = false;
16081 
16082   // Variable declaration that has type_tag_for_datatype attribute.
16083   const ValueDecl *VD = nullptr;
16084 
16085   uint64_t MagicValue;
16086 
16087   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16088     return false;
16089 
16090   if (VD) {
16091     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16092       if (I->getArgumentKind() != ArgumentKind) {
16093         FoundWrongKind = true;
16094         return false;
16095       }
16096       TypeInfo.Type = I->getMatchingCType();
16097       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16098       TypeInfo.MustBeNull = I->getMustBeNull();
16099       return true;
16100     }
16101     return false;
16102   }
16103 
16104   if (!MagicValues)
16105     return false;
16106 
16107   llvm::DenseMap<Sema::TypeTagMagicValue,
16108                  Sema::TypeTagData>::const_iterator I =
16109       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16110   if (I == MagicValues->end())
16111     return false;
16112 
16113   TypeInfo = I->second;
16114   return true;
16115 }
16116 
16117 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16118                                       uint64_t MagicValue, QualType Type,
16119                                       bool LayoutCompatible,
16120                                       bool MustBeNull) {
16121   if (!TypeTagForDatatypeMagicValues)
16122     TypeTagForDatatypeMagicValues.reset(
16123         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16124 
16125   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16126   (*TypeTagForDatatypeMagicValues)[Magic] =
16127       TypeTagData(Type, LayoutCompatible, MustBeNull);
16128 }
16129 
16130 static bool IsSameCharType(QualType T1, QualType T2) {
16131   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16132   if (!BT1)
16133     return false;
16134 
16135   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16136   if (!BT2)
16137     return false;
16138 
16139   BuiltinType::Kind T1Kind = BT1->getKind();
16140   BuiltinType::Kind T2Kind = BT2->getKind();
16141 
16142   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16143          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16144          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16145          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16146 }
16147 
16148 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16149                                     const ArrayRef<const Expr *> ExprArgs,
16150                                     SourceLocation CallSiteLoc) {
16151   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16152   bool IsPointerAttr = Attr->getIsPointer();
16153 
16154   // Retrieve the argument representing the 'type_tag'.
16155   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16156   if (TypeTagIdxAST >= ExprArgs.size()) {
16157     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16158         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16159     return;
16160   }
16161   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16162   bool FoundWrongKind;
16163   TypeTagData TypeInfo;
16164   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16165                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16166                         TypeInfo, isConstantEvaluated())) {
16167     if (FoundWrongKind)
16168       Diag(TypeTagExpr->getExprLoc(),
16169            diag::warn_type_tag_for_datatype_wrong_kind)
16170         << TypeTagExpr->getSourceRange();
16171     return;
16172   }
16173 
16174   // Retrieve the argument representing the 'arg_idx'.
16175   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16176   if (ArgumentIdxAST >= ExprArgs.size()) {
16177     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16178         << 1 << Attr->getArgumentIdx().getSourceIndex();
16179     return;
16180   }
16181   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16182   if (IsPointerAttr) {
16183     // Skip implicit cast of pointer to `void *' (as a function argument).
16184     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16185       if (ICE->getType()->isVoidPointerType() &&
16186           ICE->getCastKind() == CK_BitCast)
16187         ArgumentExpr = ICE->getSubExpr();
16188   }
16189   QualType ArgumentType = ArgumentExpr->getType();
16190 
16191   // Passing a `void*' pointer shouldn't trigger a warning.
16192   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16193     return;
16194 
16195   if (TypeInfo.MustBeNull) {
16196     // Type tag with matching void type requires a null pointer.
16197     if (!ArgumentExpr->isNullPointerConstant(Context,
16198                                              Expr::NPC_ValueDependentIsNotNull)) {
16199       Diag(ArgumentExpr->getExprLoc(),
16200            diag::warn_type_safety_null_pointer_required)
16201           << ArgumentKind->getName()
16202           << ArgumentExpr->getSourceRange()
16203           << TypeTagExpr->getSourceRange();
16204     }
16205     return;
16206   }
16207 
16208   QualType RequiredType = TypeInfo.Type;
16209   if (IsPointerAttr)
16210     RequiredType = Context.getPointerType(RequiredType);
16211 
16212   bool mismatch = false;
16213   if (!TypeInfo.LayoutCompatible) {
16214     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16215 
16216     // C++11 [basic.fundamental] p1:
16217     // Plain char, signed char, and unsigned char are three distinct types.
16218     //
16219     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16220     // char' depending on the current char signedness mode.
16221     if (mismatch)
16222       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16223                                            RequiredType->getPointeeType())) ||
16224           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16225         mismatch = false;
16226   } else
16227     if (IsPointerAttr)
16228       mismatch = !isLayoutCompatible(Context,
16229                                      ArgumentType->getPointeeType(),
16230                                      RequiredType->getPointeeType());
16231     else
16232       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16233 
16234   if (mismatch)
16235     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16236         << ArgumentType << ArgumentKind
16237         << TypeInfo.LayoutCompatible << RequiredType
16238         << ArgumentExpr->getSourceRange()
16239         << TypeTagExpr->getSourceRange();
16240 }
16241 
16242 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16243                                          CharUnits Alignment) {
16244   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16245 }
16246 
16247 void Sema::DiagnoseMisalignedMembers() {
16248   for (MisalignedMember &m : MisalignedMembers) {
16249     const NamedDecl *ND = m.RD;
16250     if (ND->getName().empty()) {
16251       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16252         ND = TD;
16253     }
16254     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16255         << m.MD << ND << m.E->getSourceRange();
16256   }
16257   MisalignedMembers.clear();
16258 }
16259 
16260 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16261   E = E->IgnoreParens();
16262   if (!T->isPointerType() && !T->isIntegerType())
16263     return;
16264   if (isa<UnaryOperator>(E) &&
16265       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16266     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16267     if (isa<MemberExpr>(Op)) {
16268       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16269       if (MA != MisalignedMembers.end() &&
16270           (T->isIntegerType() ||
16271            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16272                                    Context.getTypeAlignInChars(
16273                                        T->getPointeeType()) <= MA->Alignment))))
16274         MisalignedMembers.erase(MA);
16275     }
16276   }
16277 }
16278 
16279 void Sema::RefersToMemberWithReducedAlignment(
16280     Expr *E,
16281     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16282         Action) {
16283   const auto *ME = dyn_cast<MemberExpr>(E);
16284   if (!ME)
16285     return;
16286 
16287   // No need to check expressions with an __unaligned-qualified type.
16288   if (E->getType().getQualifiers().hasUnaligned())
16289     return;
16290 
16291   // For a chain of MemberExpr like "a.b.c.d" this list
16292   // will keep FieldDecl's like [d, c, b].
16293   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16294   const MemberExpr *TopME = nullptr;
16295   bool AnyIsPacked = false;
16296   do {
16297     QualType BaseType = ME->getBase()->getType();
16298     if (BaseType->isDependentType())
16299       return;
16300     if (ME->isArrow())
16301       BaseType = BaseType->getPointeeType();
16302     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16303     if (RD->isInvalidDecl())
16304       return;
16305 
16306     ValueDecl *MD = ME->getMemberDecl();
16307     auto *FD = dyn_cast<FieldDecl>(MD);
16308     // We do not care about non-data members.
16309     if (!FD || FD->isInvalidDecl())
16310       return;
16311 
16312     AnyIsPacked =
16313         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16314     ReverseMemberChain.push_back(FD);
16315 
16316     TopME = ME;
16317     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16318   } while (ME);
16319   assert(TopME && "We did not compute a topmost MemberExpr!");
16320 
16321   // Not the scope of this diagnostic.
16322   if (!AnyIsPacked)
16323     return;
16324 
16325   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16326   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16327   // TODO: The innermost base of the member expression may be too complicated.
16328   // For now, just disregard these cases. This is left for future
16329   // improvement.
16330   if (!DRE && !isa<CXXThisExpr>(TopBase))
16331       return;
16332 
16333   // Alignment expected by the whole expression.
16334   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16335 
16336   // No need to do anything else with this case.
16337   if (ExpectedAlignment.isOne())
16338     return;
16339 
16340   // Synthesize offset of the whole access.
16341   CharUnits Offset;
16342   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16343        I++) {
16344     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16345   }
16346 
16347   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16348   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16349       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16350 
16351   // The base expression of the innermost MemberExpr may give
16352   // stronger guarantees than the class containing the member.
16353   if (DRE && !TopME->isArrow()) {
16354     const ValueDecl *VD = DRE->getDecl();
16355     if (!VD->getType()->isReferenceType())
16356       CompleteObjectAlignment =
16357           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16358   }
16359 
16360   // Check if the synthesized offset fulfills the alignment.
16361   if (Offset % ExpectedAlignment != 0 ||
16362       // It may fulfill the offset it but the effective alignment may still be
16363       // lower than the expected expression alignment.
16364       CompleteObjectAlignment < ExpectedAlignment) {
16365     // If this happens, we want to determine a sensible culprit of this.
16366     // Intuitively, watching the chain of member expressions from right to
16367     // left, we start with the required alignment (as required by the field
16368     // type) but some packed attribute in that chain has reduced the alignment.
16369     // It may happen that another packed structure increases it again. But if
16370     // we are here such increase has not been enough. So pointing the first
16371     // FieldDecl that either is packed or else its RecordDecl is,
16372     // seems reasonable.
16373     FieldDecl *FD = nullptr;
16374     CharUnits Alignment;
16375     for (FieldDecl *FDI : ReverseMemberChain) {
16376       if (FDI->hasAttr<PackedAttr>() ||
16377           FDI->getParent()->hasAttr<PackedAttr>()) {
16378         FD = FDI;
16379         Alignment = std::min(
16380             Context.getTypeAlignInChars(FD->getType()),
16381             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16382         break;
16383       }
16384     }
16385     assert(FD && "We did not find a packed FieldDecl!");
16386     Action(E, FD->getParent(), FD, Alignment);
16387   }
16388 }
16389 
16390 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16391   using namespace std::placeholders;
16392 
16393   RefersToMemberWithReducedAlignment(
16394       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16395                      _2, _3, _4));
16396 }
16397 
16398 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16399                                             ExprResult CallResult) {
16400   if (checkArgCount(*this, TheCall, 1))
16401     return ExprError();
16402 
16403   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16404   if (MatrixArg.isInvalid())
16405     return MatrixArg;
16406   Expr *Matrix = MatrixArg.get();
16407 
16408   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16409   if (!MType) {
16410     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16411     return ExprError();
16412   }
16413 
16414   // Create returned matrix type by swapping rows and columns of the argument
16415   // matrix type.
16416   QualType ResultType = Context.getConstantMatrixType(
16417       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16418 
16419   // Change the return type to the type of the returned matrix.
16420   TheCall->setType(ResultType);
16421 
16422   // Update call argument to use the possibly converted matrix argument.
16423   TheCall->setArg(0, Matrix);
16424   return CallResult;
16425 }
16426 
16427 // Get and verify the matrix dimensions.
16428 static llvm::Optional<unsigned>
16429 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16430   SourceLocation ErrorPos;
16431   Optional<llvm::APSInt> Value =
16432       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16433   if (!Value) {
16434     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16435         << Name;
16436     return {};
16437   }
16438   uint64_t Dim = Value->getZExtValue();
16439   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16440     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16441         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16442     return {};
16443   }
16444   return Dim;
16445 }
16446 
16447 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16448                                                   ExprResult CallResult) {
16449   if (!getLangOpts().MatrixTypes) {
16450     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16451     return ExprError();
16452   }
16453 
16454   if (checkArgCount(*this, TheCall, 4))
16455     return ExprError();
16456 
16457   unsigned PtrArgIdx = 0;
16458   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16459   Expr *RowsExpr = TheCall->getArg(1);
16460   Expr *ColumnsExpr = TheCall->getArg(2);
16461   Expr *StrideExpr = TheCall->getArg(3);
16462 
16463   bool ArgError = false;
16464 
16465   // Check pointer argument.
16466   {
16467     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16468     if (PtrConv.isInvalid())
16469       return PtrConv;
16470     PtrExpr = PtrConv.get();
16471     TheCall->setArg(0, PtrExpr);
16472     if (PtrExpr->isTypeDependent()) {
16473       TheCall->setType(Context.DependentTy);
16474       return TheCall;
16475     }
16476   }
16477 
16478   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16479   QualType ElementTy;
16480   if (!PtrTy) {
16481     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16482         << PtrArgIdx + 1;
16483     ArgError = true;
16484   } else {
16485     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16486 
16487     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16488       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16489           << PtrArgIdx + 1;
16490       ArgError = true;
16491     }
16492   }
16493 
16494   // Apply default Lvalue conversions and convert the expression to size_t.
16495   auto ApplyArgumentConversions = [this](Expr *E) {
16496     ExprResult Conv = DefaultLvalueConversion(E);
16497     if (Conv.isInvalid())
16498       return Conv;
16499 
16500     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16501   };
16502 
16503   // Apply conversion to row and column expressions.
16504   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16505   if (!RowsConv.isInvalid()) {
16506     RowsExpr = RowsConv.get();
16507     TheCall->setArg(1, RowsExpr);
16508   } else
16509     RowsExpr = nullptr;
16510 
16511   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16512   if (!ColumnsConv.isInvalid()) {
16513     ColumnsExpr = ColumnsConv.get();
16514     TheCall->setArg(2, ColumnsExpr);
16515   } else
16516     ColumnsExpr = nullptr;
16517 
16518   // If any any part of the result matrix type is still pending, just use
16519   // Context.DependentTy, until all parts are resolved.
16520   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16521       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16522     TheCall->setType(Context.DependentTy);
16523     return CallResult;
16524   }
16525 
16526   // Check row and column dimenions.
16527   llvm::Optional<unsigned> MaybeRows;
16528   if (RowsExpr)
16529     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16530 
16531   llvm::Optional<unsigned> MaybeColumns;
16532   if (ColumnsExpr)
16533     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16534 
16535   // Check stride argument.
16536   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16537   if (StrideConv.isInvalid())
16538     return ExprError();
16539   StrideExpr = StrideConv.get();
16540   TheCall->setArg(3, StrideExpr);
16541 
16542   if (MaybeRows) {
16543     if (Optional<llvm::APSInt> Value =
16544             StrideExpr->getIntegerConstantExpr(Context)) {
16545       uint64_t Stride = Value->getZExtValue();
16546       if (Stride < *MaybeRows) {
16547         Diag(StrideExpr->getBeginLoc(),
16548              diag::err_builtin_matrix_stride_too_small);
16549         ArgError = true;
16550       }
16551     }
16552   }
16553 
16554   if (ArgError || !MaybeRows || !MaybeColumns)
16555     return ExprError();
16556 
16557   TheCall->setType(
16558       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16559   return CallResult;
16560 }
16561 
16562 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16563                                                    ExprResult CallResult) {
16564   if (checkArgCount(*this, TheCall, 3))
16565     return ExprError();
16566 
16567   unsigned PtrArgIdx = 1;
16568   Expr *MatrixExpr = TheCall->getArg(0);
16569   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16570   Expr *StrideExpr = TheCall->getArg(2);
16571 
16572   bool ArgError = false;
16573 
16574   {
16575     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16576     if (MatrixConv.isInvalid())
16577       return MatrixConv;
16578     MatrixExpr = MatrixConv.get();
16579     TheCall->setArg(0, MatrixExpr);
16580   }
16581   if (MatrixExpr->isTypeDependent()) {
16582     TheCall->setType(Context.DependentTy);
16583     return TheCall;
16584   }
16585 
16586   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16587   if (!MatrixTy) {
16588     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16589     ArgError = true;
16590   }
16591 
16592   {
16593     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16594     if (PtrConv.isInvalid())
16595       return PtrConv;
16596     PtrExpr = PtrConv.get();
16597     TheCall->setArg(1, PtrExpr);
16598     if (PtrExpr->isTypeDependent()) {
16599       TheCall->setType(Context.DependentTy);
16600       return TheCall;
16601     }
16602   }
16603 
16604   // Check pointer argument.
16605   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16606   if (!PtrTy) {
16607     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16608         << PtrArgIdx + 1;
16609     ArgError = true;
16610   } else {
16611     QualType ElementTy = PtrTy->getPointeeType();
16612     if (ElementTy.isConstQualified()) {
16613       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16614       ArgError = true;
16615     }
16616     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16617     if (MatrixTy &&
16618         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16619       Diag(PtrExpr->getBeginLoc(),
16620            diag::err_builtin_matrix_pointer_arg_mismatch)
16621           << ElementTy << MatrixTy->getElementType();
16622       ArgError = true;
16623     }
16624   }
16625 
16626   // Apply default Lvalue conversions and convert the stride expression to
16627   // size_t.
16628   {
16629     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16630     if (StrideConv.isInvalid())
16631       return StrideConv;
16632 
16633     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16634     if (StrideConv.isInvalid())
16635       return StrideConv;
16636     StrideExpr = StrideConv.get();
16637     TheCall->setArg(2, StrideExpr);
16638   }
16639 
16640   // Check stride argument.
16641   if (MatrixTy) {
16642     if (Optional<llvm::APSInt> Value =
16643             StrideExpr->getIntegerConstantExpr(Context)) {
16644       uint64_t Stride = Value->getZExtValue();
16645       if (Stride < MatrixTy->getNumRows()) {
16646         Diag(StrideExpr->getBeginLoc(),
16647              diag::err_builtin_matrix_stride_too_small);
16648         ArgError = true;
16649       }
16650     }
16651   }
16652 
16653   if (ArgError)
16654     return ExprError();
16655 
16656   return CallResult;
16657 }
16658 
16659 /// \brief Enforce the bounds of a TCB
16660 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16661 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16662 /// and enforce_tcb_leaf attributes.
16663 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16664                                const FunctionDecl *Callee) {
16665   const FunctionDecl *Caller = getCurFunctionDecl();
16666 
16667   // Calls to builtins are not enforced.
16668   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16669       Callee->getBuiltinID() != 0)
16670     return;
16671 
16672   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16673   // all TCBs the callee is a part of.
16674   llvm::StringSet<> CalleeTCBs;
16675   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16676            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16677   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16678            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16679 
16680   // Go through the TCBs the caller is a part of and emit warnings if Caller
16681   // is in a TCB that the Callee is not.
16682   for_each(
16683       Caller->specific_attrs<EnforceTCBAttr>(),
16684       [&](const auto *A) {
16685         StringRef CallerTCB = A->getTCBName();
16686         if (CalleeTCBs.count(CallerTCB) == 0) {
16687           this->Diag(TheCall->getExprLoc(),
16688                      diag::warn_tcb_enforcement_violation) << Callee
16689                                                            << CallerTCB;
16690         }
16691       });
16692 }
16693