1 //===- SemaChecking.cpp - Extra Semantic Checking -------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 //  This file implements extra semantic analysis beyond what is enforced
10 //  by the C type system.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/AST/APValue.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/AttrIterator.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclarationName.h"
24 #include "clang/AST/EvaluatedExprVisitor.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/ExprOpenMP.h"
29 #include "clang/AST/FormatString.h"
30 #include "clang/AST/NSAPI.h"
31 #include "clang/AST/NonTrivialTypeVisitor.h"
32 #include "clang/AST/OperationKinds.h"
33 #include "clang/AST/RecordLayout.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/TypeLoc.h"
38 #include "clang/AST/UnresolvedSet.h"
39 #include "clang/Basic/AddressSpaces.h"
40 #include "clang/Basic/CharInfo.h"
41 #include "clang/Basic/Diagnostic.h"
42 #include "clang/Basic/IdentifierTable.h"
43 #include "clang/Basic/LLVM.h"
44 #include "clang/Basic/LangOptions.h"
45 #include "clang/Basic/OpenCLOptions.h"
46 #include "clang/Basic/OperatorKinds.h"
47 #include "clang/Basic/PartialDiagnostic.h"
48 #include "clang/Basic/SourceLocation.h"
49 #include "clang/Basic/SourceManager.h"
50 #include "clang/Basic/Specifiers.h"
51 #include "clang/Basic/SyncScope.h"
52 #include "clang/Basic/TargetBuiltins.h"
53 #include "clang/Basic/TargetCXXABI.h"
54 #include "clang/Basic/TargetInfo.h"
55 #include "clang/Basic/TypeTraits.h"
56 #include "clang/Lex/Lexer.h" // TODO: Extract static functions to fix layering.
57 #include "clang/Sema/Initialization.h"
58 #include "clang/Sema/Lookup.h"
59 #include "clang/Sema/Ownership.h"
60 #include "clang/Sema/Scope.h"
61 #include "clang/Sema/ScopeInfo.h"
62 #include "clang/Sema/Sema.h"
63 #include "clang/Sema/SemaInternal.h"
64 #include "llvm/ADT/APFloat.h"
65 #include "llvm/ADT/APInt.h"
66 #include "llvm/ADT/APSInt.h"
67 #include "llvm/ADT/ArrayRef.h"
68 #include "llvm/ADT/DenseMap.h"
69 #include "llvm/ADT/FoldingSet.h"
70 #include "llvm/ADT/None.h"
71 #include "llvm/ADT/Optional.h"
72 #include "llvm/ADT/STLExtras.h"
73 #include "llvm/ADT/SmallBitVector.h"
74 #include "llvm/ADT/SmallPtrSet.h"
75 #include "llvm/ADT/SmallString.h"
76 #include "llvm/ADT/SmallVector.h"
77 #include "llvm/ADT/StringRef.h"
78 #include "llvm/ADT/StringSet.h"
79 #include "llvm/ADT/StringSwitch.h"
80 #include "llvm/ADT/Triple.h"
81 #include "llvm/Support/AtomicOrdering.h"
82 #include "llvm/Support/Casting.h"
83 #include "llvm/Support/Compiler.h"
84 #include "llvm/Support/ConvertUTF.h"
85 #include "llvm/Support/ErrorHandling.h"
86 #include "llvm/Support/Format.h"
87 #include "llvm/Support/Locale.h"
88 #include "llvm/Support/MathExtras.h"
89 #include "llvm/Support/SaveAndRestore.h"
90 #include "llvm/Support/raw_ostream.h"
91 #include <algorithm>
92 #include <bitset>
93 #include <cassert>
94 #include <cctype>
95 #include <cstddef>
96 #include <cstdint>
97 #include <functional>
98 #include <limits>
99 #include <string>
100 #include <tuple>
101 #include <utility>
102 
103 using namespace clang;
104 using namespace sema;
105 
106 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
107                                                     unsigned ByteNo) const {
108   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
109                                Context.getTargetInfo());
110 }
111 
112 /// Checks that a call expression's argument count is the desired number.
113 /// This is useful when doing custom type-checking.  Returns true on error.
114 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
115   unsigned argCount = call->getNumArgs();
116   if (argCount == desiredArgCount) return false;
117 
118   if (argCount < desiredArgCount)
119     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
120            << 0 /*function call*/ << desiredArgCount << argCount
121            << call->getSourceRange();
122 
123   // Highlight all the excess arguments.
124   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
125                     call->getArg(argCount - 1)->getEndLoc());
126 
127   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
128     << 0 /*function call*/ << desiredArgCount << argCount
129     << call->getArg(1)->getSourceRange();
130 }
131 
132 /// Check that the first argument to __builtin_annotation is an integer
133 /// and the second argument is a non-wide string literal.
134 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
135   if (checkArgCount(S, TheCall, 2))
136     return true;
137 
138   // First argument should be an integer.
139   Expr *ValArg = TheCall->getArg(0);
140   QualType Ty = ValArg->getType();
141   if (!Ty->isIntegerType()) {
142     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
143         << ValArg->getSourceRange();
144     return true;
145   }
146 
147   // Second argument should be a constant string.
148   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
149   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
150   if (!Literal || !Literal->isAscii()) {
151     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
152         << StrArg->getSourceRange();
153     return true;
154   }
155 
156   TheCall->setType(Ty);
157   return false;
158 }
159 
160 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
161   // We need at least one argument.
162   if (TheCall->getNumArgs() < 1) {
163     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
164         << 0 << 1 << TheCall->getNumArgs()
165         << TheCall->getCallee()->getSourceRange();
166     return true;
167   }
168 
169   // All arguments should be wide string literals.
170   for (Expr *Arg : TheCall->arguments()) {
171     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
172     if (!Literal || !Literal->isWide()) {
173       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
174           << Arg->getSourceRange();
175       return true;
176     }
177   }
178 
179   return false;
180 }
181 
182 /// Check that the argument to __builtin_addressof is a glvalue, and set the
183 /// result type to the corresponding pointer type.
184 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
185   if (checkArgCount(S, TheCall, 1))
186     return true;
187 
188   ExprResult Arg(TheCall->getArg(0));
189   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
190   if (ResultType.isNull())
191     return true;
192 
193   TheCall->setArg(0, Arg.get());
194   TheCall->setType(ResultType);
195   return false;
196 }
197 
198 /// Check the number of arguments and set the result type to
199 /// the argument type.
200 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
201   if (checkArgCount(S, TheCall, 1))
202     return true;
203 
204   TheCall->setType(TheCall->getArg(0)->getType());
205   return false;
206 }
207 
208 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
209 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
210 /// type (but not a function pointer) and that the alignment is a power-of-two.
211 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
212   if (checkArgCount(S, TheCall, 2))
213     return true;
214 
215   clang::Expr *Source = TheCall->getArg(0);
216   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
217 
218   auto IsValidIntegerType = [](QualType Ty) {
219     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
220   };
221   QualType SrcTy = Source->getType();
222   // We should also be able to use it with arrays (but not functions!).
223   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
224     SrcTy = S.Context.getDecayedType(SrcTy);
225   }
226   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
227       SrcTy->isFunctionPointerType()) {
228     // FIXME: this is not quite the right error message since we don't allow
229     // floating point types, or member pointers.
230     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
231         << SrcTy;
232     return true;
233   }
234 
235   clang::Expr *AlignOp = TheCall->getArg(1);
236   if (!IsValidIntegerType(AlignOp->getType())) {
237     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
238         << AlignOp->getType();
239     return true;
240   }
241   Expr::EvalResult AlignResult;
242   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
243   // We can't check validity of alignment if it is value dependent.
244   if (!AlignOp->isValueDependent() &&
245       AlignOp->EvaluateAsInt(AlignResult, S.Context,
246                              Expr::SE_AllowSideEffects)) {
247     llvm::APSInt AlignValue = AlignResult.Val.getInt();
248     llvm::APSInt MaxValue(
249         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
250     if (AlignValue < 1) {
251       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
252       return true;
253     }
254     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
255       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
256           << toString(MaxValue, 10);
257       return true;
258     }
259     if (!AlignValue.isPowerOf2()) {
260       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
261       return true;
262     }
263     if (AlignValue == 1) {
264       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
265           << IsBooleanAlignBuiltin;
266     }
267   }
268 
269   ExprResult SrcArg = S.PerformCopyInitialization(
270       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
271       SourceLocation(), Source);
272   if (SrcArg.isInvalid())
273     return true;
274   TheCall->setArg(0, SrcArg.get());
275   ExprResult AlignArg =
276       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
277                                       S.Context, AlignOp->getType(), false),
278                                   SourceLocation(), AlignOp);
279   if (AlignArg.isInvalid())
280     return true;
281   TheCall->setArg(1, AlignArg.get());
282   // For align_up/align_down, the return type is the same as the (potentially
283   // decayed) argument type including qualifiers. For is_aligned(), the result
284   // is always bool.
285   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
286   return false;
287 }
288 
289 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
290                                 unsigned BuiltinID) {
291   if (checkArgCount(S, TheCall, 3))
292     return true;
293 
294   // First two arguments should be integers.
295   for (unsigned I = 0; I < 2; ++I) {
296     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
297     if (Arg.isInvalid()) return true;
298     TheCall->setArg(I, Arg.get());
299 
300     QualType Ty = Arg.get()->getType();
301     if (!Ty->isIntegerType()) {
302       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
303           << Ty << Arg.get()->getSourceRange();
304       return true;
305     }
306   }
307 
308   // Third argument should be a pointer to a non-const integer.
309   // IRGen correctly handles volatile, restrict, and address spaces, and
310   // the other qualifiers aren't possible.
311   {
312     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
313     if (Arg.isInvalid()) return true;
314     TheCall->setArg(2, Arg.get());
315 
316     QualType Ty = Arg.get()->getType();
317     const auto *PtrTy = Ty->getAs<PointerType>();
318     if (!PtrTy ||
319         !PtrTy->getPointeeType()->isIntegerType() ||
320         PtrTy->getPointeeType().isConstQualified()) {
321       S.Diag(Arg.get()->getBeginLoc(),
322              diag::err_overflow_builtin_must_be_ptr_int)
323         << Ty << Arg.get()->getSourceRange();
324       return true;
325     }
326   }
327 
328   // Disallow signed ExtIntType args larger than 128 bits to mul function until
329   // we improve backend support.
330   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
331     for (unsigned I = 0; I < 3; ++I) {
332       const auto Arg = TheCall->getArg(I);
333       // Third argument will be a pointer.
334       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
335       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
336           S.getASTContext().getIntWidth(Ty) > 128)
337         return S.Diag(Arg->getBeginLoc(),
338                       diag::err_overflow_builtin_ext_int_max_size)
339                << 128;
340     }
341   }
342 
343   return false;
344 }
345 
346 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
347   if (checkArgCount(S, BuiltinCall, 2))
348     return true;
349 
350   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
351   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
352   Expr *Call = BuiltinCall->getArg(0);
353   Expr *Chain = BuiltinCall->getArg(1);
354 
355   if (Call->getStmtClass() != Stmt::CallExprClass) {
356     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
357         << Call->getSourceRange();
358     return true;
359   }
360 
361   auto CE = cast<CallExpr>(Call);
362   if (CE->getCallee()->getType()->isBlockPointerType()) {
363     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
364         << Call->getSourceRange();
365     return true;
366   }
367 
368   const Decl *TargetDecl = CE->getCalleeDecl();
369   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
370     if (FD->getBuiltinID()) {
371       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
372           << Call->getSourceRange();
373       return true;
374     }
375 
376   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
377     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
378         << Call->getSourceRange();
379     return true;
380   }
381 
382   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
383   if (ChainResult.isInvalid())
384     return true;
385   if (!ChainResult.get()->getType()->isPointerType()) {
386     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
387         << Chain->getSourceRange();
388     return true;
389   }
390 
391   QualType ReturnTy = CE->getCallReturnType(S.Context);
392   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
393   QualType BuiltinTy = S.Context.getFunctionType(
394       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
395   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
396 
397   Builtin =
398       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
399 
400   BuiltinCall->setType(CE->getType());
401   BuiltinCall->setValueKind(CE->getValueKind());
402   BuiltinCall->setObjectKind(CE->getObjectKind());
403   BuiltinCall->setCallee(Builtin);
404   BuiltinCall->setArg(1, ChainResult.get());
405 
406   return false;
407 }
408 
409 namespace {
410 
411 class EstimateSizeFormatHandler
412     : public analyze_format_string::FormatStringHandler {
413   size_t Size;
414 
415 public:
416   EstimateSizeFormatHandler(StringRef Format)
417       : Size(std::min(Format.find(0), Format.size()) +
418              1 /* null byte always written by sprintf */) {}
419 
420   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
421                              const char *, unsigned SpecifierLen) override {
422 
423     const size_t FieldWidth = computeFieldWidth(FS);
424     const size_t Precision = computePrecision(FS);
425 
426     // The actual format.
427     switch (FS.getConversionSpecifier().getKind()) {
428     // Just a char.
429     case analyze_format_string::ConversionSpecifier::cArg:
430     case analyze_format_string::ConversionSpecifier::CArg:
431       Size += std::max(FieldWidth, (size_t)1);
432       break;
433     // Just an integer.
434     case analyze_format_string::ConversionSpecifier::dArg:
435     case analyze_format_string::ConversionSpecifier::DArg:
436     case analyze_format_string::ConversionSpecifier::iArg:
437     case analyze_format_string::ConversionSpecifier::oArg:
438     case analyze_format_string::ConversionSpecifier::OArg:
439     case analyze_format_string::ConversionSpecifier::uArg:
440     case analyze_format_string::ConversionSpecifier::UArg:
441     case analyze_format_string::ConversionSpecifier::xArg:
442     case analyze_format_string::ConversionSpecifier::XArg:
443       Size += std::max(FieldWidth, Precision);
444       break;
445 
446     // %g style conversion switches between %f or %e style dynamically.
447     // %f always takes less space, so default to it.
448     case analyze_format_string::ConversionSpecifier::gArg:
449     case analyze_format_string::ConversionSpecifier::GArg:
450 
451     // Floating point number in the form '[+]ddd.ddd'.
452     case analyze_format_string::ConversionSpecifier::fArg:
453     case analyze_format_string::ConversionSpecifier::FArg:
454       Size += std::max(FieldWidth, 1 /* integer part */ +
455                                        (Precision ? 1 + Precision
456                                                   : 0) /* period + decimal */);
457       break;
458 
459     // Floating point number in the form '[-]d.ddde[+-]dd'.
460     case analyze_format_string::ConversionSpecifier::eArg:
461     case analyze_format_string::ConversionSpecifier::EArg:
462       Size +=
463           std::max(FieldWidth,
464                    1 /* integer part */ +
465                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
466                        1 /* e or E letter */ + 2 /* exponent */);
467       break;
468 
469     // Floating point number in the form '[-]0xh.hhhhp±dd'.
470     case analyze_format_string::ConversionSpecifier::aArg:
471     case analyze_format_string::ConversionSpecifier::AArg:
472       Size +=
473           std::max(FieldWidth,
474                    2 /* 0x */ + 1 /* integer part */ +
475                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
476                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
477       break;
478 
479     // Just a string.
480     case analyze_format_string::ConversionSpecifier::sArg:
481     case analyze_format_string::ConversionSpecifier::SArg:
482       Size += FieldWidth;
483       break;
484 
485     // Just a pointer in the form '0xddd'.
486     case analyze_format_string::ConversionSpecifier::pArg:
487       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
488       break;
489 
490     // A plain percent.
491     case analyze_format_string::ConversionSpecifier::PercentArg:
492       Size += 1;
493       break;
494 
495     default:
496       break;
497     }
498 
499     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
500 
501     if (FS.hasAlternativeForm()) {
502       switch (FS.getConversionSpecifier().getKind()) {
503       default:
504         break;
505       // Force a leading '0'.
506       case analyze_format_string::ConversionSpecifier::oArg:
507         Size += 1;
508         break;
509       // Force a leading '0x'.
510       case analyze_format_string::ConversionSpecifier::xArg:
511       case analyze_format_string::ConversionSpecifier::XArg:
512         Size += 2;
513         break;
514       // Force a period '.' before decimal, even if precision is 0.
515       case analyze_format_string::ConversionSpecifier::aArg:
516       case analyze_format_string::ConversionSpecifier::AArg:
517       case analyze_format_string::ConversionSpecifier::eArg:
518       case analyze_format_string::ConversionSpecifier::EArg:
519       case analyze_format_string::ConversionSpecifier::fArg:
520       case analyze_format_string::ConversionSpecifier::FArg:
521       case analyze_format_string::ConversionSpecifier::gArg:
522       case analyze_format_string::ConversionSpecifier::GArg:
523         Size += (Precision ? 0 : 1);
524         break;
525       }
526     }
527     assert(SpecifierLen <= Size && "no underflow");
528     Size -= SpecifierLen;
529     return true;
530   }
531 
532   size_t getSizeLowerBound() const { return Size; }
533 
534 private:
535   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
536     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
537     size_t FieldWidth = 0;
538     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
539       FieldWidth = FW.getConstantAmount();
540     return FieldWidth;
541   }
542 
543   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
544     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
545     size_t Precision = 0;
546 
547     // See man 3 printf for default precision value based on the specifier.
548     switch (FW.getHowSpecified()) {
549     case analyze_format_string::OptionalAmount::NotSpecified:
550       switch (FS.getConversionSpecifier().getKind()) {
551       default:
552         break;
553       case analyze_format_string::ConversionSpecifier::dArg: // %d
554       case analyze_format_string::ConversionSpecifier::DArg: // %D
555       case analyze_format_string::ConversionSpecifier::iArg: // %i
556         Precision = 1;
557         break;
558       case analyze_format_string::ConversionSpecifier::oArg: // %d
559       case analyze_format_string::ConversionSpecifier::OArg: // %D
560       case analyze_format_string::ConversionSpecifier::uArg: // %d
561       case analyze_format_string::ConversionSpecifier::UArg: // %D
562       case analyze_format_string::ConversionSpecifier::xArg: // %d
563       case analyze_format_string::ConversionSpecifier::XArg: // %D
564         Precision = 1;
565         break;
566       case analyze_format_string::ConversionSpecifier::fArg: // %f
567       case analyze_format_string::ConversionSpecifier::FArg: // %F
568       case analyze_format_string::ConversionSpecifier::eArg: // %e
569       case analyze_format_string::ConversionSpecifier::EArg: // %E
570       case analyze_format_string::ConversionSpecifier::gArg: // %g
571       case analyze_format_string::ConversionSpecifier::GArg: // %G
572         Precision = 6;
573         break;
574       case analyze_format_string::ConversionSpecifier::pArg: // %d
575         Precision = 1;
576         break;
577       }
578       break;
579     case analyze_format_string::OptionalAmount::Constant:
580       Precision = FW.getConstantAmount();
581       break;
582     default:
583       break;
584     }
585     return Precision;
586   }
587 };
588 
589 } // namespace
590 
591 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
592                                                CallExpr *TheCall) {
593   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
594       isConstantEvaluated())
595     return;
596 
597   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
598   if (!BuiltinID)
599     return;
600 
601   const TargetInfo &TI = getASTContext().getTargetInfo();
602   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
603 
604   auto ComputeExplicitObjectSizeArgument =
605       [&](unsigned Index) -> Optional<llvm::APSInt> {
606     Expr::EvalResult Result;
607     Expr *SizeArg = TheCall->getArg(Index);
608     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
609       return llvm::None;
610     return Result.Val.getInt();
611   };
612 
613   auto ComputeSizeArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
614     // If the parameter has a pass_object_size attribute, then we should use its
615     // (potentially) more strict checking mode. Otherwise, conservatively assume
616     // type 0.
617     int BOSType = 0;
618     if (const auto *POS =
619             FD->getParamDecl(Index)->getAttr<PassObjectSizeAttr>())
620       BOSType = POS->getType();
621 
622     const Expr *ObjArg = TheCall->getArg(Index);
623     uint64_t Result;
624     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
625       return llvm::None;
626 
627     // Get the object size in the target's size_t width.
628     return llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
629   };
630 
631   auto ComputeStrLenArgument = [&](unsigned Index) -> Optional<llvm::APSInt> {
632     Expr *ObjArg = TheCall->getArg(Index);
633     uint64_t Result;
634     if (!ObjArg->tryEvaluateStrLen(Result, getASTContext()))
635       return llvm::None;
636     // Add 1 for null byte.
637     return llvm::APSInt::getUnsigned(Result + 1).extOrTrunc(SizeTypeWidth);
638   };
639 
640   Optional<llvm::APSInt> SourceSize;
641   Optional<llvm::APSInt> DestinationSize;
642   unsigned DiagID = 0;
643   bool IsChkVariant = false;
644 
645   switch (BuiltinID) {
646   default:
647     return;
648   case Builtin::BI__builtin_strcpy:
649   case Builtin::BIstrcpy: {
650     DiagID = diag::warn_fortify_strlen_overflow;
651     SourceSize = ComputeStrLenArgument(1);
652     DestinationSize = ComputeSizeArgument(0);
653     break;
654   }
655 
656   case Builtin::BI__builtin___strcpy_chk: {
657     DiagID = diag::warn_fortify_strlen_overflow;
658     SourceSize = ComputeStrLenArgument(1);
659     DestinationSize = ComputeExplicitObjectSizeArgument(2);
660     IsChkVariant = true;
661     break;
662   }
663 
664   case Builtin::BIsprintf:
665   case Builtin::BI__builtin___sprintf_chk: {
666     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
667     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
668 
669     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
670 
671       if (!Format->isAscii() && !Format->isUTF8())
672         return;
673 
674       StringRef FormatStrRef = Format->getString();
675       EstimateSizeFormatHandler H(FormatStrRef);
676       const char *FormatBytes = FormatStrRef.data();
677       const ConstantArrayType *T =
678           Context.getAsConstantArrayType(Format->getType());
679       assert(T && "String literal not of constant array type!");
680       size_t TypeSize = T->getSize().getZExtValue();
681 
682       // In case there's a null byte somewhere.
683       size_t StrLen =
684           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
685       if (!analyze_format_string::ParsePrintfString(
686               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
687               Context.getTargetInfo(), false)) {
688         DiagID = diag::warn_fortify_source_format_overflow;
689         SourceSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
690                          .extOrTrunc(SizeTypeWidth);
691         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
692           DestinationSize = ComputeExplicitObjectSizeArgument(2);
693           IsChkVariant = true;
694         } else {
695           DestinationSize = ComputeSizeArgument(0);
696         }
697         break;
698       }
699     }
700     return;
701   }
702   case Builtin::BI__builtin___memcpy_chk:
703   case Builtin::BI__builtin___memmove_chk:
704   case Builtin::BI__builtin___memset_chk:
705   case Builtin::BI__builtin___strlcat_chk:
706   case Builtin::BI__builtin___strlcpy_chk:
707   case Builtin::BI__builtin___strncat_chk:
708   case Builtin::BI__builtin___strncpy_chk:
709   case Builtin::BI__builtin___stpncpy_chk:
710   case Builtin::BI__builtin___memccpy_chk:
711   case Builtin::BI__builtin___mempcpy_chk: {
712     DiagID = diag::warn_builtin_chk_overflow;
713     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 2);
714     DestinationSize =
715         ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
716     IsChkVariant = true;
717     break;
718   }
719 
720   case Builtin::BI__builtin___snprintf_chk:
721   case Builtin::BI__builtin___vsnprintf_chk: {
722     DiagID = diag::warn_builtin_chk_overflow;
723     SourceSize = ComputeExplicitObjectSizeArgument(1);
724     DestinationSize = ComputeExplicitObjectSizeArgument(3);
725     IsChkVariant = true;
726     break;
727   }
728 
729   case Builtin::BIstrncat:
730   case Builtin::BI__builtin_strncat:
731   case Builtin::BIstrncpy:
732   case Builtin::BI__builtin_strncpy:
733   case Builtin::BIstpncpy:
734   case Builtin::BI__builtin_stpncpy: {
735     // Whether these functions overflow depends on the runtime strlen of the
736     // string, not just the buffer size, so emitting the "always overflow"
737     // diagnostic isn't quite right. We should still diagnose passing a buffer
738     // size larger than the destination buffer though; this is a runtime abort
739     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
740     DiagID = diag::warn_fortify_source_size_mismatch;
741     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
742     DestinationSize = ComputeSizeArgument(0);
743     break;
744   }
745 
746   case Builtin::BImemcpy:
747   case Builtin::BI__builtin_memcpy:
748   case Builtin::BImemmove:
749   case Builtin::BI__builtin_memmove:
750   case Builtin::BImemset:
751   case Builtin::BI__builtin_memset:
752   case Builtin::BImempcpy:
753   case Builtin::BI__builtin_mempcpy: {
754     DiagID = diag::warn_fortify_source_overflow;
755     SourceSize = ComputeExplicitObjectSizeArgument(TheCall->getNumArgs() - 1);
756     DestinationSize = ComputeSizeArgument(0);
757     break;
758   }
759   case Builtin::BIsnprintf:
760   case Builtin::BI__builtin_snprintf:
761   case Builtin::BIvsnprintf:
762   case Builtin::BI__builtin_vsnprintf: {
763     DiagID = diag::warn_fortify_source_size_mismatch;
764     SourceSize = ComputeExplicitObjectSizeArgument(1);
765     DestinationSize = ComputeSizeArgument(0);
766     break;
767   }
768   }
769 
770   if (!SourceSize || !DestinationSize ||
771       SourceSize.getValue().ule(DestinationSize.getValue()))
772     return;
773 
774   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
775   // Skim off the details of whichever builtin was called to produce a better
776   // diagnostic, as it's unlikely that the user wrote the __builtin explicitly.
777   if (IsChkVariant) {
778     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
779     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
780   } else if (FunctionName.startswith("__builtin_")) {
781     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
782   }
783 
784   SmallString<16> DestinationStr;
785   SmallString<16> SourceStr;
786   DestinationSize->toString(DestinationStr, /*Radix=*/10);
787   SourceSize->toString(SourceStr, /*Radix=*/10);
788   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
789                       PDiag(DiagID)
790                           << FunctionName << DestinationStr << SourceStr);
791 }
792 
793 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
794                                      Scope::ScopeFlags NeededScopeFlags,
795                                      unsigned DiagID) {
796   // Scopes aren't available during instantiation. Fortunately, builtin
797   // functions cannot be template args so they cannot be formed through template
798   // instantiation. Therefore checking once during the parse is sufficient.
799   if (SemaRef.inTemplateInstantiation())
800     return false;
801 
802   Scope *S = SemaRef.getCurScope();
803   while (S && !S->isSEHExceptScope())
804     S = S->getParent();
805   if (!S || !(S->getFlags() & NeededScopeFlags)) {
806     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
807     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
808         << DRE->getDecl()->getIdentifier();
809     return true;
810   }
811 
812   return false;
813 }
814 
815 static inline bool isBlockPointer(Expr *Arg) {
816   return Arg->getType()->isBlockPointerType();
817 }
818 
819 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
820 /// void*, which is a requirement of device side enqueue.
821 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
822   const BlockPointerType *BPT =
823       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
824   ArrayRef<QualType> Params =
825       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
826   unsigned ArgCounter = 0;
827   bool IllegalParams = false;
828   // Iterate through the block parameters until either one is found that is not
829   // a local void*, or the block is valid.
830   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
831        I != E; ++I, ++ArgCounter) {
832     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
833         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
834             LangAS::opencl_local) {
835       // Get the location of the error. If a block literal has been passed
836       // (BlockExpr) then we can point straight to the offending argument,
837       // else we just point to the variable reference.
838       SourceLocation ErrorLoc;
839       if (isa<BlockExpr>(BlockArg)) {
840         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
841         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
842       } else if (isa<DeclRefExpr>(BlockArg)) {
843         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
844       }
845       S.Diag(ErrorLoc,
846              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
847       IllegalParams = true;
848     }
849   }
850 
851   return IllegalParams;
852 }
853 
854 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
855   if (!S.getOpenCLOptions().isSupported("cl_khr_subgroups", S.getLangOpts())) {
856     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
857         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
858     return true;
859   }
860   return false;
861 }
862 
863 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
864   if (checkArgCount(S, TheCall, 2))
865     return true;
866 
867   if (checkOpenCLSubgroupExt(S, TheCall))
868     return true;
869 
870   // First argument is an ndrange_t type.
871   Expr *NDRangeArg = TheCall->getArg(0);
872   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
873     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
874         << TheCall->getDirectCallee() << "'ndrange_t'";
875     return true;
876   }
877 
878   Expr *BlockArg = TheCall->getArg(1);
879   if (!isBlockPointer(BlockArg)) {
880     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
881         << TheCall->getDirectCallee() << "block";
882     return true;
883   }
884   return checkOpenCLBlockArgs(S, BlockArg);
885 }
886 
887 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
888 /// get_kernel_work_group_size
889 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
890 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
891   if (checkArgCount(S, TheCall, 1))
892     return true;
893 
894   Expr *BlockArg = TheCall->getArg(0);
895   if (!isBlockPointer(BlockArg)) {
896     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
897         << TheCall->getDirectCallee() << "block";
898     return true;
899   }
900   return checkOpenCLBlockArgs(S, BlockArg);
901 }
902 
903 /// Diagnose integer type and any valid implicit conversion to it.
904 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
905                                       const QualType &IntType);
906 
907 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
908                                             unsigned Start, unsigned End) {
909   bool IllegalParams = false;
910   for (unsigned I = Start; I <= End; ++I)
911     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
912                                               S.Context.getSizeType());
913   return IllegalParams;
914 }
915 
916 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
917 /// 'local void*' parameter of passed block.
918 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
919                                            Expr *BlockArg,
920                                            unsigned NumNonVarArgs) {
921   const BlockPointerType *BPT =
922       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
923   unsigned NumBlockParams =
924       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
925   unsigned TotalNumArgs = TheCall->getNumArgs();
926 
927   // For each argument passed to the block, a corresponding uint needs to
928   // be passed to describe the size of the local memory.
929   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
930     S.Diag(TheCall->getBeginLoc(),
931            diag::err_opencl_enqueue_kernel_local_size_args);
932     return true;
933   }
934 
935   // Check that the sizes of the local memory are specified by integers.
936   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
937                                          TotalNumArgs - 1);
938 }
939 
940 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
941 /// overload formats specified in Table 6.13.17.1.
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    void (^block)(void))
946 /// int enqueue_kernel(queue_t queue,
947 ///                    kernel_enqueue_flags_t flags,
948 ///                    const ndrange_t ndrange,
949 ///                    uint num_events_in_wait_list,
950 ///                    clk_event_t *event_wait_list,
951 ///                    clk_event_t *event_ret,
952 ///                    void (^block)(void))
953 /// int enqueue_kernel(queue_t queue,
954 ///                    kernel_enqueue_flags_t flags,
955 ///                    const ndrange_t ndrange,
956 ///                    void (^block)(local void*, ...),
957 ///                    uint size0, ...)
958 /// int enqueue_kernel(queue_t queue,
959 ///                    kernel_enqueue_flags_t flags,
960 ///                    const ndrange_t ndrange,
961 ///                    uint num_events_in_wait_list,
962 ///                    clk_event_t *event_wait_list,
963 ///                    clk_event_t *event_ret,
964 ///                    void (^block)(local void*, ...),
965 ///                    uint size0, ...)
966 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
967   unsigned NumArgs = TheCall->getNumArgs();
968 
969   if (NumArgs < 4) {
970     S.Diag(TheCall->getBeginLoc(),
971            diag::err_typecheck_call_too_few_args_at_least)
972         << 0 << 4 << NumArgs;
973     return true;
974   }
975 
976   Expr *Arg0 = TheCall->getArg(0);
977   Expr *Arg1 = TheCall->getArg(1);
978   Expr *Arg2 = TheCall->getArg(2);
979   Expr *Arg3 = TheCall->getArg(3);
980 
981   // First argument always needs to be a queue_t type.
982   if (!Arg0->getType()->isQueueT()) {
983     S.Diag(TheCall->getArg(0)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
986     return true;
987   }
988 
989   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
990   if (!Arg1->getType()->isIntegerType()) {
991     S.Diag(TheCall->getArg(1)->getBeginLoc(),
992            diag::err_opencl_builtin_expected_type)
993         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
994     return true;
995   }
996 
997   // Third argument is always an ndrange_t type.
998   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
999     S.Diag(TheCall->getArg(2)->getBeginLoc(),
1000            diag::err_opencl_builtin_expected_type)
1001         << TheCall->getDirectCallee() << "'ndrange_t'";
1002     return true;
1003   }
1004 
1005   // With four arguments, there is only one form that the function could be
1006   // called in: no events and no variable arguments.
1007   if (NumArgs == 4) {
1008     // check that the last argument is the right block type.
1009     if (!isBlockPointer(Arg3)) {
1010       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1011           << TheCall->getDirectCallee() << "block";
1012       return true;
1013     }
1014     // we have a block type, check the prototype
1015     const BlockPointerType *BPT =
1016         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1017     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1018       S.Diag(Arg3->getBeginLoc(),
1019              diag::err_opencl_enqueue_kernel_blocks_no_args);
1020       return true;
1021     }
1022     return false;
1023   }
1024   // we can have block + varargs.
1025   if (isBlockPointer(Arg3))
1026     return (checkOpenCLBlockArgs(S, Arg3) ||
1027             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1028   // last two cases with either exactly 7 args or 7 args and varargs.
1029   if (NumArgs >= 7) {
1030     // check common block argument.
1031     Expr *Arg6 = TheCall->getArg(6);
1032     if (!isBlockPointer(Arg6)) {
1033       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1034           << TheCall->getDirectCallee() << "block";
1035       return true;
1036     }
1037     if (checkOpenCLBlockArgs(S, Arg6))
1038       return true;
1039 
1040     // Forth argument has to be any integer type.
1041     if (!Arg3->getType()->isIntegerType()) {
1042       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1043              diag::err_opencl_builtin_expected_type)
1044           << TheCall->getDirectCallee() << "integer";
1045       return true;
1046     }
1047     // check remaining common arguments.
1048     Expr *Arg4 = TheCall->getArg(4);
1049     Expr *Arg5 = TheCall->getArg(5);
1050 
1051     // Fifth argument is always passed as a pointer to clk_event_t.
1052     if (!Arg4->isNullPointerConstant(S.Context,
1053                                      Expr::NPC_ValueDependentIsNotNull) &&
1054         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1055       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1056              diag::err_opencl_builtin_expected_type)
1057           << TheCall->getDirectCallee()
1058           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1059       return true;
1060     }
1061 
1062     // Sixth argument is always passed as a pointer to clk_event_t.
1063     if (!Arg5->isNullPointerConstant(S.Context,
1064                                      Expr::NPC_ValueDependentIsNotNull) &&
1065         !(Arg5->getType()->isPointerType() &&
1066           Arg5->getType()->getPointeeType()->isClkEventT())) {
1067       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1068              diag::err_opencl_builtin_expected_type)
1069           << TheCall->getDirectCallee()
1070           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1071       return true;
1072     }
1073 
1074     if (NumArgs == 7)
1075       return false;
1076 
1077     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1078   }
1079 
1080   // None of the specific case has been detected, give generic error
1081   S.Diag(TheCall->getBeginLoc(),
1082          diag::err_opencl_enqueue_kernel_incorrect_args);
1083   return true;
1084 }
1085 
1086 /// Returns OpenCL access qual.
1087 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1088     return D->getAttr<OpenCLAccessAttr>();
1089 }
1090 
1091 /// Returns true if pipe element type is different from the pointer.
1092 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1093   const Expr *Arg0 = Call->getArg(0);
1094   // First argument type should always be pipe.
1095   if (!Arg0->getType()->isPipeType()) {
1096     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1097         << Call->getDirectCallee() << Arg0->getSourceRange();
1098     return true;
1099   }
1100   OpenCLAccessAttr *AccessQual =
1101       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1102   // Validates the access qualifier is compatible with the call.
1103   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1104   // read_only and write_only, and assumed to be read_only if no qualifier is
1105   // specified.
1106   switch (Call->getDirectCallee()->getBuiltinID()) {
1107   case Builtin::BIread_pipe:
1108   case Builtin::BIreserve_read_pipe:
1109   case Builtin::BIcommit_read_pipe:
1110   case Builtin::BIwork_group_reserve_read_pipe:
1111   case Builtin::BIsub_group_reserve_read_pipe:
1112   case Builtin::BIwork_group_commit_read_pipe:
1113   case Builtin::BIsub_group_commit_read_pipe:
1114     if (!(!AccessQual || AccessQual->isReadOnly())) {
1115       S.Diag(Arg0->getBeginLoc(),
1116              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1117           << "read_only" << Arg0->getSourceRange();
1118       return true;
1119     }
1120     break;
1121   case Builtin::BIwrite_pipe:
1122   case Builtin::BIreserve_write_pipe:
1123   case Builtin::BIcommit_write_pipe:
1124   case Builtin::BIwork_group_reserve_write_pipe:
1125   case Builtin::BIsub_group_reserve_write_pipe:
1126   case Builtin::BIwork_group_commit_write_pipe:
1127   case Builtin::BIsub_group_commit_write_pipe:
1128     if (!(AccessQual && AccessQual->isWriteOnly())) {
1129       S.Diag(Arg0->getBeginLoc(),
1130              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1131           << "write_only" << Arg0->getSourceRange();
1132       return true;
1133     }
1134     break;
1135   default:
1136     break;
1137   }
1138   return false;
1139 }
1140 
1141 /// Returns true if pipe element type is different from the pointer.
1142 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1143   const Expr *Arg0 = Call->getArg(0);
1144   const Expr *ArgIdx = Call->getArg(Idx);
1145   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1146   const QualType EltTy = PipeTy->getElementType();
1147   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1148   // The Idx argument should be a pointer and the type of the pointer and
1149   // the type of pipe element should also be the same.
1150   if (!ArgTy ||
1151       !S.Context.hasSameType(
1152           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1153     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1154         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1155         << ArgIdx->getType() << ArgIdx->getSourceRange();
1156     return true;
1157   }
1158   return false;
1159 }
1160 
1161 // Performs semantic analysis for the read/write_pipe call.
1162 // \param S Reference to the semantic analyzer.
1163 // \param Call A pointer to the builtin call.
1164 // \return True if a semantic error has been found, false otherwise.
1165 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1166   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1167   // functions have two forms.
1168   switch (Call->getNumArgs()) {
1169   case 2:
1170     if (checkOpenCLPipeArg(S, Call))
1171       return true;
1172     // The call with 2 arguments should be
1173     // read/write_pipe(pipe T, T*).
1174     // Check packet type T.
1175     if (checkOpenCLPipePacketType(S, Call, 1))
1176       return true;
1177     break;
1178 
1179   case 4: {
1180     if (checkOpenCLPipeArg(S, Call))
1181       return true;
1182     // The call with 4 arguments should be
1183     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1184     // Check reserve_id_t.
1185     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1186       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1187           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1188           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1189       return true;
1190     }
1191 
1192     // Check the index.
1193     const Expr *Arg2 = Call->getArg(2);
1194     if (!Arg2->getType()->isIntegerType() &&
1195         !Arg2->getType()->isUnsignedIntegerType()) {
1196       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1197           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1198           << Arg2->getType() << Arg2->getSourceRange();
1199       return true;
1200     }
1201 
1202     // Check packet type T.
1203     if (checkOpenCLPipePacketType(S, Call, 3))
1204       return true;
1205   } break;
1206   default:
1207     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1208         << Call->getDirectCallee() << Call->getSourceRange();
1209     return true;
1210   }
1211 
1212   return false;
1213 }
1214 
1215 // Performs a semantic analysis on the {work_group_/sub_group_
1216 //        /_}reserve_{read/write}_pipe
1217 // \param S Reference to the semantic analyzer.
1218 // \param Call The call to the builtin function to be analyzed.
1219 // \return True if a semantic error was found, false otherwise.
1220 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1221   if (checkArgCount(S, Call, 2))
1222     return true;
1223 
1224   if (checkOpenCLPipeArg(S, Call))
1225     return true;
1226 
1227   // Check the reserve size.
1228   if (!Call->getArg(1)->getType()->isIntegerType() &&
1229       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1230     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1231         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1232         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1233     return true;
1234   }
1235 
1236   // Since return type of reserve_read/write_pipe built-in function is
1237   // reserve_id_t, which is not defined in the builtin def file , we used int
1238   // as return type and need to override the return type of these functions.
1239   Call->setType(S.Context.OCLReserveIDTy);
1240 
1241   return false;
1242 }
1243 
1244 // Performs a semantic analysis on {work_group_/sub_group_
1245 //        /_}commit_{read/write}_pipe
1246 // \param S Reference to the semantic analyzer.
1247 // \param Call The call to the builtin function to be analyzed.
1248 // \return True if a semantic error was found, false otherwise.
1249 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1250   if (checkArgCount(S, Call, 2))
1251     return true;
1252 
1253   if (checkOpenCLPipeArg(S, Call))
1254     return true;
1255 
1256   // Check reserve_id_t.
1257   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1258     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1259         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1260         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1261     return true;
1262   }
1263 
1264   return false;
1265 }
1266 
1267 // Performs a semantic analysis on the call to built-in Pipe
1268 //        Query Functions.
1269 // \param S Reference to the semantic analyzer.
1270 // \param Call The call to the builtin function to be analyzed.
1271 // \return True if a semantic error was found, false otherwise.
1272 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1273   if (checkArgCount(S, Call, 1))
1274     return true;
1275 
1276   if (!Call->getArg(0)->getType()->isPipeType()) {
1277     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1278         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1279     return true;
1280   }
1281 
1282   return false;
1283 }
1284 
1285 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1286 // Performs semantic analysis for the to_global/local/private call.
1287 // \param S Reference to the semantic analyzer.
1288 // \param BuiltinID ID of the builtin function.
1289 // \param Call A pointer to the builtin call.
1290 // \return True if a semantic error has been found, false otherwise.
1291 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1292                                     CallExpr *Call) {
1293   if (checkArgCount(S, Call, 1))
1294     return true;
1295 
1296   auto RT = Call->getArg(0)->getType();
1297   if (!RT->isPointerType() || RT->getPointeeType()
1298       .getAddressSpace() == LangAS::opencl_constant) {
1299     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1300         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1301     return true;
1302   }
1303 
1304   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1305     S.Diag(Call->getArg(0)->getBeginLoc(),
1306            diag::warn_opencl_generic_address_space_arg)
1307         << Call->getDirectCallee()->getNameInfo().getAsString()
1308         << Call->getArg(0)->getSourceRange();
1309   }
1310 
1311   RT = RT->getPointeeType();
1312   auto Qual = RT.getQualifiers();
1313   switch (BuiltinID) {
1314   case Builtin::BIto_global:
1315     Qual.setAddressSpace(LangAS::opencl_global);
1316     break;
1317   case Builtin::BIto_local:
1318     Qual.setAddressSpace(LangAS::opencl_local);
1319     break;
1320   case Builtin::BIto_private:
1321     Qual.setAddressSpace(LangAS::opencl_private);
1322     break;
1323   default:
1324     llvm_unreachable("Invalid builtin function");
1325   }
1326   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1327       RT.getUnqualifiedType(), Qual)));
1328 
1329   return false;
1330 }
1331 
1332 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1333   if (checkArgCount(S, TheCall, 1))
1334     return ExprError();
1335 
1336   // Compute __builtin_launder's parameter type from the argument.
1337   // The parameter type is:
1338   //  * The type of the argument if it's not an array or function type,
1339   //  Otherwise,
1340   //  * The decayed argument type.
1341   QualType ParamTy = [&]() {
1342     QualType ArgTy = TheCall->getArg(0)->getType();
1343     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1344       return S.Context.getPointerType(Ty->getElementType());
1345     if (ArgTy->isFunctionType()) {
1346       return S.Context.getPointerType(ArgTy);
1347     }
1348     return ArgTy;
1349   }();
1350 
1351   TheCall->setType(ParamTy);
1352 
1353   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1354     if (!ParamTy->isPointerType())
1355       return 0;
1356     if (ParamTy->isFunctionPointerType())
1357       return 1;
1358     if (ParamTy->isVoidPointerType())
1359       return 2;
1360     return llvm::Optional<unsigned>{};
1361   }();
1362   if (DiagSelect.hasValue()) {
1363     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1364         << DiagSelect.getValue() << TheCall->getSourceRange();
1365     return ExprError();
1366   }
1367 
1368   // We either have an incomplete class type, or we have a class template
1369   // whose instantiation has not been forced. Example:
1370   //
1371   //   template <class T> struct Foo { T value; };
1372   //   Foo<int> *p = nullptr;
1373   //   auto *d = __builtin_launder(p);
1374   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1375                             diag::err_incomplete_type))
1376     return ExprError();
1377 
1378   assert(ParamTy->getPointeeType()->isObjectType() &&
1379          "Unhandled non-object pointer case");
1380 
1381   InitializedEntity Entity =
1382       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1383   ExprResult Arg =
1384       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1385   if (Arg.isInvalid())
1386     return ExprError();
1387   TheCall->setArg(0, Arg.get());
1388 
1389   return TheCall;
1390 }
1391 
1392 // Emit an error and return true if the current architecture is not in the list
1393 // of supported architectures.
1394 static bool
1395 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1396                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1397   llvm::Triple::ArchType CurArch =
1398       S.getASTContext().getTargetInfo().getTriple().getArch();
1399   if (llvm::is_contained(SupportedArchs, CurArch))
1400     return false;
1401   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1402       << TheCall->getSourceRange();
1403   return true;
1404 }
1405 
1406 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1407                                  SourceLocation CallSiteLoc);
1408 
1409 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1410                                       CallExpr *TheCall) {
1411   switch (TI.getTriple().getArch()) {
1412   default:
1413     // Some builtins don't require additional checking, so just consider these
1414     // acceptable.
1415     return false;
1416   case llvm::Triple::arm:
1417   case llvm::Triple::armeb:
1418   case llvm::Triple::thumb:
1419   case llvm::Triple::thumbeb:
1420     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1421   case llvm::Triple::aarch64:
1422   case llvm::Triple::aarch64_32:
1423   case llvm::Triple::aarch64_be:
1424     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1425   case llvm::Triple::bpfeb:
1426   case llvm::Triple::bpfel:
1427     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1428   case llvm::Triple::hexagon:
1429     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1430   case llvm::Triple::mips:
1431   case llvm::Triple::mipsel:
1432   case llvm::Triple::mips64:
1433   case llvm::Triple::mips64el:
1434     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1435   case llvm::Triple::systemz:
1436     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1437   case llvm::Triple::x86:
1438   case llvm::Triple::x86_64:
1439     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1440   case llvm::Triple::ppc:
1441   case llvm::Triple::ppcle:
1442   case llvm::Triple::ppc64:
1443   case llvm::Triple::ppc64le:
1444     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1445   case llvm::Triple::amdgcn:
1446     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1447   case llvm::Triple::riscv32:
1448   case llvm::Triple::riscv64:
1449     return CheckRISCVBuiltinFunctionCall(TI, BuiltinID, TheCall);
1450   }
1451 }
1452 
1453 ExprResult
1454 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1455                                CallExpr *TheCall) {
1456   ExprResult TheCallResult(TheCall);
1457 
1458   // Find out if any arguments are required to be integer constant expressions.
1459   unsigned ICEArguments = 0;
1460   ASTContext::GetBuiltinTypeError Error;
1461   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1462   if (Error != ASTContext::GE_None)
1463     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1464 
1465   // If any arguments are required to be ICE's, check and diagnose.
1466   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1467     // Skip arguments not required to be ICE's.
1468     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1469 
1470     llvm::APSInt Result;
1471     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1472       return true;
1473     ICEArguments &= ~(1 << ArgNo);
1474   }
1475 
1476   switch (BuiltinID) {
1477   case Builtin::BI__builtin___CFStringMakeConstantString:
1478     assert(TheCall->getNumArgs() == 1 &&
1479            "Wrong # arguments to builtin CFStringMakeConstantString");
1480     if (CheckObjCString(TheCall->getArg(0)))
1481       return ExprError();
1482     break;
1483   case Builtin::BI__builtin_ms_va_start:
1484   case Builtin::BI__builtin_stdarg_start:
1485   case Builtin::BI__builtin_va_start:
1486     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1487       return ExprError();
1488     break;
1489   case Builtin::BI__va_start: {
1490     switch (Context.getTargetInfo().getTriple().getArch()) {
1491     case llvm::Triple::aarch64:
1492     case llvm::Triple::arm:
1493     case llvm::Triple::thumb:
1494       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1495         return ExprError();
1496       break;
1497     default:
1498       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1499         return ExprError();
1500       break;
1501     }
1502     break;
1503   }
1504 
1505   // The acquire, release, and no fence variants are ARM and AArch64 only.
1506   case Builtin::BI_interlockedbittestandset_acq:
1507   case Builtin::BI_interlockedbittestandset_rel:
1508   case Builtin::BI_interlockedbittestandset_nf:
1509   case Builtin::BI_interlockedbittestandreset_acq:
1510   case Builtin::BI_interlockedbittestandreset_rel:
1511   case Builtin::BI_interlockedbittestandreset_nf:
1512     if (CheckBuiltinTargetSupport(
1513             *this, BuiltinID, TheCall,
1514             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1515       return ExprError();
1516     break;
1517 
1518   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1519   case Builtin::BI_bittest64:
1520   case Builtin::BI_bittestandcomplement64:
1521   case Builtin::BI_bittestandreset64:
1522   case Builtin::BI_bittestandset64:
1523   case Builtin::BI_interlockedbittestandreset64:
1524   case Builtin::BI_interlockedbittestandset64:
1525     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1526                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1527                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1528       return ExprError();
1529     break;
1530 
1531   case Builtin::BI__builtin_isgreater:
1532   case Builtin::BI__builtin_isgreaterequal:
1533   case Builtin::BI__builtin_isless:
1534   case Builtin::BI__builtin_islessequal:
1535   case Builtin::BI__builtin_islessgreater:
1536   case Builtin::BI__builtin_isunordered:
1537     if (SemaBuiltinUnorderedCompare(TheCall))
1538       return ExprError();
1539     break;
1540   case Builtin::BI__builtin_fpclassify:
1541     if (SemaBuiltinFPClassification(TheCall, 6))
1542       return ExprError();
1543     break;
1544   case Builtin::BI__builtin_isfinite:
1545   case Builtin::BI__builtin_isinf:
1546   case Builtin::BI__builtin_isinf_sign:
1547   case Builtin::BI__builtin_isnan:
1548   case Builtin::BI__builtin_isnormal:
1549   case Builtin::BI__builtin_signbit:
1550   case Builtin::BI__builtin_signbitf:
1551   case Builtin::BI__builtin_signbitl:
1552     if (SemaBuiltinFPClassification(TheCall, 1))
1553       return ExprError();
1554     break;
1555   case Builtin::BI__builtin_shufflevector:
1556     return SemaBuiltinShuffleVector(TheCall);
1557     // TheCall will be freed by the smart pointer here, but that's fine, since
1558     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1559   case Builtin::BI__builtin_prefetch:
1560     if (SemaBuiltinPrefetch(TheCall))
1561       return ExprError();
1562     break;
1563   case Builtin::BI__builtin_alloca_with_align:
1564     if (SemaBuiltinAllocaWithAlign(TheCall))
1565       return ExprError();
1566     LLVM_FALLTHROUGH;
1567   case Builtin::BI__builtin_alloca:
1568     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1569         << TheCall->getDirectCallee();
1570     break;
1571   case Builtin::BI__arithmetic_fence:
1572     if (SemaBuiltinArithmeticFence(TheCall))
1573       return ExprError();
1574     break;
1575   case Builtin::BI__assume:
1576   case Builtin::BI__builtin_assume:
1577     if (SemaBuiltinAssume(TheCall))
1578       return ExprError();
1579     break;
1580   case Builtin::BI__builtin_assume_aligned:
1581     if (SemaBuiltinAssumeAligned(TheCall))
1582       return ExprError();
1583     break;
1584   case Builtin::BI__builtin_dynamic_object_size:
1585   case Builtin::BI__builtin_object_size:
1586     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1587       return ExprError();
1588     break;
1589   case Builtin::BI__builtin_longjmp:
1590     if (SemaBuiltinLongjmp(TheCall))
1591       return ExprError();
1592     break;
1593   case Builtin::BI__builtin_setjmp:
1594     if (SemaBuiltinSetjmp(TheCall))
1595       return ExprError();
1596     break;
1597   case Builtin::BI__builtin_classify_type:
1598     if (checkArgCount(*this, TheCall, 1)) return true;
1599     TheCall->setType(Context.IntTy);
1600     break;
1601   case Builtin::BI__builtin_complex:
1602     if (SemaBuiltinComplex(TheCall))
1603       return ExprError();
1604     break;
1605   case Builtin::BI__builtin_constant_p: {
1606     if (checkArgCount(*this, TheCall, 1)) return true;
1607     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1608     if (Arg.isInvalid()) return true;
1609     TheCall->setArg(0, Arg.get());
1610     TheCall->setType(Context.IntTy);
1611     break;
1612   }
1613   case Builtin::BI__builtin_launder:
1614     return SemaBuiltinLaunder(*this, TheCall);
1615   case Builtin::BI__sync_fetch_and_add:
1616   case Builtin::BI__sync_fetch_and_add_1:
1617   case Builtin::BI__sync_fetch_and_add_2:
1618   case Builtin::BI__sync_fetch_and_add_4:
1619   case Builtin::BI__sync_fetch_and_add_8:
1620   case Builtin::BI__sync_fetch_and_add_16:
1621   case Builtin::BI__sync_fetch_and_sub:
1622   case Builtin::BI__sync_fetch_and_sub_1:
1623   case Builtin::BI__sync_fetch_and_sub_2:
1624   case Builtin::BI__sync_fetch_and_sub_4:
1625   case Builtin::BI__sync_fetch_and_sub_8:
1626   case Builtin::BI__sync_fetch_and_sub_16:
1627   case Builtin::BI__sync_fetch_and_or:
1628   case Builtin::BI__sync_fetch_and_or_1:
1629   case Builtin::BI__sync_fetch_and_or_2:
1630   case Builtin::BI__sync_fetch_and_or_4:
1631   case Builtin::BI__sync_fetch_and_or_8:
1632   case Builtin::BI__sync_fetch_and_or_16:
1633   case Builtin::BI__sync_fetch_and_and:
1634   case Builtin::BI__sync_fetch_and_and_1:
1635   case Builtin::BI__sync_fetch_and_and_2:
1636   case Builtin::BI__sync_fetch_and_and_4:
1637   case Builtin::BI__sync_fetch_and_and_8:
1638   case Builtin::BI__sync_fetch_and_and_16:
1639   case Builtin::BI__sync_fetch_and_xor:
1640   case Builtin::BI__sync_fetch_and_xor_1:
1641   case Builtin::BI__sync_fetch_and_xor_2:
1642   case Builtin::BI__sync_fetch_and_xor_4:
1643   case Builtin::BI__sync_fetch_and_xor_8:
1644   case Builtin::BI__sync_fetch_and_xor_16:
1645   case Builtin::BI__sync_fetch_and_nand:
1646   case Builtin::BI__sync_fetch_and_nand_1:
1647   case Builtin::BI__sync_fetch_and_nand_2:
1648   case Builtin::BI__sync_fetch_and_nand_4:
1649   case Builtin::BI__sync_fetch_and_nand_8:
1650   case Builtin::BI__sync_fetch_and_nand_16:
1651   case Builtin::BI__sync_add_and_fetch:
1652   case Builtin::BI__sync_add_and_fetch_1:
1653   case Builtin::BI__sync_add_and_fetch_2:
1654   case Builtin::BI__sync_add_and_fetch_4:
1655   case Builtin::BI__sync_add_and_fetch_8:
1656   case Builtin::BI__sync_add_and_fetch_16:
1657   case Builtin::BI__sync_sub_and_fetch:
1658   case Builtin::BI__sync_sub_and_fetch_1:
1659   case Builtin::BI__sync_sub_and_fetch_2:
1660   case Builtin::BI__sync_sub_and_fetch_4:
1661   case Builtin::BI__sync_sub_and_fetch_8:
1662   case Builtin::BI__sync_sub_and_fetch_16:
1663   case Builtin::BI__sync_and_and_fetch:
1664   case Builtin::BI__sync_and_and_fetch_1:
1665   case Builtin::BI__sync_and_and_fetch_2:
1666   case Builtin::BI__sync_and_and_fetch_4:
1667   case Builtin::BI__sync_and_and_fetch_8:
1668   case Builtin::BI__sync_and_and_fetch_16:
1669   case Builtin::BI__sync_or_and_fetch:
1670   case Builtin::BI__sync_or_and_fetch_1:
1671   case Builtin::BI__sync_or_and_fetch_2:
1672   case Builtin::BI__sync_or_and_fetch_4:
1673   case Builtin::BI__sync_or_and_fetch_8:
1674   case Builtin::BI__sync_or_and_fetch_16:
1675   case Builtin::BI__sync_xor_and_fetch:
1676   case Builtin::BI__sync_xor_and_fetch_1:
1677   case Builtin::BI__sync_xor_and_fetch_2:
1678   case Builtin::BI__sync_xor_and_fetch_4:
1679   case Builtin::BI__sync_xor_and_fetch_8:
1680   case Builtin::BI__sync_xor_and_fetch_16:
1681   case Builtin::BI__sync_nand_and_fetch:
1682   case Builtin::BI__sync_nand_and_fetch_1:
1683   case Builtin::BI__sync_nand_and_fetch_2:
1684   case Builtin::BI__sync_nand_and_fetch_4:
1685   case Builtin::BI__sync_nand_and_fetch_8:
1686   case Builtin::BI__sync_nand_and_fetch_16:
1687   case Builtin::BI__sync_val_compare_and_swap:
1688   case Builtin::BI__sync_val_compare_and_swap_1:
1689   case Builtin::BI__sync_val_compare_and_swap_2:
1690   case Builtin::BI__sync_val_compare_and_swap_4:
1691   case Builtin::BI__sync_val_compare_and_swap_8:
1692   case Builtin::BI__sync_val_compare_and_swap_16:
1693   case Builtin::BI__sync_bool_compare_and_swap:
1694   case Builtin::BI__sync_bool_compare_and_swap_1:
1695   case Builtin::BI__sync_bool_compare_and_swap_2:
1696   case Builtin::BI__sync_bool_compare_and_swap_4:
1697   case Builtin::BI__sync_bool_compare_and_swap_8:
1698   case Builtin::BI__sync_bool_compare_and_swap_16:
1699   case Builtin::BI__sync_lock_test_and_set:
1700   case Builtin::BI__sync_lock_test_and_set_1:
1701   case Builtin::BI__sync_lock_test_and_set_2:
1702   case Builtin::BI__sync_lock_test_and_set_4:
1703   case Builtin::BI__sync_lock_test_and_set_8:
1704   case Builtin::BI__sync_lock_test_and_set_16:
1705   case Builtin::BI__sync_lock_release:
1706   case Builtin::BI__sync_lock_release_1:
1707   case Builtin::BI__sync_lock_release_2:
1708   case Builtin::BI__sync_lock_release_4:
1709   case Builtin::BI__sync_lock_release_8:
1710   case Builtin::BI__sync_lock_release_16:
1711   case Builtin::BI__sync_swap:
1712   case Builtin::BI__sync_swap_1:
1713   case Builtin::BI__sync_swap_2:
1714   case Builtin::BI__sync_swap_4:
1715   case Builtin::BI__sync_swap_8:
1716   case Builtin::BI__sync_swap_16:
1717     return SemaBuiltinAtomicOverloaded(TheCallResult);
1718   case Builtin::BI__sync_synchronize:
1719     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1720         << TheCall->getCallee()->getSourceRange();
1721     break;
1722   case Builtin::BI__builtin_nontemporal_load:
1723   case Builtin::BI__builtin_nontemporal_store:
1724     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1725   case Builtin::BI__builtin_memcpy_inline: {
1726     clang::Expr *SizeOp = TheCall->getArg(2);
1727     // We warn about copying to or from `nullptr` pointers when `size` is
1728     // greater than 0. When `size` is value dependent we cannot evaluate its
1729     // value so we bail out.
1730     if (SizeOp->isValueDependent())
1731       break;
1732     if (!SizeOp->EvaluateKnownConstInt(Context).isZero()) {
1733       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1734       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1735     }
1736     break;
1737   }
1738 #define BUILTIN(ID, TYPE, ATTRS)
1739 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1740   case Builtin::BI##ID: \
1741     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1742 #include "clang/Basic/Builtins.def"
1743   case Builtin::BI__annotation:
1744     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1745       return ExprError();
1746     break;
1747   case Builtin::BI__builtin_annotation:
1748     if (SemaBuiltinAnnotation(*this, TheCall))
1749       return ExprError();
1750     break;
1751   case Builtin::BI__builtin_addressof:
1752     if (SemaBuiltinAddressof(*this, TheCall))
1753       return ExprError();
1754     break;
1755   case Builtin::BI__builtin_is_aligned:
1756   case Builtin::BI__builtin_align_up:
1757   case Builtin::BI__builtin_align_down:
1758     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1759       return ExprError();
1760     break;
1761   case Builtin::BI__builtin_add_overflow:
1762   case Builtin::BI__builtin_sub_overflow:
1763   case Builtin::BI__builtin_mul_overflow:
1764     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1765       return ExprError();
1766     break;
1767   case Builtin::BI__builtin_operator_new:
1768   case Builtin::BI__builtin_operator_delete: {
1769     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1770     ExprResult Res =
1771         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1772     if (Res.isInvalid())
1773       CorrectDelayedTyposInExpr(TheCallResult.get());
1774     return Res;
1775   }
1776   case Builtin::BI__builtin_dump_struct: {
1777     // We first want to ensure we are called with 2 arguments
1778     if (checkArgCount(*this, TheCall, 2))
1779       return ExprError();
1780     // Ensure that the first argument is of type 'struct XX *'
1781     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1782     const QualType PtrArgType = PtrArg->getType();
1783     if (!PtrArgType->isPointerType() ||
1784         !PtrArgType->getPointeeType()->isRecordType()) {
1785       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1786           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1787           << "structure pointer";
1788       return ExprError();
1789     }
1790 
1791     // Ensure that the second argument is of type 'FunctionType'
1792     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1793     const QualType FnPtrArgType = FnPtrArg->getType();
1794     if (!FnPtrArgType->isPointerType()) {
1795       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1796           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1797           << FnPtrArgType << "'int (*)(const char *, ...)'";
1798       return ExprError();
1799     }
1800 
1801     const auto *FuncType =
1802         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1803 
1804     if (!FuncType) {
1805       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1806           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1807           << FnPtrArgType << "'int (*)(const char *, ...)'";
1808       return ExprError();
1809     }
1810 
1811     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1812       if (!FT->getNumParams()) {
1813         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1814             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1815             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1816         return ExprError();
1817       }
1818       QualType PT = FT->getParamType(0);
1819       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1820           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1821           !PT->getPointeeType().isConstQualified()) {
1822         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1823             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1824             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1825         return ExprError();
1826       }
1827     }
1828 
1829     TheCall->setType(Context.IntTy);
1830     break;
1831   }
1832   case Builtin::BI__builtin_expect_with_probability: {
1833     // We first want to ensure we are called with 3 arguments
1834     if (checkArgCount(*this, TheCall, 3))
1835       return ExprError();
1836     // then check probability is constant float in range [0.0, 1.0]
1837     const Expr *ProbArg = TheCall->getArg(2);
1838     SmallVector<PartialDiagnosticAt, 8> Notes;
1839     Expr::EvalResult Eval;
1840     Eval.Diag = &Notes;
1841     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1842         !Eval.Val.isFloat()) {
1843       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1844           << ProbArg->getSourceRange();
1845       for (const PartialDiagnosticAt &PDiag : Notes)
1846         Diag(PDiag.first, PDiag.second);
1847       return ExprError();
1848     }
1849     llvm::APFloat Probability = Eval.Val.getFloat();
1850     bool LoseInfo = false;
1851     Probability.convert(llvm::APFloat::IEEEdouble(),
1852                         llvm::RoundingMode::Dynamic, &LoseInfo);
1853     if (!(Probability >= llvm::APFloat(0.0) &&
1854           Probability <= llvm::APFloat(1.0))) {
1855       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1856           << ProbArg->getSourceRange();
1857       return ExprError();
1858     }
1859     break;
1860   }
1861   case Builtin::BI__builtin_preserve_access_index:
1862     if (SemaBuiltinPreserveAI(*this, TheCall))
1863       return ExprError();
1864     break;
1865   case Builtin::BI__builtin_call_with_static_chain:
1866     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1867       return ExprError();
1868     break;
1869   case Builtin::BI__exception_code:
1870   case Builtin::BI_exception_code:
1871     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1872                                  diag::err_seh___except_block))
1873       return ExprError();
1874     break;
1875   case Builtin::BI__exception_info:
1876   case Builtin::BI_exception_info:
1877     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1878                                  diag::err_seh___except_filter))
1879       return ExprError();
1880     break;
1881   case Builtin::BI__GetExceptionInfo:
1882     if (checkArgCount(*this, TheCall, 1))
1883       return ExprError();
1884 
1885     if (CheckCXXThrowOperand(
1886             TheCall->getBeginLoc(),
1887             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1888             TheCall))
1889       return ExprError();
1890 
1891     TheCall->setType(Context.VoidPtrTy);
1892     break;
1893   // OpenCL v2.0, s6.13.16 - Pipe functions
1894   case Builtin::BIread_pipe:
1895   case Builtin::BIwrite_pipe:
1896     // Since those two functions are declared with var args, we need a semantic
1897     // check for the argument.
1898     if (SemaBuiltinRWPipe(*this, TheCall))
1899       return ExprError();
1900     break;
1901   case Builtin::BIreserve_read_pipe:
1902   case Builtin::BIreserve_write_pipe:
1903   case Builtin::BIwork_group_reserve_read_pipe:
1904   case Builtin::BIwork_group_reserve_write_pipe:
1905     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIsub_group_reserve_read_pipe:
1909   case Builtin::BIsub_group_reserve_write_pipe:
1910     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1911         SemaBuiltinReserveRWPipe(*this, TheCall))
1912       return ExprError();
1913     break;
1914   case Builtin::BIcommit_read_pipe:
1915   case Builtin::BIcommit_write_pipe:
1916   case Builtin::BIwork_group_commit_read_pipe:
1917   case Builtin::BIwork_group_commit_write_pipe:
1918     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1919       return ExprError();
1920     break;
1921   case Builtin::BIsub_group_commit_read_pipe:
1922   case Builtin::BIsub_group_commit_write_pipe:
1923     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1924         SemaBuiltinCommitRWPipe(*this, TheCall))
1925       return ExprError();
1926     break;
1927   case Builtin::BIget_pipe_num_packets:
1928   case Builtin::BIget_pipe_max_packets:
1929     if (SemaBuiltinPipePackets(*this, TheCall))
1930       return ExprError();
1931     break;
1932   case Builtin::BIto_global:
1933   case Builtin::BIto_local:
1934   case Builtin::BIto_private:
1935     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1936       return ExprError();
1937     break;
1938   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1939   case Builtin::BIenqueue_kernel:
1940     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1941       return ExprError();
1942     break;
1943   case Builtin::BIget_kernel_work_group_size:
1944   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1945     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1946       return ExprError();
1947     break;
1948   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1949   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1950     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1951       return ExprError();
1952     break;
1953   case Builtin::BI__builtin_os_log_format:
1954     Cleanup.setExprNeedsCleanups(true);
1955     LLVM_FALLTHROUGH;
1956   case Builtin::BI__builtin_os_log_format_buffer_size:
1957     if (SemaBuiltinOSLogFormat(TheCall))
1958       return ExprError();
1959     break;
1960   case Builtin::BI__builtin_frame_address:
1961   case Builtin::BI__builtin_return_address: {
1962     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1963       return ExprError();
1964 
1965     // -Wframe-address warning if non-zero passed to builtin
1966     // return/frame address.
1967     Expr::EvalResult Result;
1968     if (!TheCall->getArg(0)->isValueDependent() &&
1969         TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1970         Result.Val.getInt() != 0)
1971       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1972           << ((BuiltinID == Builtin::BI__builtin_return_address)
1973                   ? "__builtin_return_address"
1974                   : "__builtin_frame_address")
1975           << TheCall->getSourceRange();
1976     break;
1977   }
1978 
1979   case Builtin::BI__builtin_matrix_transpose:
1980     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1981 
1982   case Builtin::BI__builtin_matrix_column_major_load:
1983     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1984 
1985   case Builtin::BI__builtin_matrix_column_major_store:
1986     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1987 
1988   case Builtin::BI__builtin_get_device_side_mangled_name: {
1989     auto Check = [](CallExpr *TheCall) {
1990       if (TheCall->getNumArgs() != 1)
1991         return false;
1992       auto *DRE = dyn_cast<DeclRefExpr>(TheCall->getArg(0)->IgnoreImpCasts());
1993       if (!DRE)
1994         return false;
1995       auto *D = DRE->getDecl();
1996       if (!isa<FunctionDecl>(D) && !isa<VarDecl>(D))
1997         return false;
1998       return D->hasAttr<CUDAGlobalAttr>() || D->hasAttr<CUDADeviceAttr>() ||
1999              D->hasAttr<CUDAConstantAttr>() || D->hasAttr<HIPManagedAttr>();
2000     };
2001     if (!Check(TheCall)) {
2002       Diag(TheCall->getBeginLoc(),
2003            diag::err_hip_invalid_args_builtin_mangled_name);
2004       return ExprError();
2005     }
2006   }
2007   }
2008 
2009   // Since the target specific builtins for each arch overlap, only check those
2010   // of the arch we are compiling for.
2011   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
2012     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
2013       assert(Context.getAuxTargetInfo() &&
2014              "Aux Target Builtin, but not an aux target?");
2015 
2016       if (CheckTSBuiltinFunctionCall(
2017               *Context.getAuxTargetInfo(),
2018               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
2019         return ExprError();
2020     } else {
2021       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
2022                                      TheCall))
2023         return ExprError();
2024     }
2025   }
2026 
2027   return TheCallResult;
2028 }
2029 
2030 // Get the valid immediate range for the specified NEON type code.
2031 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
2032   NeonTypeFlags Type(t);
2033   int IsQuad = ForceQuad ? true : Type.isQuad();
2034   switch (Type.getEltType()) {
2035   case NeonTypeFlags::Int8:
2036   case NeonTypeFlags::Poly8:
2037     return shift ? 7 : (8 << IsQuad) - 1;
2038   case NeonTypeFlags::Int16:
2039   case NeonTypeFlags::Poly16:
2040     return shift ? 15 : (4 << IsQuad) - 1;
2041   case NeonTypeFlags::Int32:
2042     return shift ? 31 : (2 << IsQuad) - 1;
2043   case NeonTypeFlags::Int64:
2044   case NeonTypeFlags::Poly64:
2045     return shift ? 63 : (1 << IsQuad) - 1;
2046   case NeonTypeFlags::Poly128:
2047     return shift ? 127 : (1 << IsQuad) - 1;
2048   case NeonTypeFlags::Float16:
2049     assert(!shift && "cannot shift float types!");
2050     return (4 << IsQuad) - 1;
2051   case NeonTypeFlags::Float32:
2052     assert(!shift && "cannot shift float types!");
2053     return (2 << IsQuad) - 1;
2054   case NeonTypeFlags::Float64:
2055     assert(!shift && "cannot shift float types!");
2056     return (1 << IsQuad) - 1;
2057   case NeonTypeFlags::BFloat16:
2058     assert(!shift && "cannot shift float types!");
2059     return (4 << IsQuad) - 1;
2060   }
2061   llvm_unreachable("Invalid NeonTypeFlag!");
2062 }
2063 
2064 /// getNeonEltType - Return the QualType corresponding to the elements of
2065 /// the vector type specified by the NeonTypeFlags.  This is used to check
2066 /// the pointer arguments for Neon load/store intrinsics.
2067 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2068                                bool IsPolyUnsigned, bool IsInt64Long) {
2069   switch (Flags.getEltType()) {
2070   case NeonTypeFlags::Int8:
2071     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2072   case NeonTypeFlags::Int16:
2073     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2074   case NeonTypeFlags::Int32:
2075     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2076   case NeonTypeFlags::Int64:
2077     if (IsInt64Long)
2078       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2079     else
2080       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2081                                 : Context.LongLongTy;
2082   case NeonTypeFlags::Poly8:
2083     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2084   case NeonTypeFlags::Poly16:
2085     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2086   case NeonTypeFlags::Poly64:
2087     if (IsInt64Long)
2088       return Context.UnsignedLongTy;
2089     else
2090       return Context.UnsignedLongLongTy;
2091   case NeonTypeFlags::Poly128:
2092     break;
2093   case NeonTypeFlags::Float16:
2094     return Context.HalfTy;
2095   case NeonTypeFlags::Float32:
2096     return Context.FloatTy;
2097   case NeonTypeFlags::Float64:
2098     return Context.DoubleTy;
2099   case NeonTypeFlags::BFloat16:
2100     return Context.BFloat16Ty;
2101   }
2102   llvm_unreachable("Invalid NeonTypeFlag!");
2103 }
2104 
2105 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2106   // Range check SVE intrinsics that take immediate values.
2107   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2108 
2109   switch (BuiltinID) {
2110   default:
2111     return false;
2112 #define GET_SVE_IMMEDIATE_CHECK
2113 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2114 #undef GET_SVE_IMMEDIATE_CHECK
2115   }
2116 
2117   // Perform all the immediate checks for this builtin call.
2118   bool HasError = false;
2119   for (auto &I : ImmChecks) {
2120     int ArgNum, CheckTy, ElementSizeInBits;
2121     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2122 
2123     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2124 
2125     // Function that checks whether the operand (ArgNum) is an immediate
2126     // that is one of the predefined values.
2127     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2128                                    int ErrDiag) -> bool {
2129       // We can't check the value of a dependent argument.
2130       Expr *Arg = TheCall->getArg(ArgNum);
2131       if (Arg->isTypeDependent() || Arg->isValueDependent())
2132         return false;
2133 
2134       // Check constant-ness first.
2135       llvm::APSInt Imm;
2136       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2137         return true;
2138 
2139       if (!CheckImm(Imm.getSExtValue()))
2140         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2141       return false;
2142     };
2143 
2144     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2145     case SVETypeFlags::ImmCheck0_31:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2147         HasError = true;
2148       break;
2149     case SVETypeFlags::ImmCheck0_13:
2150       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2151         HasError = true;
2152       break;
2153     case SVETypeFlags::ImmCheck1_16:
2154       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2155         HasError = true;
2156       break;
2157     case SVETypeFlags::ImmCheck0_7:
2158       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2159         HasError = true;
2160       break;
2161     case SVETypeFlags::ImmCheckExtract:
2162       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2163                                       (2048 / ElementSizeInBits) - 1))
2164         HasError = true;
2165       break;
2166     case SVETypeFlags::ImmCheckShiftRight:
2167       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2168         HasError = true;
2169       break;
2170     case SVETypeFlags::ImmCheckShiftRightNarrow:
2171       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2172                                       ElementSizeInBits / 2))
2173         HasError = true;
2174       break;
2175     case SVETypeFlags::ImmCheckShiftLeft:
2176       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2177                                       ElementSizeInBits - 1))
2178         HasError = true;
2179       break;
2180     case SVETypeFlags::ImmCheckLaneIndex:
2181       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2182                                       (128 / (1 * ElementSizeInBits)) - 1))
2183         HasError = true;
2184       break;
2185     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2186       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2187                                       (128 / (2 * ElementSizeInBits)) - 1))
2188         HasError = true;
2189       break;
2190     case SVETypeFlags::ImmCheckLaneIndexDot:
2191       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2192                                       (128 / (4 * ElementSizeInBits)) - 1))
2193         HasError = true;
2194       break;
2195     case SVETypeFlags::ImmCheckComplexRot90_270:
2196       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2197                               diag::err_rotation_argument_to_cadd))
2198         HasError = true;
2199       break;
2200     case SVETypeFlags::ImmCheckComplexRotAll90:
2201       if (CheckImmediateInSet(
2202               [](int64_t V) {
2203                 return V == 0 || V == 90 || V == 180 || V == 270;
2204               },
2205               diag::err_rotation_argument_to_cmla))
2206         HasError = true;
2207       break;
2208     case SVETypeFlags::ImmCheck0_1:
2209       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2210         HasError = true;
2211       break;
2212     case SVETypeFlags::ImmCheck0_2:
2213       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2214         HasError = true;
2215       break;
2216     case SVETypeFlags::ImmCheck0_3:
2217       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2218         HasError = true;
2219       break;
2220     }
2221   }
2222 
2223   return HasError;
2224 }
2225 
2226 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2227                                         unsigned BuiltinID, CallExpr *TheCall) {
2228   llvm::APSInt Result;
2229   uint64_t mask = 0;
2230   unsigned TV = 0;
2231   int PtrArgNum = -1;
2232   bool HasConstPtr = false;
2233   switch (BuiltinID) {
2234 #define GET_NEON_OVERLOAD_CHECK
2235 #include "clang/Basic/arm_neon.inc"
2236 #include "clang/Basic/arm_fp16.inc"
2237 #undef GET_NEON_OVERLOAD_CHECK
2238   }
2239 
2240   // For NEON intrinsics which are overloaded on vector element type, validate
2241   // the immediate which specifies which variant to emit.
2242   unsigned ImmArg = TheCall->getNumArgs()-1;
2243   if (mask) {
2244     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2245       return true;
2246 
2247     TV = Result.getLimitedValue(64);
2248     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2249       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2250              << TheCall->getArg(ImmArg)->getSourceRange();
2251   }
2252 
2253   if (PtrArgNum >= 0) {
2254     // Check that pointer arguments have the specified type.
2255     Expr *Arg = TheCall->getArg(PtrArgNum);
2256     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2257       Arg = ICE->getSubExpr();
2258     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2259     QualType RHSTy = RHS.get()->getType();
2260 
2261     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2262     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2263                           Arch == llvm::Triple::aarch64_32 ||
2264                           Arch == llvm::Triple::aarch64_be;
2265     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2266     QualType EltTy =
2267         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2268     if (HasConstPtr)
2269       EltTy = EltTy.withConst();
2270     QualType LHSTy = Context.getPointerType(EltTy);
2271     AssignConvertType ConvTy;
2272     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2273     if (RHS.isInvalid())
2274       return true;
2275     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2276                                  RHS.get(), AA_Assigning))
2277       return true;
2278   }
2279 
2280   // For NEON intrinsics which take an immediate value as part of the
2281   // instruction, range check them here.
2282   unsigned i = 0, l = 0, u = 0;
2283   switch (BuiltinID) {
2284   default:
2285     return false;
2286   #define GET_NEON_IMMEDIATE_CHECK
2287   #include "clang/Basic/arm_neon.inc"
2288   #include "clang/Basic/arm_fp16.inc"
2289   #undef GET_NEON_IMMEDIATE_CHECK
2290   }
2291 
2292   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2293 }
2294 
2295 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2296   switch (BuiltinID) {
2297   default:
2298     return false;
2299   #include "clang/Basic/arm_mve_builtin_sema.inc"
2300   }
2301 }
2302 
2303 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2304                                        CallExpr *TheCall) {
2305   bool Err = false;
2306   switch (BuiltinID) {
2307   default:
2308     return false;
2309 #include "clang/Basic/arm_cde_builtin_sema.inc"
2310   }
2311 
2312   if (Err)
2313     return true;
2314 
2315   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2316 }
2317 
2318 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2319                                         const Expr *CoprocArg, bool WantCDE) {
2320   if (isConstantEvaluated())
2321     return false;
2322 
2323   // We can't check the value of a dependent argument.
2324   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2325     return false;
2326 
2327   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2328   int64_t CoprocNo = CoprocNoAP.getExtValue();
2329   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2330 
2331   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2332   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2333 
2334   if (IsCDECoproc != WantCDE)
2335     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2336            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2337 
2338   return false;
2339 }
2340 
2341 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2342                                         unsigned MaxWidth) {
2343   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2344           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2345           BuiltinID == ARM::BI__builtin_arm_strex ||
2346           BuiltinID == ARM::BI__builtin_arm_stlex ||
2347           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2348           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2349           BuiltinID == AArch64::BI__builtin_arm_strex ||
2350           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2351          "unexpected ARM builtin");
2352   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2353                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2354                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2355                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2356 
2357   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2358 
2359   // Ensure that we have the proper number of arguments.
2360   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2361     return true;
2362 
2363   // Inspect the pointer argument of the atomic builtin.  This should always be
2364   // a pointer type, whose element is an integral scalar or pointer type.
2365   // Because it is a pointer type, we don't have to worry about any implicit
2366   // casts here.
2367   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2368   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2369   if (PointerArgRes.isInvalid())
2370     return true;
2371   PointerArg = PointerArgRes.get();
2372 
2373   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2374   if (!pointerType) {
2375     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2376         << PointerArg->getType() << PointerArg->getSourceRange();
2377     return true;
2378   }
2379 
2380   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2381   // task is to insert the appropriate casts into the AST. First work out just
2382   // what the appropriate type is.
2383   QualType ValType = pointerType->getPointeeType();
2384   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2385   if (IsLdrex)
2386     AddrType.addConst();
2387 
2388   // Issue a warning if the cast is dodgy.
2389   CastKind CastNeeded = CK_NoOp;
2390   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2391     CastNeeded = CK_BitCast;
2392     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2393         << PointerArg->getType() << Context.getPointerType(AddrType)
2394         << AA_Passing << PointerArg->getSourceRange();
2395   }
2396 
2397   // Finally, do the cast and replace the argument with the corrected version.
2398   AddrType = Context.getPointerType(AddrType);
2399   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2400   if (PointerArgRes.isInvalid())
2401     return true;
2402   PointerArg = PointerArgRes.get();
2403 
2404   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2405 
2406   // In general, we allow ints, floats and pointers to be loaded and stored.
2407   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2408       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2409     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2410         << PointerArg->getType() << PointerArg->getSourceRange();
2411     return true;
2412   }
2413 
2414   // But ARM doesn't have instructions to deal with 128-bit versions.
2415   if (Context.getTypeSize(ValType) > MaxWidth) {
2416     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2417     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2418         << PointerArg->getType() << PointerArg->getSourceRange();
2419     return true;
2420   }
2421 
2422   switch (ValType.getObjCLifetime()) {
2423   case Qualifiers::OCL_None:
2424   case Qualifiers::OCL_ExplicitNone:
2425     // okay
2426     break;
2427 
2428   case Qualifiers::OCL_Weak:
2429   case Qualifiers::OCL_Strong:
2430   case Qualifiers::OCL_Autoreleasing:
2431     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2432         << ValType << PointerArg->getSourceRange();
2433     return true;
2434   }
2435 
2436   if (IsLdrex) {
2437     TheCall->setType(ValType);
2438     return false;
2439   }
2440 
2441   // Initialize the argument to be stored.
2442   ExprResult ValArg = TheCall->getArg(0);
2443   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2444       Context, ValType, /*consume*/ false);
2445   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2446   if (ValArg.isInvalid())
2447     return true;
2448   TheCall->setArg(0, ValArg.get());
2449 
2450   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2451   // but the custom checker bypasses all default analysis.
2452   TheCall->setType(Context.IntTy);
2453   return false;
2454 }
2455 
2456 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2457                                        CallExpr *TheCall) {
2458   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2459       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2460       BuiltinID == ARM::BI__builtin_arm_strex ||
2461       BuiltinID == ARM::BI__builtin_arm_stlex) {
2462     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2463   }
2464 
2465   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2466     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2467       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2468   }
2469 
2470   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2471       BuiltinID == ARM::BI__builtin_arm_wsr64)
2472     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2473 
2474   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2475       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2476       BuiltinID == ARM::BI__builtin_arm_wsr ||
2477       BuiltinID == ARM::BI__builtin_arm_wsrp)
2478     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2479 
2480   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2481     return true;
2482   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2483     return true;
2484   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2485     return true;
2486 
2487   // For intrinsics which take an immediate value as part of the instruction,
2488   // range check them here.
2489   // FIXME: VFP Intrinsics should error if VFP not present.
2490   switch (BuiltinID) {
2491   default: return false;
2492   case ARM::BI__builtin_arm_ssat:
2493     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2494   case ARM::BI__builtin_arm_usat:
2495     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2496   case ARM::BI__builtin_arm_ssat16:
2497     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2498   case ARM::BI__builtin_arm_usat16:
2499     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2500   case ARM::BI__builtin_arm_vcvtr_f:
2501   case ARM::BI__builtin_arm_vcvtr_d:
2502     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2503   case ARM::BI__builtin_arm_dmb:
2504   case ARM::BI__builtin_arm_dsb:
2505   case ARM::BI__builtin_arm_isb:
2506   case ARM::BI__builtin_arm_dbg:
2507     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2508   case ARM::BI__builtin_arm_cdp:
2509   case ARM::BI__builtin_arm_cdp2:
2510   case ARM::BI__builtin_arm_mcr:
2511   case ARM::BI__builtin_arm_mcr2:
2512   case ARM::BI__builtin_arm_mrc:
2513   case ARM::BI__builtin_arm_mrc2:
2514   case ARM::BI__builtin_arm_mcrr:
2515   case ARM::BI__builtin_arm_mcrr2:
2516   case ARM::BI__builtin_arm_mrrc:
2517   case ARM::BI__builtin_arm_mrrc2:
2518   case ARM::BI__builtin_arm_ldc:
2519   case ARM::BI__builtin_arm_ldcl:
2520   case ARM::BI__builtin_arm_ldc2:
2521   case ARM::BI__builtin_arm_ldc2l:
2522   case ARM::BI__builtin_arm_stc:
2523   case ARM::BI__builtin_arm_stcl:
2524   case ARM::BI__builtin_arm_stc2:
2525   case ARM::BI__builtin_arm_stc2l:
2526     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2527            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2528                                         /*WantCDE*/ false);
2529   }
2530 }
2531 
2532 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2533                                            unsigned BuiltinID,
2534                                            CallExpr *TheCall) {
2535   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2536       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2537       BuiltinID == AArch64::BI__builtin_arm_strex ||
2538       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2539     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2540   }
2541 
2542   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2543     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2544       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2545       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2546       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2547   }
2548 
2549   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2550       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2551     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2552 
2553   // Memory Tagging Extensions (MTE) Intrinsics
2554   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2555       BuiltinID == AArch64::BI__builtin_arm_addg ||
2556       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2557       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2558       BuiltinID == AArch64::BI__builtin_arm_stg ||
2559       BuiltinID == AArch64::BI__builtin_arm_subp) {
2560     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2561   }
2562 
2563   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2564       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2565       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2566       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2567     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2568 
2569   // Only check the valid encoding range. Any constant in this range would be
2570   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2571   // an exception for incorrect registers. This matches MSVC behavior.
2572   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2573       BuiltinID == AArch64::BI_WriteStatusReg)
2574     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2575 
2576   if (BuiltinID == AArch64::BI__getReg)
2577     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2578 
2579   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2580     return true;
2581 
2582   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2583     return true;
2584 
2585   // For intrinsics which take an immediate value as part of the instruction,
2586   // range check them here.
2587   unsigned i = 0, l = 0, u = 0;
2588   switch (BuiltinID) {
2589   default: return false;
2590   case AArch64::BI__builtin_arm_dmb:
2591   case AArch64::BI__builtin_arm_dsb:
2592   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2593   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2594   }
2595 
2596   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2597 }
2598 
2599 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2600   if (Arg->getType()->getAsPlaceholderType())
2601     return false;
2602 
2603   // The first argument needs to be a record field access.
2604   // If it is an array element access, we delay decision
2605   // to BPF backend to check whether the access is a
2606   // field access or not.
2607   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2608           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2609           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2610 }
2611 
2612 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2613                             QualType VectorTy, QualType EltTy) {
2614   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2615   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2616     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2617         << Call->getSourceRange() << VectorEltTy << EltTy;
2618     return false;
2619   }
2620   return true;
2621 }
2622 
2623 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2624   QualType ArgType = Arg->getType();
2625   if (ArgType->getAsPlaceholderType())
2626     return false;
2627 
2628   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2629   // format:
2630   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2631   //   2. <type> var;
2632   //      __builtin_preserve_type_info(var, flag);
2633   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2634       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2635     return false;
2636 
2637   // Typedef type.
2638   if (ArgType->getAs<TypedefType>())
2639     return true;
2640 
2641   // Record type or Enum type.
2642   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2643   if (const auto *RT = Ty->getAs<RecordType>()) {
2644     if (!RT->getDecl()->getDeclName().isEmpty())
2645       return true;
2646   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2647     if (!ET->getDecl()->getDeclName().isEmpty())
2648       return true;
2649   }
2650 
2651   return false;
2652 }
2653 
2654 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2655   QualType ArgType = Arg->getType();
2656   if (ArgType->getAsPlaceholderType())
2657     return false;
2658 
2659   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2660   // format:
2661   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2662   //                                 flag);
2663   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2664   if (!UO)
2665     return false;
2666 
2667   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2668   if (!CE)
2669     return false;
2670   if (CE->getCastKind() != CK_IntegralToPointer &&
2671       CE->getCastKind() != CK_NullToPointer)
2672     return false;
2673 
2674   // The integer must be from an EnumConstantDecl.
2675   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2676   if (!DR)
2677     return false;
2678 
2679   const EnumConstantDecl *Enumerator =
2680       dyn_cast<EnumConstantDecl>(DR->getDecl());
2681   if (!Enumerator)
2682     return false;
2683 
2684   // The type must be EnumType.
2685   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2686   const auto *ET = Ty->getAs<EnumType>();
2687   if (!ET)
2688     return false;
2689 
2690   // The enum value must be supported.
2691   return llvm::is_contained(ET->getDecl()->enumerators(), Enumerator);
2692 }
2693 
2694 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2695                                        CallExpr *TheCall) {
2696   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2697           BuiltinID == BPF::BI__builtin_btf_type_id ||
2698           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2699           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2700          "unexpected BPF builtin");
2701 
2702   if (checkArgCount(*this, TheCall, 2))
2703     return true;
2704 
2705   // The second argument needs to be a constant int
2706   Expr *Arg = TheCall->getArg(1);
2707   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2708   diag::kind kind;
2709   if (!Value) {
2710     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2711       kind = diag::err_preserve_field_info_not_const;
2712     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2713       kind = diag::err_btf_type_id_not_const;
2714     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2715       kind = diag::err_preserve_type_info_not_const;
2716     else
2717       kind = diag::err_preserve_enum_value_not_const;
2718     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2719     return true;
2720   }
2721 
2722   // The first argument
2723   Arg = TheCall->getArg(0);
2724   bool InvalidArg = false;
2725   bool ReturnUnsignedInt = true;
2726   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2727     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2728       InvalidArg = true;
2729       kind = diag::err_preserve_field_info_not_field;
2730     }
2731   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2732     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2733       InvalidArg = true;
2734       kind = diag::err_preserve_type_info_invalid;
2735     }
2736   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2737     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2738       InvalidArg = true;
2739       kind = diag::err_preserve_enum_value_invalid;
2740     }
2741     ReturnUnsignedInt = false;
2742   } else if (BuiltinID == BPF::BI__builtin_btf_type_id) {
2743     ReturnUnsignedInt = false;
2744   }
2745 
2746   if (InvalidArg) {
2747     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2748     return true;
2749   }
2750 
2751   if (ReturnUnsignedInt)
2752     TheCall->setType(Context.UnsignedIntTy);
2753   else
2754     TheCall->setType(Context.UnsignedLongTy);
2755   return false;
2756 }
2757 
2758 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2759   struct ArgInfo {
2760     uint8_t OpNum;
2761     bool IsSigned;
2762     uint8_t BitWidth;
2763     uint8_t Align;
2764   };
2765   struct BuiltinInfo {
2766     unsigned BuiltinID;
2767     ArgInfo Infos[2];
2768   };
2769 
2770   static BuiltinInfo Infos[] = {
2771     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2772     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2773     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2774     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2775     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2776     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2777     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2778     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2779     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2780     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2781     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2782 
2783     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2786     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2787     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2788     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2789     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2794 
2795     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2802     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2810     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2817     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2819     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2821     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2823     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2840     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2841     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2843     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2844     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2846     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2847                                                       {{ 1, false, 6,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2849     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2850     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2855                                                       {{ 1, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2862                                                        { 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2864                                                        { 2, false, 6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2866                                                        { 3, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2868                                                        { 3, false, 6,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2874     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2877     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2885                                                       {{ 2, false, 4,  0 },
2886                                                        { 3, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2888                                                       {{ 2, false, 4,  0 },
2889                                                        { 3, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2891                                                       {{ 2, false, 4,  0 },
2892                                                        { 3, false, 5,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2894                                                       {{ 2, false, 4,  0 },
2895                                                        { 3, false, 5,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2898     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2903     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2907                                                        { 2, false, 5,  0 }} },
2908     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2909                                                        { 2, false, 6,  0 }} },
2910     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2911     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2912     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2913     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2914     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2915     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2916     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2917     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2918     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2919                                                       {{ 1, false, 4,  0 }} },
2920     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2921     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2922                                                       {{ 1, false, 4,  0 }} },
2923     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2924     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2925     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2926     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2927     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2928     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2929     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2930     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2931     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2932     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2933     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2934     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2935     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2936     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2937     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2938     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2939     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2940     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2941     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2942     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2943                                                       {{ 3, false, 1,  0 }} },
2944     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2945     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2946     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2947     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2948                                                       {{ 3, false, 1,  0 }} },
2949     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2950     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2951     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2952     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2953                                                       {{ 3, false, 1,  0 }} },
2954   };
2955 
2956   // Use a dynamically initialized static to sort the table exactly once on
2957   // first run.
2958   static const bool SortOnce =
2959       (llvm::sort(Infos,
2960                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2961                    return LHS.BuiltinID < RHS.BuiltinID;
2962                  }),
2963        true);
2964   (void)SortOnce;
2965 
2966   const BuiltinInfo *F = llvm::partition_point(
2967       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2968   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2969     return false;
2970 
2971   bool Error = false;
2972 
2973   for (const ArgInfo &A : F->Infos) {
2974     // Ignore empty ArgInfo elements.
2975     if (A.BitWidth == 0)
2976       continue;
2977 
2978     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2979     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2980     if (!A.Align) {
2981       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2982     } else {
2983       unsigned M = 1 << A.Align;
2984       Min *= M;
2985       Max *= M;
2986       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2987       Error |= SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2988     }
2989   }
2990   return Error;
2991 }
2992 
2993 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2994                                            CallExpr *TheCall) {
2995   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2996 }
2997 
2998 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2999                                         unsigned BuiltinID, CallExpr *TheCall) {
3000   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
3001          CheckMipsBuiltinArgument(BuiltinID, TheCall);
3002 }
3003 
3004 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
3005                                CallExpr *TheCall) {
3006 
3007   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
3008       BuiltinID <= Mips::BI__builtin_mips_lwx) {
3009     if (!TI.hasFeature("dsp"))
3010       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
3011   }
3012 
3013   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
3014       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
3015     if (!TI.hasFeature("dspr2"))
3016       return Diag(TheCall->getBeginLoc(),
3017                   diag::err_mips_builtin_requires_dspr2);
3018   }
3019 
3020   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
3021       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
3022     if (!TI.hasFeature("msa"))
3023       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
3024   }
3025 
3026   return false;
3027 }
3028 
3029 // CheckMipsBuiltinArgument - Checks the constant value passed to the
3030 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
3031 // ordering for DSP is unspecified. MSA is ordered by the data format used
3032 // by the underlying instruction i.e., df/m, df/n and then by size.
3033 //
3034 // FIXME: The size tests here should instead be tablegen'd along with the
3035 //        definitions from include/clang/Basic/BuiltinsMips.def.
3036 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
3037 //        be too.
3038 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
3039   unsigned i = 0, l = 0, u = 0, m = 0;
3040   switch (BuiltinID) {
3041   default: return false;
3042   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
3043   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
3044   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3045   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3046   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3047   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3048   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3049   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3050   // df/m field.
3051   // These intrinsics take an unsigned 3 bit immediate.
3052   case Mips::BI__builtin_msa_bclri_b:
3053   case Mips::BI__builtin_msa_bnegi_b:
3054   case Mips::BI__builtin_msa_bseti_b:
3055   case Mips::BI__builtin_msa_sat_s_b:
3056   case Mips::BI__builtin_msa_sat_u_b:
3057   case Mips::BI__builtin_msa_slli_b:
3058   case Mips::BI__builtin_msa_srai_b:
3059   case Mips::BI__builtin_msa_srari_b:
3060   case Mips::BI__builtin_msa_srli_b:
3061   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3062   case Mips::BI__builtin_msa_binsli_b:
3063   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3064   // These intrinsics take an unsigned 4 bit immediate.
3065   case Mips::BI__builtin_msa_bclri_h:
3066   case Mips::BI__builtin_msa_bnegi_h:
3067   case Mips::BI__builtin_msa_bseti_h:
3068   case Mips::BI__builtin_msa_sat_s_h:
3069   case Mips::BI__builtin_msa_sat_u_h:
3070   case Mips::BI__builtin_msa_slli_h:
3071   case Mips::BI__builtin_msa_srai_h:
3072   case Mips::BI__builtin_msa_srari_h:
3073   case Mips::BI__builtin_msa_srli_h:
3074   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3075   case Mips::BI__builtin_msa_binsli_h:
3076   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3077   // These intrinsics take an unsigned 5 bit immediate.
3078   // The first block of intrinsics actually have an unsigned 5 bit field,
3079   // not a df/n field.
3080   case Mips::BI__builtin_msa_cfcmsa:
3081   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3082   case Mips::BI__builtin_msa_clei_u_b:
3083   case Mips::BI__builtin_msa_clei_u_h:
3084   case Mips::BI__builtin_msa_clei_u_w:
3085   case Mips::BI__builtin_msa_clei_u_d:
3086   case Mips::BI__builtin_msa_clti_u_b:
3087   case Mips::BI__builtin_msa_clti_u_h:
3088   case Mips::BI__builtin_msa_clti_u_w:
3089   case Mips::BI__builtin_msa_clti_u_d:
3090   case Mips::BI__builtin_msa_maxi_u_b:
3091   case Mips::BI__builtin_msa_maxi_u_h:
3092   case Mips::BI__builtin_msa_maxi_u_w:
3093   case Mips::BI__builtin_msa_maxi_u_d:
3094   case Mips::BI__builtin_msa_mini_u_b:
3095   case Mips::BI__builtin_msa_mini_u_h:
3096   case Mips::BI__builtin_msa_mini_u_w:
3097   case Mips::BI__builtin_msa_mini_u_d:
3098   case Mips::BI__builtin_msa_addvi_b:
3099   case Mips::BI__builtin_msa_addvi_h:
3100   case Mips::BI__builtin_msa_addvi_w:
3101   case Mips::BI__builtin_msa_addvi_d:
3102   case Mips::BI__builtin_msa_bclri_w:
3103   case Mips::BI__builtin_msa_bnegi_w:
3104   case Mips::BI__builtin_msa_bseti_w:
3105   case Mips::BI__builtin_msa_sat_s_w:
3106   case Mips::BI__builtin_msa_sat_u_w:
3107   case Mips::BI__builtin_msa_slli_w:
3108   case Mips::BI__builtin_msa_srai_w:
3109   case Mips::BI__builtin_msa_srari_w:
3110   case Mips::BI__builtin_msa_srli_w:
3111   case Mips::BI__builtin_msa_srlri_w:
3112   case Mips::BI__builtin_msa_subvi_b:
3113   case Mips::BI__builtin_msa_subvi_h:
3114   case Mips::BI__builtin_msa_subvi_w:
3115   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3116   case Mips::BI__builtin_msa_binsli_w:
3117   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3118   // These intrinsics take an unsigned 6 bit immediate.
3119   case Mips::BI__builtin_msa_bclri_d:
3120   case Mips::BI__builtin_msa_bnegi_d:
3121   case Mips::BI__builtin_msa_bseti_d:
3122   case Mips::BI__builtin_msa_sat_s_d:
3123   case Mips::BI__builtin_msa_sat_u_d:
3124   case Mips::BI__builtin_msa_slli_d:
3125   case Mips::BI__builtin_msa_srai_d:
3126   case Mips::BI__builtin_msa_srari_d:
3127   case Mips::BI__builtin_msa_srli_d:
3128   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3129   case Mips::BI__builtin_msa_binsli_d:
3130   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3131   // These intrinsics take a signed 5 bit immediate.
3132   case Mips::BI__builtin_msa_ceqi_b:
3133   case Mips::BI__builtin_msa_ceqi_h:
3134   case Mips::BI__builtin_msa_ceqi_w:
3135   case Mips::BI__builtin_msa_ceqi_d:
3136   case Mips::BI__builtin_msa_clti_s_b:
3137   case Mips::BI__builtin_msa_clti_s_h:
3138   case Mips::BI__builtin_msa_clti_s_w:
3139   case Mips::BI__builtin_msa_clti_s_d:
3140   case Mips::BI__builtin_msa_clei_s_b:
3141   case Mips::BI__builtin_msa_clei_s_h:
3142   case Mips::BI__builtin_msa_clei_s_w:
3143   case Mips::BI__builtin_msa_clei_s_d:
3144   case Mips::BI__builtin_msa_maxi_s_b:
3145   case Mips::BI__builtin_msa_maxi_s_h:
3146   case Mips::BI__builtin_msa_maxi_s_w:
3147   case Mips::BI__builtin_msa_maxi_s_d:
3148   case Mips::BI__builtin_msa_mini_s_b:
3149   case Mips::BI__builtin_msa_mini_s_h:
3150   case Mips::BI__builtin_msa_mini_s_w:
3151   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3152   // These intrinsics take an unsigned 8 bit immediate.
3153   case Mips::BI__builtin_msa_andi_b:
3154   case Mips::BI__builtin_msa_nori_b:
3155   case Mips::BI__builtin_msa_ori_b:
3156   case Mips::BI__builtin_msa_shf_b:
3157   case Mips::BI__builtin_msa_shf_h:
3158   case Mips::BI__builtin_msa_shf_w:
3159   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3160   case Mips::BI__builtin_msa_bseli_b:
3161   case Mips::BI__builtin_msa_bmnzi_b:
3162   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3163   // df/n format
3164   // These intrinsics take an unsigned 4 bit immediate.
3165   case Mips::BI__builtin_msa_copy_s_b:
3166   case Mips::BI__builtin_msa_copy_u_b:
3167   case Mips::BI__builtin_msa_insve_b:
3168   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3169   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3170   // These intrinsics take an unsigned 3 bit immediate.
3171   case Mips::BI__builtin_msa_copy_s_h:
3172   case Mips::BI__builtin_msa_copy_u_h:
3173   case Mips::BI__builtin_msa_insve_h:
3174   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3175   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3176   // These intrinsics take an unsigned 2 bit immediate.
3177   case Mips::BI__builtin_msa_copy_s_w:
3178   case Mips::BI__builtin_msa_copy_u_w:
3179   case Mips::BI__builtin_msa_insve_w:
3180   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3181   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3182   // These intrinsics take an unsigned 1 bit immediate.
3183   case Mips::BI__builtin_msa_copy_s_d:
3184   case Mips::BI__builtin_msa_copy_u_d:
3185   case Mips::BI__builtin_msa_insve_d:
3186   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3187   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3188   // Memory offsets and immediate loads.
3189   // These intrinsics take a signed 10 bit immediate.
3190   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3191   case Mips::BI__builtin_msa_ldi_h:
3192   case Mips::BI__builtin_msa_ldi_w:
3193   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3194   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3195   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3196   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3197   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3198   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3199   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3200   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3201   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3202   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3203   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3204   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3205   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3206   }
3207 
3208   if (!m)
3209     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3210 
3211   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3212          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3213 }
3214 
3215 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3216 /// advancing the pointer over the consumed characters. The decoded type is
3217 /// returned. If the decoded type represents a constant integer with a
3218 /// constraint on its value then Mask is set to that value. The type descriptors
3219 /// used in Str are specific to PPC MMA builtins and are documented in the file
3220 /// defining the PPC builtins.
3221 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3222                                         unsigned &Mask) {
3223   bool RequireICE = false;
3224   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3225   switch (*Str++) {
3226   case 'V':
3227     return Context.getVectorType(Context.UnsignedCharTy, 16,
3228                                  VectorType::VectorKind::AltiVecVector);
3229   case 'i': {
3230     char *End;
3231     unsigned size = strtoul(Str, &End, 10);
3232     assert(End != Str && "Missing constant parameter constraint");
3233     Str = End;
3234     Mask = size;
3235     return Context.IntTy;
3236   }
3237   case 'W': {
3238     char *End;
3239     unsigned size = strtoul(Str, &End, 10);
3240     assert(End != Str && "Missing PowerPC MMA type size");
3241     Str = End;
3242     QualType Type;
3243     switch (size) {
3244   #define PPC_VECTOR_TYPE(typeName, Id, size) \
3245     case size: Type = Context.Id##Ty; break;
3246   #include "clang/Basic/PPCTypes.def"
3247     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3248     }
3249     bool CheckVectorArgs = false;
3250     while (!CheckVectorArgs) {
3251       switch (*Str++) {
3252       case '*':
3253         Type = Context.getPointerType(Type);
3254         break;
3255       case 'C':
3256         Type = Type.withConst();
3257         break;
3258       default:
3259         CheckVectorArgs = true;
3260         --Str;
3261         break;
3262       }
3263     }
3264     return Type;
3265   }
3266   default:
3267     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3268   }
3269 }
3270 
3271 static bool isPPC_64Builtin(unsigned BuiltinID) {
3272   // These builtins only work on PPC 64bit targets.
3273   switch (BuiltinID) {
3274   case PPC::BI__builtin_divde:
3275   case PPC::BI__builtin_divdeu:
3276   case PPC::BI__builtin_bpermd:
3277   case PPC::BI__builtin_ppc_ldarx:
3278   case PPC::BI__builtin_ppc_stdcx:
3279   case PPC::BI__builtin_ppc_tdw:
3280   case PPC::BI__builtin_ppc_trapd:
3281   case PPC::BI__builtin_ppc_cmpeqb:
3282   case PPC::BI__builtin_ppc_setb:
3283   case PPC::BI__builtin_ppc_mulhd:
3284   case PPC::BI__builtin_ppc_mulhdu:
3285   case PPC::BI__builtin_ppc_maddhd:
3286   case PPC::BI__builtin_ppc_maddhdu:
3287   case PPC::BI__builtin_ppc_maddld:
3288   case PPC::BI__builtin_ppc_load8r:
3289   case PPC::BI__builtin_ppc_store8r:
3290   case PPC::BI__builtin_ppc_insert_exp:
3291   case PPC::BI__builtin_ppc_extract_sig:
3292   case PPC::BI__builtin_ppc_addex:
3293   case PPC::BI__builtin_darn:
3294   case PPC::BI__builtin_darn_raw:
3295   case PPC::BI__builtin_ppc_compare_and_swaplp:
3296   case PPC::BI__builtin_ppc_fetch_and_addlp:
3297   case PPC::BI__builtin_ppc_fetch_and_andlp:
3298   case PPC::BI__builtin_ppc_fetch_and_orlp:
3299   case PPC::BI__builtin_ppc_fetch_and_swaplp:
3300     return true;
3301   }
3302   return false;
3303 }
3304 
3305 static bool SemaFeatureCheck(Sema &S, CallExpr *TheCall,
3306                              StringRef FeatureToCheck, unsigned DiagID,
3307                              StringRef DiagArg = "") {
3308   if (S.Context.getTargetInfo().hasFeature(FeatureToCheck))
3309     return false;
3310 
3311   if (DiagArg.empty())
3312     S.Diag(TheCall->getBeginLoc(), DiagID) << TheCall->getSourceRange();
3313   else
3314     S.Diag(TheCall->getBeginLoc(), DiagID)
3315         << DiagArg << TheCall->getSourceRange();
3316 
3317   return true;
3318 }
3319 
3320 /// Returns true if the argument consists of one contiguous run of 1s with any
3321 /// number of 0s on either side. The 1s are allowed to wrap from LSB to MSB, so
3322 /// 0x000FFF0, 0x0000FFFF, 0xFF0000FF, 0x0 are all runs. 0x0F0F0000 is not,
3323 /// since all 1s are not contiguous.
3324 bool Sema::SemaValueIsRunOfOnes(CallExpr *TheCall, unsigned ArgNum) {
3325   llvm::APSInt Result;
3326   // We can't check the value of a dependent argument.
3327   Expr *Arg = TheCall->getArg(ArgNum);
3328   if (Arg->isTypeDependent() || Arg->isValueDependent())
3329     return false;
3330 
3331   // Check constant-ness first.
3332   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3333     return true;
3334 
3335   // Check contiguous run of 1s, 0xFF0000FF is also a run of 1s.
3336   if (Result.isShiftedMask() || (~Result).isShiftedMask())
3337     return false;
3338 
3339   return Diag(TheCall->getBeginLoc(),
3340               diag::err_argument_not_contiguous_bit_field)
3341          << ArgNum << Arg->getSourceRange();
3342 }
3343 
3344 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3345                                        CallExpr *TheCall) {
3346   unsigned i = 0, l = 0, u = 0;
3347   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3348   llvm::APSInt Result;
3349 
3350   if (isPPC_64Builtin(BuiltinID) && !IsTarget64Bit)
3351     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3352            << TheCall->getSourceRange();
3353 
3354   switch (BuiltinID) {
3355   default: return false;
3356   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3357   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3358     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3359            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3360   case PPC::BI__builtin_altivec_dss:
3361     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3362   case PPC::BI__builtin_tbegin:
3363   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3364   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3365   case PPC::BI__builtin_tabortwc:
3366   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3367   case PPC::BI__builtin_tabortwci:
3368   case PPC::BI__builtin_tabortdci:
3369     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3370            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3371   case PPC::BI__builtin_altivec_dst:
3372   case PPC::BI__builtin_altivec_dstt:
3373   case PPC::BI__builtin_altivec_dstst:
3374   case PPC::BI__builtin_altivec_dststt:
3375     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3376   case PPC::BI__builtin_vsx_xxpermdi:
3377   case PPC::BI__builtin_vsx_xxsldwi:
3378     return SemaBuiltinVSX(TheCall);
3379   case PPC::BI__builtin_divwe:
3380   case PPC::BI__builtin_divweu:
3381   case PPC::BI__builtin_divde:
3382   case PPC::BI__builtin_divdeu:
3383     return SemaFeatureCheck(*this, TheCall, "extdiv",
3384                             diag::err_ppc_builtin_only_on_arch, "7");
3385   case PPC::BI__builtin_bpermd:
3386     return SemaFeatureCheck(*this, TheCall, "bpermd",
3387                             diag::err_ppc_builtin_only_on_arch, "7");
3388   case PPC::BI__builtin_unpack_vector_int128:
3389     return SemaFeatureCheck(*this, TheCall, "vsx",
3390                             diag::err_ppc_builtin_only_on_arch, "7") ||
3391            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3392   case PPC::BI__builtin_pack_vector_int128:
3393     return SemaFeatureCheck(*this, TheCall, "vsx",
3394                             diag::err_ppc_builtin_only_on_arch, "7");
3395   case PPC::BI__builtin_altivec_vgnb:
3396      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3397   case PPC::BI__builtin_altivec_vec_replace_elt:
3398   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3399     QualType VecTy = TheCall->getArg(0)->getType();
3400     QualType EltTy = TheCall->getArg(1)->getType();
3401     unsigned Width = Context.getIntWidth(EltTy);
3402     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3403            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3404   }
3405   case PPC::BI__builtin_vsx_xxeval:
3406      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3407   case PPC::BI__builtin_altivec_vsldbi:
3408      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3409   case PPC::BI__builtin_altivec_vsrdbi:
3410      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3411   case PPC::BI__builtin_vsx_xxpermx:
3412      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3413   case PPC::BI__builtin_ppc_tw:
3414   case PPC::BI__builtin_ppc_tdw:
3415     return SemaBuiltinConstantArgRange(TheCall, 2, 1, 31);
3416   case PPC::BI__builtin_ppc_cmpeqb:
3417   case PPC::BI__builtin_ppc_setb:
3418   case PPC::BI__builtin_ppc_maddhd:
3419   case PPC::BI__builtin_ppc_maddhdu:
3420   case PPC::BI__builtin_ppc_maddld:
3421     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3422                             diag::err_ppc_builtin_only_on_arch, "9");
3423   case PPC::BI__builtin_ppc_cmprb:
3424     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3425                             diag::err_ppc_builtin_only_on_arch, "9") ||
3426            SemaBuiltinConstantArgRange(TheCall, 0, 0, 1);
3427   // For __rlwnm, __rlwimi and __rldimi, the last parameter mask must
3428   // be a constant that represents a contiguous bit field.
3429   case PPC::BI__builtin_ppc_rlwnm:
3430     return SemaValueIsRunOfOnes(TheCall, 2);
3431   case PPC::BI__builtin_ppc_rlwimi:
3432   case PPC::BI__builtin_ppc_rldimi:
3433     return SemaBuiltinConstantArg(TheCall, 2, Result) ||
3434            SemaValueIsRunOfOnes(TheCall, 3);
3435   case PPC::BI__builtin_ppc_extract_exp:
3436   case PPC::BI__builtin_ppc_extract_sig:
3437   case PPC::BI__builtin_ppc_insert_exp:
3438     return SemaFeatureCheck(*this, TheCall, "power9-vector",
3439                             diag::err_ppc_builtin_only_on_arch, "9");
3440   case PPC::BI__builtin_ppc_addex: {
3441     if (SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3442                          diag::err_ppc_builtin_only_on_arch, "9") ||
3443         SemaBuiltinConstantArgRange(TheCall, 2, 0, 3))
3444       return true;
3445     // Output warning for reserved values 1 to 3.
3446     int ArgValue =
3447         TheCall->getArg(2)->getIntegerConstantExpr(Context)->getSExtValue();
3448     if (ArgValue != 0)
3449       Diag(TheCall->getBeginLoc(), diag::warn_argument_undefined_behaviour)
3450           << ArgValue;
3451     return false;
3452   }
3453   case PPC::BI__builtin_ppc_mtfsb0:
3454   case PPC::BI__builtin_ppc_mtfsb1:
3455     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
3456   case PPC::BI__builtin_ppc_mtfsf:
3457     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 255);
3458   case PPC::BI__builtin_ppc_mtfsfi:
3459     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 7) ||
3460            SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
3461   case PPC::BI__builtin_ppc_alignx:
3462     return SemaBuiltinConstantArgPower2(TheCall, 0);
3463   case PPC::BI__builtin_ppc_rdlam:
3464     return SemaValueIsRunOfOnes(TheCall, 2);
3465   case PPC::BI__builtin_ppc_icbt:
3466   case PPC::BI__builtin_ppc_sthcx:
3467   case PPC::BI__builtin_ppc_stbcx:
3468   case PPC::BI__builtin_ppc_lharx:
3469   case PPC::BI__builtin_ppc_lbarx:
3470     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3471                             diag::err_ppc_builtin_only_on_arch, "8");
3472   case PPC::BI__builtin_vsx_ldrmb:
3473   case PPC::BI__builtin_vsx_strmb:
3474     return SemaFeatureCheck(*this, TheCall, "isa-v207-instructions",
3475                             diag::err_ppc_builtin_only_on_arch, "8") ||
3476            SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
3477   case PPC::BI__builtin_altivec_vcntmbb:
3478   case PPC::BI__builtin_altivec_vcntmbh:
3479   case PPC::BI__builtin_altivec_vcntmbw:
3480   case PPC::BI__builtin_altivec_vcntmbd:
3481     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3482   case PPC::BI__builtin_darn:
3483   case PPC::BI__builtin_darn_raw:
3484   case PPC::BI__builtin_darn_32:
3485     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3486                             diag::err_ppc_builtin_only_on_arch, "9");
3487   case PPC::BI__builtin_vsx_xxgenpcvbm:
3488   case PPC::BI__builtin_vsx_xxgenpcvhm:
3489   case PPC::BI__builtin_vsx_xxgenpcvwm:
3490   case PPC::BI__builtin_vsx_xxgenpcvdm:
3491     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3);
3492   case PPC::BI__builtin_ppc_compare_exp_uo:
3493   case PPC::BI__builtin_ppc_compare_exp_lt:
3494   case PPC::BI__builtin_ppc_compare_exp_gt:
3495   case PPC::BI__builtin_ppc_compare_exp_eq:
3496     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3497                             diag::err_ppc_builtin_only_on_arch, "9") ||
3498            SemaFeatureCheck(*this, TheCall, "vsx",
3499                             diag::err_ppc_builtin_requires_vsx);
3500   case PPC::BI__builtin_ppc_test_data_class: {
3501     // Check if the first argument of the __builtin_ppc_test_data_class call is
3502     // valid. The argument must be either a 'float' or a 'double'.
3503     QualType ArgType = TheCall->getArg(0)->getType();
3504     if (ArgType != QualType(Context.FloatTy) &&
3505         ArgType != QualType(Context.DoubleTy))
3506       return Diag(TheCall->getBeginLoc(),
3507                   diag::err_ppc_invalid_test_data_class_type);
3508     return SemaFeatureCheck(*this, TheCall, "isa-v30-instructions",
3509                             diag::err_ppc_builtin_only_on_arch, "9") ||
3510            SemaFeatureCheck(*this, TheCall, "vsx",
3511                             diag::err_ppc_builtin_requires_vsx) ||
3512            SemaBuiltinConstantArgRange(TheCall, 1, 0, 127);
3513   }
3514   case PPC::BI__builtin_ppc_load8r:
3515   case PPC::BI__builtin_ppc_store8r:
3516     return SemaFeatureCheck(*this, TheCall, "isa-v206-instructions",
3517                             diag::err_ppc_builtin_only_on_arch, "7");
3518 #define CUSTOM_BUILTIN(Name, Intr, Types, Acc)                                 \
3519   case PPC::BI__builtin_##Name:                                                \
3520     return SemaBuiltinPPCMMACall(TheCall, BuiltinID, Types);
3521 #include "clang/Basic/BuiltinsPPC.def"
3522   }
3523   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3524 }
3525 
3526 // Check if the given type is a non-pointer PPC MMA type. This function is used
3527 // in Sema to prevent invalid uses of restricted PPC MMA types.
3528 bool Sema::CheckPPCMMAType(QualType Type, SourceLocation TypeLoc) {
3529   if (Type->isPointerType() || Type->isArrayType())
3530     return false;
3531 
3532   QualType CoreType = Type.getCanonicalType().getUnqualifiedType();
3533 #define PPC_VECTOR_TYPE(Name, Id, Size) || CoreType == Context.Id##Ty
3534   if (false
3535 #include "clang/Basic/PPCTypes.def"
3536      ) {
3537     Diag(TypeLoc, diag::err_ppc_invalid_use_mma_type);
3538     return true;
3539   }
3540   return false;
3541 }
3542 
3543 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3544                                           CallExpr *TheCall) {
3545   // position of memory order and scope arguments in the builtin
3546   unsigned OrderIndex, ScopeIndex;
3547   switch (BuiltinID) {
3548   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3549   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3550   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3551   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3552     OrderIndex = 2;
3553     ScopeIndex = 3;
3554     break;
3555   case AMDGPU::BI__builtin_amdgcn_fence:
3556     OrderIndex = 0;
3557     ScopeIndex = 1;
3558     break;
3559   default:
3560     return false;
3561   }
3562 
3563   ExprResult Arg = TheCall->getArg(OrderIndex);
3564   auto ArgExpr = Arg.get();
3565   Expr::EvalResult ArgResult;
3566 
3567   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3568     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3569            << ArgExpr->getType();
3570   auto Ord = ArgResult.Val.getInt().getZExtValue();
3571 
3572   // Check validity of memory ordering as per C11 / C++11's memody model.
3573   // Only fence needs check. Atomic dec/inc allow all memory orders.
3574   if (!llvm::isValidAtomicOrderingCABI(Ord))
3575     return Diag(ArgExpr->getBeginLoc(),
3576                 diag::warn_atomic_op_has_invalid_memory_order)
3577            << ArgExpr->getSourceRange();
3578   switch (static_cast<llvm::AtomicOrderingCABI>(Ord)) {
3579   case llvm::AtomicOrderingCABI::relaxed:
3580   case llvm::AtomicOrderingCABI::consume:
3581     if (BuiltinID == AMDGPU::BI__builtin_amdgcn_fence)
3582       return Diag(ArgExpr->getBeginLoc(),
3583                   diag::warn_atomic_op_has_invalid_memory_order)
3584              << ArgExpr->getSourceRange();
3585     break;
3586   case llvm::AtomicOrderingCABI::acquire:
3587   case llvm::AtomicOrderingCABI::release:
3588   case llvm::AtomicOrderingCABI::acq_rel:
3589   case llvm::AtomicOrderingCABI::seq_cst:
3590     break;
3591   }
3592 
3593   Arg = TheCall->getArg(ScopeIndex);
3594   ArgExpr = Arg.get();
3595   Expr::EvalResult ArgResult1;
3596   // Check that sync scope is a constant literal
3597   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3598     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3599            << ArgExpr->getType();
3600 
3601   return false;
3602 }
3603 
3604 bool Sema::CheckRISCVLMUL(CallExpr *TheCall, unsigned ArgNum) {
3605   llvm::APSInt Result;
3606 
3607   // We can't check the value of a dependent argument.
3608   Expr *Arg = TheCall->getArg(ArgNum);
3609   if (Arg->isTypeDependent() || Arg->isValueDependent())
3610     return false;
3611 
3612   // Check constant-ness first.
3613   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3614     return true;
3615 
3616   int64_t Val = Result.getSExtValue();
3617   if ((Val >= 0 && Val <= 3) || (Val >= 5 && Val <= 7))
3618     return false;
3619 
3620   return Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_invalid_lmul)
3621          << Arg->getSourceRange();
3622 }
3623 
3624 bool Sema::CheckRISCVBuiltinFunctionCall(const TargetInfo &TI,
3625                                          unsigned BuiltinID,
3626                                          CallExpr *TheCall) {
3627   // CodeGenFunction can also detect this, but this gives a better error
3628   // message.
3629   bool FeatureMissing = false;
3630   SmallVector<StringRef> ReqFeatures;
3631   StringRef Features = Context.BuiltinInfo.getRequiredFeatures(BuiltinID);
3632   Features.split(ReqFeatures, ',');
3633 
3634   // Check if each required feature is included
3635   for (StringRef F : ReqFeatures) {
3636     if (TI.hasFeature(F))
3637       continue;
3638 
3639     // If the feature is 64bit, alter the string so it will print better in
3640     // the diagnostic.
3641     if (F == "64bit")
3642       F = "RV64";
3643 
3644     // Convert features like "zbr" and "experimental-zbr" to "Zbr".
3645     F.consume_front("experimental-");
3646     std::string FeatureStr = F.str();
3647     FeatureStr[0] = std::toupper(FeatureStr[0]);
3648 
3649     // Error message
3650     FeatureMissing = true;
3651     Diag(TheCall->getBeginLoc(), diag::err_riscv_builtin_requires_extension)
3652         << TheCall->getSourceRange() << StringRef(FeatureStr);
3653   }
3654 
3655   if (FeatureMissing)
3656     return true;
3657 
3658   switch (BuiltinID) {
3659   case RISCVVector::BI__builtin_rvv_vsetvli:
3660     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 3) ||
3661            CheckRISCVLMUL(TheCall, 2);
3662   case RISCVVector::BI__builtin_rvv_vsetvlimax:
3663     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3) ||
3664            CheckRISCVLMUL(TheCall, 1);
3665   }
3666 
3667   return false;
3668 }
3669 
3670 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3671                                            CallExpr *TheCall) {
3672   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3673     Expr *Arg = TheCall->getArg(0);
3674     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3675       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3676         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3677                << Arg->getSourceRange();
3678   }
3679 
3680   // For intrinsics which take an immediate value as part of the instruction,
3681   // range check them here.
3682   unsigned i = 0, l = 0, u = 0;
3683   switch (BuiltinID) {
3684   default: return false;
3685   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3686   case SystemZ::BI__builtin_s390_verimb:
3687   case SystemZ::BI__builtin_s390_verimh:
3688   case SystemZ::BI__builtin_s390_verimf:
3689   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3690   case SystemZ::BI__builtin_s390_vfaeb:
3691   case SystemZ::BI__builtin_s390_vfaeh:
3692   case SystemZ::BI__builtin_s390_vfaef:
3693   case SystemZ::BI__builtin_s390_vfaebs:
3694   case SystemZ::BI__builtin_s390_vfaehs:
3695   case SystemZ::BI__builtin_s390_vfaefs:
3696   case SystemZ::BI__builtin_s390_vfaezb:
3697   case SystemZ::BI__builtin_s390_vfaezh:
3698   case SystemZ::BI__builtin_s390_vfaezf:
3699   case SystemZ::BI__builtin_s390_vfaezbs:
3700   case SystemZ::BI__builtin_s390_vfaezhs:
3701   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3702   case SystemZ::BI__builtin_s390_vfisb:
3703   case SystemZ::BI__builtin_s390_vfidb:
3704     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3705            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3706   case SystemZ::BI__builtin_s390_vftcisb:
3707   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3708   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3709   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3710   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3711   case SystemZ::BI__builtin_s390_vstrcb:
3712   case SystemZ::BI__builtin_s390_vstrch:
3713   case SystemZ::BI__builtin_s390_vstrcf:
3714   case SystemZ::BI__builtin_s390_vstrczb:
3715   case SystemZ::BI__builtin_s390_vstrczh:
3716   case SystemZ::BI__builtin_s390_vstrczf:
3717   case SystemZ::BI__builtin_s390_vstrcbs:
3718   case SystemZ::BI__builtin_s390_vstrchs:
3719   case SystemZ::BI__builtin_s390_vstrcfs:
3720   case SystemZ::BI__builtin_s390_vstrczbs:
3721   case SystemZ::BI__builtin_s390_vstrczhs:
3722   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3723   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3724   case SystemZ::BI__builtin_s390_vfminsb:
3725   case SystemZ::BI__builtin_s390_vfmaxsb:
3726   case SystemZ::BI__builtin_s390_vfmindb:
3727   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3728   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3729   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3730   case SystemZ::BI__builtin_s390_vclfnhs:
3731   case SystemZ::BI__builtin_s390_vclfnls:
3732   case SystemZ::BI__builtin_s390_vcfn:
3733   case SystemZ::BI__builtin_s390_vcnf: i = 1; l = 0; u = 15; break;
3734   case SystemZ::BI__builtin_s390_vcrnfs: i = 2; l = 0; u = 15; break;
3735   }
3736   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3737 }
3738 
3739 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3740 /// This checks that the target supports __builtin_cpu_supports and
3741 /// that the string argument is constant and valid.
3742 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3743                                    CallExpr *TheCall) {
3744   Expr *Arg = TheCall->getArg(0);
3745 
3746   // Check if the argument is a string literal.
3747   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3748     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3749            << Arg->getSourceRange();
3750 
3751   // Check the contents of the string.
3752   StringRef Feature =
3753       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3754   if (!TI.validateCpuSupports(Feature))
3755     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3756            << Arg->getSourceRange();
3757   return false;
3758 }
3759 
3760 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3761 /// This checks that the target supports __builtin_cpu_is and
3762 /// that the string argument is constant and valid.
3763 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3764   Expr *Arg = TheCall->getArg(0);
3765 
3766   // Check if the argument is a string literal.
3767   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3768     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3769            << Arg->getSourceRange();
3770 
3771   // Check the contents of the string.
3772   StringRef Feature =
3773       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3774   if (!TI.validateCpuIs(Feature))
3775     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3776            << Arg->getSourceRange();
3777   return false;
3778 }
3779 
3780 // Check if the rounding mode is legal.
3781 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3782   // Indicates if this instruction has rounding control or just SAE.
3783   bool HasRC = false;
3784 
3785   unsigned ArgNum = 0;
3786   switch (BuiltinID) {
3787   default:
3788     return false;
3789   case X86::BI__builtin_ia32_vcvttsd2si32:
3790   case X86::BI__builtin_ia32_vcvttsd2si64:
3791   case X86::BI__builtin_ia32_vcvttsd2usi32:
3792   case X86::BI__builtin_ia32_vcvttsd2usi64:
3793   case X86::BI__builtin_ia32_vcvttss2si32:
3794   case X86::BI__builtin_ia32_vcvttss2si64:
3795   case X86::BI__builtin_ia32_vcvttss2usi32:
3796   case X86::BI__builtin_ia32_vcvttss2usi64:
3797   case X86::BI__builtin_ia32_vcvttsh2si32:
3798   case X86::BI__builtin_ia32_vcvttsh2si64:
3799   case X86::BI__builtin_ia32_vcvttsh2usi32:
3800   case X86::BI__builtin_ia32_vcvttsh2usi64:
3801     ArgNum = 1;
3802     break;
3803   case X86::BI__builtin_ia32_maxpd512:
3804   case X86::BI__builtin_ia32_maxps512:
3805   case X86::BI__builtin_ia32_minpd512:
3806   case X86::BI__builtin_ia32_minps512:
3807   case X86::BI__builtin_ia32_maxph512:
3808   case X86::BI__builtin_ia32_minph512:
3809     ArgNum = 2;
3810     break;
3811   case X86::BI__builtin_ia32_vcvtph2pd512_mask:
3812   case X86::BI__builtin_ia32_vcvtph2psx512_mask:
3813   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3814   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3815   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3816   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3817   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3818   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3819   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3820   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3821   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3822   case X86::BI__builtin_ia32_vcvttph2w512_mask:
3823   case X86::BI__builtin_ia32_vcvttph2uw512_mask:
3824   case X86::BI__builtin_ia32_vcvttph2dq512_mask:
3825   case X86::BI__builtin_ia32_vcvttph2udq512_mask:
3826   case X86::BI__builtin_ia32_vcvttph2qq512_mask:
3827   case X86::BI__builtin_ia32_vcvttph2uqq512_mask:
3828   case X86::BI__builtin_ia32_exp2pd_mask:
3829   case X86::BI__builtin_ia32_exp2ps_mask:
3830   case X86::BI__builtin_ia32_getexppd512_mask:
3831   case X86::BI__builtin_ia32_getexpps512_mask:
3832   case X86::BI__builtin_ia32_getexpph512_mask:
3833   case X86::BI__builtin_ia32_rcp28pd_mask:
3834   case X86::BI__builtin_ia32_rcp28ps_mask:
3835   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3836   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3837   case X86::BI__builtin_ia32_vcomisd:
3838   case X86::BI__builtin_ia32_vcomiss:
3839   case X86::BI__builtin_ia32_vcomish:
3840   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3841     ArgNum = 3;
3842     break;
3843   case X86::BI__builtin_ia32_cmppd512_mask:
3844   case X86::BI__builtin_ia32_cmpps512_mask:
3845   case X86::BI__builtin_ia32_cmpsd_mask:
3846   case X86::BI__builtin_ia32_cmpss_mask:
3847   case X86::BI__builtin_ia32_cmpsh_mask:
3848   case X86::BI__builtin_ia32_vcvtsh2sd_round_mask:
3849   case X86::BI__builtin_ia32_vcvtsh2ss_round_mask:
3850   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3851   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3852   case X86::BI__builtin_ia32_getexpss128_round_mask:
3853   case X86::BI__builtin_ia32_getexpsh128_round_mask:
3854   case X86::BI__builtin_ia32_getmantpd512_mask:
3855   case X86::BI__builtin_ia32_getmantps512_mask:
3856   case X86::BI__builtin_ia32_getmantph512_mask:
3857   case X86::BI__builtin_ia32_maxsd_round_mask:
3858   case X86::BI__builtin_ia32_maxss_round_mask:
3859   case X86::BI__builtin_ia32_maxsh_round_mask:
3860   case X86::BI__builtin_ia32_minsd_round_mask:
3861   case X86::BI__builtin_ia32_minss_round_mask:
3862   case X86::BI__builtin_ia32_minsh_round_mask:
3863   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3864   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3865   case X86::BI__builtin_ia32_reducepd512_mask:
3866   case X86::BI__builtin_ia32_reduceps512_mask:
3867   case X86::BI__builtin_ia32_reduceph512_mask:
3868   case X86::BI__builtin_ia32_rndscalepd_mask:
3869   case X86::BI__builtin_ia32_rndscaleps_mask:
3870   case X86::BI__builtin_ia32_rndscaleph_mask:
3871   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3872   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3873     ArgNum = 4;
3874     break;
3875   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3876   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3877   case X86::BI__builtin_ia32_fixupimmps512_mask:
3878   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3879   case X86::BI__builtin_ia32_fixupimmsd_mask:
3880   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3881   case X86::BI__builtin_ia32_fixupimmss_mask:
3882   case X86::BI__builtin_ia32_fixupimmss_maskz:
3883   case X86::BI__builtin_ia32_getmantsd_round_mask:
3884   case X86::BI__builtin_ia32_getmantss_round_mask:
3885   case X86::BI__builtin_ia32_getmantsh_round_mask:
3886   case X86::BI__builtin_ia32_rangepd512_mask:
3887   case X86::BI__builtin_ia32_rangeps512_mask:
3888   case X86::BI__builtin_ia32_rangesd128_round_mask:
3889   case X86::BI__builtin_ia32_rangess128_round_mask:
3890   case X86::BI__builtin_ia32_reducesd_mask:
3891   case X86::BI__builtin_ia32_reducess_mask:
3892   case X86::BI__builtin_ia32_reducesh_mask:
3893   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3894   case X86::BI__builtin_ia32_rndscaless_round_mask:
3895   case X86::BI__builtin_ia32_rndscalesh_round_mask:
3896     ArgNum = 5;
3897     break;
3898   case X86::BI__builtin_ia32_vcvtsd2si64:
3899   case X86::BI__builtin_ia32_vcvtsd2si32:
3900   case X86::BI__builtin_ia32_vcvtsd2usi32:
3901   case X86::BI__builtin_ia32_vcvtsd2usi64:
3902   case X86::BI__builtin_ia32_vcvtss2si32:
3903   case X86::BI__builtin_ia32_vcvtss2si64:
3904   case X86::BI__builtin_ia32_vcvtss2usi32:
3905   case X86::BI__builtin_ia32_vcvtss2usi64:
3906   case X86::BI__builtin_ia32_vcvtsh2si32:
3907   case X86::BI__builtin_ia32_vcvtsh2si64:
3908   case X86::BI__builtin_ia32_vcvtsh2usi32:
3909   case X86::BI__builtin_ia32_vcvtsh2usi64:
3910   case X86::BI__builtin_ia32_sqrtpd512:
3911   case X86::BI__builtin_ia32_sqrtps512:
3912   case X86::BI__builtin_ia32_sqrtph512:
3913     ArgNum = 1;
3914     HasRC = true;
3915     break;
3916   case X86::BI__builtin_ia32_addph512:
3917   case X86::BI__builtin_ia32_divph512:
3918   case X86::BI__builtin_ia32_mulph512:
3919   case X86::BI__builtin_ia32_subph512:
3920   case X86::BI__builtin_ia32_addpd512:
3921   case X86::BI__builtin_ia32_addps512:
3922   case X86::BI__builtin_ia32_divpd512:
3923   case X86::BI__builtin_ia32_divps512:
3924   case X86::BI__builtin_ia32_mulpd512:
3925   case X86::BI__builtin_ia32_mulps512:
3926   case X86::BI__builtin_ia32_subpd512:
3927   case X86::BI__builtin_ia32_subps512:
3928   case X86::BI__builtin_ia32_cvtsi2sd64:
3929   case X86::BI__builtin_ia32_cvtsi2ss32:
3930   case X86::BI__builtin_ia32_cvtsi2ss64:
3931   case X86::BI__builtin_ia32_cvtusi2sd64:
3932   case X86::BI__builtin_ia32_cvtusi2ss32:
3933   case X86::BI__builtin_ia32_cvtusi2ss64:
3934   case X86::BI__builtin_ia32_vcvtusi2sh:
3935   case X86::BI__builtin_ia32_vcvtusi642sh:
3936   case X86::BI__builtin_ia32_vcvtsi2sh:
3937   case X86::BI__builtin_ia32_vcvtsi642sh:
3938     ArgNum = 2;
3939     HasRC = true;
3940     break;
3941   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3942   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3943   case X86::BI__builtin_ia32_vcvtpd2ph512_mask:
3944   case X86::BI__builtin_ia32_vcvtps2phx512_mask:
3945   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3946   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3947   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3948   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3949   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3950   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3951   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3952   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3953   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3954   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3955   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3956   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3957   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3958   case X86::BI__builtin_ia32_vcvtdq2ph512_mask:
3959   case X86::BI__builtin_ia32_vcvtudq2ph512_mask:
3960   case X86::BI__builtin_ia32_vcvtw2ph512_mask:
3961   case X86::BI__builtin_ia32_vcvtuw2ph512_mask:
3962   case X86::BI__builtin_ia32_vcvtph2w512_mask:
3963   case X86::BI__builtin_ia32_vcvtph2uw512_mask:
3964   case X86::BI__builtin_ia32_vcvtph2dq512_mask:
3965   case X86::BI__builtin_ia32_vcvtph2udq512_mask:
3966   case X86::BI__builtin_ia32_vcvtph2qq512_mask:
3967   case X86::BI__builtin_ia32_vcvtph2uqq512_mask:
3968   case X86::BI__builtin_ia32_vcvtqq2ph512_mask:
3969   case X86::BI__builtin_ia32_vcvtuqq2ph512_mask:
3970     ArgNum = 3;
3971     HasRC = true;
3972     break;
3973   case X86::BI__builtin_ia32_addsh_round_mask:
3974   case X86::BI__builtin_ia32_addss_round_mask:
3975   case X86::BI__builtin_ia32_addsd_round_mask:
3976   case X86::BI__builtin_ia32_divsh_round_mask:
3977   case X86::BI__builtin_ia32_divss_round_mask:
3978   case X86::BI__builtin_ia32_divsd_round_mask:
3979   case X86::BI__builtin_ia32_mulsh_round_mask:
3980   case X86::BI__builtin_ia32_mulss_round_mask:
3981   case X86::BI__builtin_ia32_mulsd_round_mask:
3982   case X86::BI__builtin_ia32_subsh_round_mask:
3983   case X86::BI__builtin_ia32_subss_round_mask:
3984   case X86::BI__builtin_ia32_subsd_round_mask:
3985   case X86::BI__builtin_ia32_scalefph512_mask:
3986   case X86::BI__builtin_ia32_scalefpd512_mask:
3987   case X86::BI__builtin_ia32_scalefps512_mask:
3988   case X86::BI__builtin_ia32_scalefsd_round_mask:
3989   case X86::BI__builtin_ia32_scalefss_round_mask:
3990   case X86::BI__builtin_ia32_scalefsh_round_mask:
3991   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3992   case X86::BI__builtin_ia32_vcvtss2sh_round_mask:
3993   case X86::BI__builtin_ia32_vcvtsd2sh_round_mask:
3994   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3995   case X86::BI__builtin_ia32_sqrtss_round_mask:
3996   case X86::BI__builtin_ia32_sqrtsh_round_mask:
3997   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3998   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3999   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
4000   case X86::BI__builtin_ia32_vfmaddss3_mask:
4001   case X86::BI__builtin_ia32_vfmaddss3_maskz:
4002   case X86::BI__builtin_ia32_vfmaddss3_mask3:
4003   case X86::BI__builtin_ia32_vfmaddsh3_mask:
4004   case X86::BI__builtin_ia32_vfmaddsh3_maskz:
4005   case X86::BI__builtin_ia32_vfmaddsh3_mask3:
4006   case X86::BI__builtin_ia32_vfmaddpd512_mask:
4007   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
4008   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
4009   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
4010   case X86::BI__builtin_ia32_vfmaddps512_mask:
4011   case X86::BI__builtin_ia32_vfmaddps512_maskz:
4012   case X86::BI__builtin_ia32_vfmaddps512_mask3:
4013   case X86::BI__builtin_ia32_vfmsubps512_mask3:
4014   case X86::BI__builtin_ia32_vfmaddph512_mask:
4015   case X86::BI__builtin_ia32_vfmaddph512_maskz:
4016   case X86::BI__builtin_ia32_vfmaddph512_mask3:
4017   case X86::BI__builtin_ia32_vfmsubph512_mask3:
4018   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
4019   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
4020   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
4021   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
4022   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
4023   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
4024   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
4025   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
4026   case X86::BI__builtin_ia32_vfmaddsubph512_mask:
4027   case X86::BI__builtin_ia32_vfmaddsubph512_maskz:
4028   case X86::BI__builtin_ia32_vfmaddsubph512_mask3:
4029   case X86::BI__builtin_ia32_vfmsubaddph512_mask3:
4030   case X86::BI__builtin_ia32_vfmaddcsh_mask:
4031   case X86::BI__builtin_ia32_vfmaddcsh_round_mask:
4032   case X86::BI__builtin_ia32_vfmaddcsh_round_mask3:
4033   case X86::BI__builtin_ia32_vfmaddcph512_mask:
4034   case X86::BI__builtin_ia32_vfmaddcph512_maskz:
4035   case X86::BI__builtin_ia32_vfmaddcph512_mask3:
4036   case X86::BI__builtin_ia32_vfcmaddcsh_mask:
4037   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask:
4038   case X86::BI__builtin_ia32_vfcmaddcsh_round_mask3:
4039   case X86::BI__builtin_ia32_vfcmaddcph512_mask:
4040   case X86::BI__builtin_ia32_vfcmaddcph512_maskz:
4041   case X86::BI__builtin_ia32_vfcmaddcph512_mask3:
4042   case X86::BI__builtin_ia32_vfmulcsh_mask:
4043   case X86::BI__builtin_ia32_vfmulcph512_mask:
4044   case X86::BI__builtin_ia32_vfcmulcsh_mask:
4045   case X86::BI__builtin_ia32_vfcmulcph512_mask:
4046     ArgNum = 4;
4047     HasRC = true;
4048     break;
4049   }
4050 
4051   llvm::APSInt Result;
4052 
4053   // We can't check the value of a dependent argument.
4054   Expr *Arg = TheCall->getArg(ArgNum);
4055   if (Arg->isTypeDependent() || Arg->isValueDependent())
4056     return false;
4057 
4058   // Check constant-ness first.
4059   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4060     return true;
4061 
4062   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
4063   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
4064   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
4065   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
4066   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
4067       Result == 8/*ROUND_NO_EXC*/ ||
4068       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
4069       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
4070     return false;
4071 
4072   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
4073          << Arg->getSourceRange();
4074 }
4075 
4076 // Check if the gather/scatter scale is legal.
4077 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
4078                                              CallExpr *TheCall) {
4079   unsigned ArgNum = 0;
4080   switch (BuiltinID) {
4081   default:
4082     return false;
4083   case X86::BI__builtin_ia32_gatherpfdpd:
4084   case X86::BI__builtin_ia32_gatherpfdps:
4085   case X86::BI__builtin_ia32_gatherpfqpd:
4086   case X86::BI__builtin_ia32_gatherpfqps:
4087   case X86::BI__builtin_ia32_scatterpfdpd:
4088   case X86::BI__builtin_ia32_scatterpfdps:
4089   case X86::BI__builtin_ia32_scatterpfqpd:
4090   case X86::BI__builtin_ia32_scatterpfqps:
4091     ArgNum = 3;
4092     break;
4093   case X86::BI__builtin_ia32_gatherd_pd:
4094   case X86::BI__builtin_ia32_gatherd_pd256:
4095   case X86::BI__builtin_ia32_gatherq_pd:
4096   case X86::BI__builtin_ia32_gatherq_pd256:
4097   case X86::BI__builtin_ia32_gatherd_ps:
4098   case X86::BI__builtin_ia32_gatherd_ps256:
4099   case X86::BI__builtin_ia32_gatherq_ps:
4100   case X86::BI__builtin_ia32_gatherq_ps256:
4101   case X86::BI__builtin_ia32_gatherd_q:
4102   case X86::BI__builtin_ia32_gatherd_q256:
4103   case X86::BI__builtin_ia32_gatherq_q:
4104   case X86::BI__builtin_ia32_gatherq_q256:
4105   case X86::BI__builtin_ia32_gatherd_d:
4106   case X86::BI__builtin_ia32_gatherd_d256:
4107   case X86::BI__builtin_ia32_gatherq_d:
4108   case X86::BI__builtin_ia32_gatherq_d256:
4109   case X86::BI__builtin_ia32_gather3div2df:
4110   case X86::BI__builtin_ia32_gather3div2di:
4111   case X86::BI__builtin_ia32_gather3div4df:
4112   case X86::BI__builtin_ia32_gather3div4di:
4113   case X86::BI__builtin_ia32_gather3div4sf:
4114   case X86::BI__builtin_ia32_gather3div4si:
4115   case X86::BI__builtin_ia32_gather3div8sf:
4116   case X86::BI__builtin_ia32_gather3div8si:
4117   case X86::BI__builtin_ia32_gather3siv2df:
4118   case X86::BI__builtin_ia32_gather3siv2di:
4119   case X86::BI__builtin_ia32_gather3siv4df:
4120   case X86::BI__builtin_ia32_gather3siv4di:
4121   case X86::BI__builtin_ia32_gather3siv4sf:
4122   case X86::BI__builtin_ia32_gather3siv4si:
4123   case X86::BI__builtin_ia32_gather3siv8sf:
4124   case X86::BI__builtin_ia32_gather3siv8si:
4125   case X86::BI__builtin_ia32_gathersiv8df:
4126   case X86::BI__builtin_ia32_gathersiv16sf:
4127   case X86::BI__builtin_ia32_gatherdiv8df:
4128   case X86::BI__builtin_ia32_gatherdiv16sf:
4129   case X86::BI__builtin_ia32_gathersiv8di:
4130   case X86::BI__builtin_ia32_gathersiv16si:
4131   case X86::BI__builtin_ia32_gatherdiv8di:
4132   case X86::BI__builtin_ia32_gatherdiv16si:
4133   case X86::BI__builtin_ia32_scatterdiv2df:
4134   case X86::BI__builtin_ia32_scatterdiv2di:
4135   case X86::BI__builtin_ia32_scatterdiv4df:
4136   case X86::BI__builtin_ia32_scatterdiv4di:
4137   case X86::BI__builtin_ia32_scatterdiv4sf:
4138   case X86::BI__builtin_ia32_scatterdiv4si:
4139   case X86::BI__builtin_ia32_scatterdiv8sf:
4140   case X86::BI__builtin_ia32_scatterdiv8si:
4141   case X86::BI__builtin_ia32_scattersiv2df:
4142   case X86::BI__builtin_ia32_scattersiv2di:
4143   case X86::BI__builtin_ia32_scattersiv4df:
4144   case X86::BI__builtin_ia32_scattersiv4di:
4145   case X86::BI__builtin_ia32_scattersiv4sf:
4146   case X86::BI__builtin_ia32_scattersiv4si:
4147   case X86::BI__builtin_ia32_scattersiv8sf:
4148   case X86::BI__builtin_ia32_scattersiv8si:
4149   case X86::BI__builtin_ia32_scattersiv8df:
4150   case X86::BI__builtin_ia32_scattersiv16sf:
4151   case X86::BI__builtin_ia32_scatterdiv8df:
4152   case X86::BI__builtin_ia32_scatterdiv16sf:
4153   case X86::BI__builtin_ia32_scattersiv8di:
4154   case X86::BI__builtin_ia32_scattersiv16si:
4155   case X86::BI__builtin_ia32_scatterdiv8di:
4156   case X86::BI__builtin_ia32_scatterdiv16si:
4157     ArgNum = 4;
4158     break;
4159   }
4160 
4161   llvm::APSInt Result;
4162 
4163   // We can't check the value of a dependent argument.
4164   Expr *Arg = TheCall->getArg(ArgNum);
4165   if (Arg->isTypeDependent() || Arg->isValueDependent())
4166     return false;
4167 
4168   // Check constant-ness first.
4169   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4170     return true;
4171 
4172   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
4173     return false;
4174 
4175   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
4176          << Arg->getSourceRange();
4177 }
4178 
4179 enum { TileRegLow = 0, TileRegHigh = 7 };
4180 
4181 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
4182                                              ArrayRef<int> ArgNums) {
4183   for (int ArgNum : ArgNums) {
4184     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
4185       return true;
4186   }
4187   return false;
4188 }
4189 
4190 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
4191                                         ArrayRef<int> ArgNums) {
4192   // Because the max number of tile register is TileRegHigh + 1, so here we use
4193   // each bit to represent the usage of them in bitset.
4194   std::bitset<TileRegHigh + 1> ArgValues;
4195   for (int ArgNum : ArgNums) {
4196     Expr *Arg = TheCall->getArg(ArgNum);
4197     if (Arg->isTypeDependent() || Arg->isValueDependent())
4198       continue;
4199 
4200     llvm::APSInt Result;
4201     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
4202       return true;
4203     int ArgExtValue = Result.getExtValue();
4204     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
4205            "Incorrect tile register num.");
4206     if (ArgValues.test(ArgExtValue))
4207       return Diag(TheCall->getBeginLoc(),
4208                   diag::err_x86_builtin_tile_arg_duplicate)
4209              << TheCall->getArg(ArgNum)->getSourceRange();
4210     ArgValues.set(ArgExtValue);
4211   }
4212   return false;
4213 }
4214 
4215 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
4216                                                 ArrayRef<int> ArgNums) {
4217   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
4218          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
4219 }
4220 
4221 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
4222   switch (BuiltinID) {
4223   default:
4224     return false;
4225   case X86::BI__builtin_ia32_tileloadd64:
4226   case X86::BI__builtin_ia32_tileloaddt164:
4227   case X86::BI__builtin_ia32_tilestored64:
4228   case X86::BI__builtin_ia32_tilezero:
4229     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
4230   case X86::BI__builtin_ia32_tdpbssd:
4231   case X86::BI__builtin_ia32_tdpbsud:
4232   case X86::BI__builtin_ia32_tdpbusd:
4233   case X86::BI__builtin_ia32_tdpbuud:
4234   case X86::BI__builtin_ia32_tdpbf16ps:
4235     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
4236   }
4237 }
4238 static bool isX86_32Builtin(unsigned BuiltinID) {
4239   // These builtins only work on x86-32 targets.
4240   switch (BuiltinID) {
4241   case X86::BI__builtin_ia32_readeflags_u32:
4242   case X86::BI__builtin_ia32_writeeflags_u32:
4243     return true;
4244   }
4245 
4246   return false;
4247 }
4248 
4249 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
4250                                        CallExpr *TheCall) {
4251   if (BuiltinID == X86::BI__builtin_cpu_supports)
4252     return SemaBuiltinCpuSupports(*this, TI, TheCall);
4253 
4254   if (BuiltinID == X86::BI__builtin_cpu_is)
4255     return SemaBuiltinCpuIs(*this, TI, TheCall);
4256 
4257   // Check for 32-bit only builtins on a 64-bit target.
4258   const llvm::Triple &TT = TI.getTriple();
4259   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
4260     return Diag(TheCall->getCallee()->getBeginLoc(),
4261                 diag::err_32_bit_builtin_64_bit_tgt);
4262 
4263   // If the intrinsic has rounding or SAE make sure its valid.
4264   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
4265     return true;
4266 
4267   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
4268   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
4269     return true;
4270 
4271   // If the intrinsic has a tile arguments, make sure they are valid.
4272   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
4273     return true;
4274 
4275   // For intrinsics which take an immediate value as part of the instruction,
4276   // range check them here.
4277   int i = 0, l = 0, u = 0;
4278   switch (BuiltinID) {
4279   default:
4280     return false;
4281   case X86::BI__builtin_ia32_vec_ext_v2si:
4282   case X86::BI__builtin_ia32_vec_ext_v2di:
4283   case X86::BI__builtin_ia32_vextractf128_pd256:
4284   case X86::BI__builtin_ia32_vextractf128_ps256:
4285   case X86::BI__builtin_ia32_vextractf128_si256:
4286   case X86::BI__builtin_ia32_extract128i256:
4287   case X86::BI__builtin_ia32_extractf64x4_mask:
4288   case X86::BI__builtin_ia32_extracti64x4_mask:
4289   case X86::BI__builtin_ia32_extractf32x8_mask:
4290   case X86::BI__builtin_ia32_extracti32x8_mask:
4291   case X86::BI__builtin_ia32_extractf64x2_256_mask:
4292   case X86::BI__builtin_ia32_extracti64x2_256_mask:
4293   case X86::BI__builtin_ia32_extractf32x4_256_mask:
4294   case X86::BI__builtin_ia32_extracti32x4_256_mask:
4295     i = 1; l = 0; u = 1;
4296     break;
4297   case X86::BI__builtin_ia32_vec_set_v2di:
4298   case X86::BI__builtin_ia32_vinsertf128_pd256:
4299   case X86::BI__builtin_ia32_vinsertf128_ps256:
4300   case X86::BI__builtin_ia32_vinsertf128_si256:
4301   case X86::BI__builtin_ia32_insert128i256:
4302   case X86::BI__builtin_ia32_insertf32x8:
4303   case X86::BI__builtin_ia32_inserti32x8:
4304   case X86::BI__builtin_ia32_insertf64x4:
4305   case X86::BI__builtin_ia32_inserti64x4:
4306   case X86::BI__builtin_ia32_insertf64x2_256:
4307   case X86::BI__builtin_ia32_inserti64x2_256:
4308   case X86::BI__builtin_ia32_insertf32x4_256:
4309   case X86::BI__builtin_ia32_inserti32x4_256:
4310     i = 2; l = 0; u = 1;
4311     break;
4312   case X86::BI__builtin_ia32_vpermilpd:
4313   case X86::BI__builtin_ia32_vec_ext_v4hi:
4314   case X86::BI__builtin_ia32_vec_ext_v4si:
4315   case X86::BI__builtin_ia32_vec_ext_v4sf:
4316   case X86::BI__builtin_ia32_vec_ext_v4di:
4317   case X86::BI__builtin_ia32_extractf32x4_mask:
4318   case X86::BI__builtin_ia32_extracti32x4_mask:
4319   case X86::BI__builtin_ia32_extractf64x2_512_mask:
4320   case X86::BI__builtin_ia32_extracti64x2_512_mask:
4321     i = 1; l = 0; u = 3;
4322     break;
4323   case X86::BI_mm_prefetch:
4324   case X86::BI__builtin_ia32_vec_ext_v8hi:
4325   case X86::BI__builtin_ia32_vec_ext_v8si:
4326     i = 1; l = 0; u = 7;
4327     break;
4328   case X86::BI__builtin_ia32_sha1rnds4:
4329   case X86::BI__builtin_ia32_blendpd:
4330   case X86::BI__builtin_ia32_shufpd:
4331   case X86::BI__builtin_ia32_vec_set_v4hi:
4332   case X86::BI__builtin_ia32_vec_set_v4si:
4333   case X86::BI__builtin_ia32_vec_set_v4di:
4334   case X86::BI__builtin_ia32_shuf_f32x4_256:
4335   case X86::BI__builtin_ia32_shuf_f64x2_256:
4336   case X86::BI__builtin_ia32_shuf_i32x4_256:
4337   case X86::BI__builtin_ia32_shuf_i64x2_256:
4338   case X86::BI__builtin_ia32_insertf64x2_512:
4339   case X86::BI__builtin_ia32_inserti64x2_512:
4340   case X86::BI__builtin_ia32_insertf32x4:
4341   case X86::BI__builtin_ia32_inserti32x4:
4342     i = 2; l = 0; u = 3;
4343     break;
4344   case X86::BI__builtin_ia32_vpermil2pd:
4345   case X86::BI__builtin_ia32_vpermil2pd256:
4346   case X86::BI__builtin_ia32_vpermil2ps:
4347   case X86::BI__builtin_ia32_vpermil2ps256:
4348     i = 3; l = 0; u = 3;
4349     break;
4350   case X86::BI__builtin_ia32_cmpb128_mask:
4351   case X86::BI__builtin_ia32_cmpw128_mask:
4352   case X86::BI__builtin_ia32_cmpd128_mask:
4353   case X86::BI__builtin_ia32_cmpq128_mask:
4354   case X86::BI__builtin_ia32_cmpb256_mask:
4355   case X86::BI__builtin_ia32_cmpw256_mask:
4356   case X86::BI__builtin_ia32_cmpd256_mask:
4357   case X86::BI__builtin_ia32_cmpq256_mask:
4358   case X86::BI__builtin_ia32_cmpb512_mask:
4359   case X86::BI__builtin_ia32_cmpw512_mask:
4360   case X86::BI__builtin_ia32_cmpd512_mask:
4361   case X86::BI__builtin_ia32_cmpq512_mask:
4362   case X86::BI__builtin_ia32_ucmpb128_mask:
4363   case X86::BI__builtin_ia32_ucmpw128_mask:
4364   case X86::BI__builtin_ia32_ucmpd128_mask:
4365   case X86::BI__builtin_ia32_ucmpq128_mask:
4366   case X86::BI__builtin_ia32_ucmpb256_mask:
4367   case X86::BI__builtin_ia32_ucmpw256_mask:
4368   case X86::BI__builtin_ia32_ucmpd256_mask:
4369   case X86::BI__builtin_ia32_ucmpq256_mask:
4370   case X86::BI__builtin_ia32_ucmpb512_mask:
4371   case X86::BI__builtin_ia32_ucmpw512_mask:
4372   case X86::BI__builtin_ia32_ucmpd512_mask:
4373   case X86::BI__builtin_ia32_ucmpq512_mask:
4374   case X86::BI__builtin_ia32_vpcomub:
4375   case X86::BI__builtin_ia32_vpcomuw:
4376   case X86::BI__builtin_ia32_vpcomud:
4377   case X86::BI__builtin_ia32_vpcomuq:
4378   case X86::BI__builtin_ia32_vpcomb:
4379   case X86::BI__builtin_ia32_vpcomw:
4380   case X86::BI__builtin_ia32_vpcomd:
4381   case X86::BI__builtin_ia32_vpcomq:
4382   case X86::BI__builtin_ia32_vec_set_v8hi:
4383   case X86::BI__builtin_ia32_vec_set_v8si:
4384     i = 2; l = 0; u = 7;
4385     break;
4386   case X86::BI__builtin_ia32_vpermilpd256:
4387   case X86::BI__builtin_ia32_roundps:
4388   case X86::BI__builtin_ia32_roundpd:
4389   case X86::BI__builtin_ia32_roundps256:
4390   case X86::BI__builtin_ia32_roundpd256:
4391   case X86::BI__builtin_ia32_getmantpd128_mask:
4392   case X86::BI__builtin_ia32_getmantpd256_mask:
4393   case X86::BI__builtin_ia32_getmantps128_mask:
4394   case X86::BI__builtin_ia32_getmantps256_mask:
4395   case X86::BI__builtin_ia32_getmantpd512_mask:
4396   case X86::BI__builtin_ia32_getmantps512_mask:
4397   case X86::BI__builtin_ia32_getmantph128_mask:
4398   case X86::BI__builtin_ia32_getmantph256_mask:
4399   case X86::BI__builtin_ia32_getmantph512_mask:
4400   case X86::BI__builtin_ia32_vec_ext_v16qi:
4401   case X86::BI__builtin_ia32_vec_ext_v16hi:
4402     i = 1; l = 0; u = 15;
4403     break;
4404   case X86::BI__builtin_ia32_pblendd128:
4405   case X86::BI__builtin_ia32_blendps:
4406   case X86::BI__builtin_ia32_blendpd256:
4407   case X86::BI__builtin_ia32_shufpd256:
4408   case X86::BI__builtin_ia32_roundss:
4409   case X86::BI__builtin_ia32_roundsd:
4410   case X86::BI__builtin_ia32_rangepd128_mask:
4411   case X86::BI__builtin_ia32_rangepd256_mask:
4412   case X86::BI__builtin_ia32_rangepd512_mask:
4413   case X86::BI__builtin_ia32_rangeps128_mask:
4414   case X86::BI__builtin_ia32_rangeps256_mask:
4415   case X86::BI__builtin_ia32_rangeps512_mask:
4416   case X86::BI__builtin_ia32_getmantsd_round_mask:
4417   case X86::BI__builtin_ia32_getmantss_round_mask:
4418   case X86::BI__builtin_ia32_getmantsh_round_mask:
4419   case X86::BI__builtin_ia32_vec_set_v16qi:
4420   case X86::BI__builtin_ia32_vec_set_v16hi:
4421     i = 2; l = 0; u = 15;
4422     break;
4423   case X86::BI__builtin_ia32_vec_ext_v32qi:
4424     i = 1; l = 0; u = 31;
4425     break;
4426   case X86::BI__builtin_ia32_cmpps:
4427   case X86::BI__builtin_ia32_cmpss:
4428   case X86::BI__builtin_ia32_cmppd:
4429   case X86::BI__builtin_ia32_cmpsd:
4430   case X86::BI__builtin_ia32_cmpps256:
4431   case X86::BI__builtin_ia32_cmppd256:
4432   case X86::BI__builtin_ia32_cmpps128_mask:
4433   case X86::BI__builtin_ia32_cmppd128_mask:
4434   case X86::BI__builtin_ia32_cmpps256_mask:
4435   case X86::BI__builtin_ia32_cmppd256_mask:
4436   case X86::BI__builtin_ia32_cmpps512_mask:
4437   case X86::BI__builtin_ia32_cmppd512_mask:
4438   case X86::BI__builtin_ia32_cmpsd_mask:
4439   case X86::BI__builtin_ia32_cmpss_mask:
4440   case X86::BI__builtin_ia32_vec_set_v32qi:
4441     i = 2; l = 0; u = 31;
4442     break;
4443   case X86::BI__builtin_ia32_permdf256:
4444   case X86::BI__builtin_ia32_permdi256:
4445   case X86::BI__builtin_ia32_permdf512:
4446   case X86::BI__builtin_ia32_permdi512:
4447   case X86::BI__builtin_ia32_vpermilps:
4448   case X86::BI__builtin_ia32_vpermilps256:
4449   case X86::BI__builtin_ia32_vpermilpd512:
4450   case X86::BI__builtin_ia32_vpermilps512:
4451   case X86::BI__builtin_ia32_pshufd:
4452   case X86::BI__builtin_ia32_pshufd256:
4453   case X86::BI__builtin_ia32_pshufd512:
4454   case X86::BI__builtin_ia32_pshufhw:
4455   case X86::BI__builtin_ia32_pshufhw256:
4456   case X86::BI__builtin_ia32_pshufhw512:
4457   case X86::BI__builtin_ia32_pshuflw:
4458   case X86::BI__builtin_ia32_pshuflw256:
4459   case X86::BI__builtin_ia32_pshuflw512:
4460   case X86::BI__builtin_ia32_vcvtps2ph:
4461   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4462   case X86::BI__builtin_ia32_vcvtps2ph256:
4463   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4464   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4465   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4466   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4467   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4468   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4469   case X86::BI__builtin_ia32_rndscaleps_mask:
4470   case X86::BI__builtin_ia32_rndscalepd_mask:
4471   case X86::BI__builtin_ia32_rndscaleph_mask:
4472   case X86::BI__builtin_ia32_reducepd128_mask:
4473   case X86::BI__builtin_ia32_reducepd256_mask:
4474   case X86::BI__builtin_ia32_reducepd512_mask:
4475   case X86::BI__builtin_ia32_reduceps128_mask:
4476   case X86::BI__builtin_ia32_reduceps256_mask:
4477   case X86::BI__builtin_ia32_reduceps512_mask:
4478   case X86::BI__builtin_ia32_reduceph128_mask:
4479   case X86::BI__builtin_ia32_reduceph256_mask:
4480   case X86::BI__builtin_ia32_reduceph512_mask:
4481   case X86::BI__builtin_ia32_prold512:
4482   case X86::BI__builtin_ia32_prolq512:
4483   case X86::BI__builtin_ia32_prold128:
4484   case X86::BI__builtin_ia32_prold256:
4485   case X86::BI__builtin_ia32_prolq128:
4486   case X86::BI__builtin_ia32_prolq256:
4487   case X86::BI__builtin_ia32_prord512:
4488   case X86::BI__builtin_ia32_prorq512:
4489   case X86::BI__builtin_ia32_prord128:
4490   case X86::BI__builtin_ia32_prord256:
4491   case X86::BI__builtin_ia32_prorq128:
4492   case X86::BI__builtin_ia32_prorq256:
4493   case X86::BI__builtin_ia32_fpclasspd128_mask:
4494   case X86::BI__builtin_ia32_fpclasspd256_mask:
4495   case X86::BI__builtin_ia32_fpclassps128_mask:
4496   case X86::BI__builtin_ia32_fpclassps256_mask:
4497   case X86::BI__builtin_ia32_fpclassps512_mask:
4498   case X86::BI__builtin_ia32_fpclasspd512_mask:
4499   case X86::BI__builtin_ia32_fpclassph128_mask:
4500   case X86::BI__builtin_ia32_fpclassph256_mask:
4501   case X86::BI__builtin_ia32_fpclassph512_mask:
4502   case X86::BI__builtin_ia32_fpclasssd_mask:
4503   case X86::BI__builtin_ia32_fpclassss_mask:
4504   case X86::BI__builtin_ia32_fpclasssh_mask:
4505   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4506   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4507   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4508   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4509   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4510   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4511   case X86::BI__builtin_ia32_kshiftliqi:
4512   case X86::BI__builtin_ia32_kshiftlihi:
4513   case X86::BI__builtin_ia32_kshiftlisi:
4514   case X86::BI__builtin_ia32_kshiftlidi:
4515   case X86::BI__builtin_ia32_kshiftriqi:
4516   case X86::BI__builtin_ia32_kshiftrihi:
4517   case X86::BI__builtin_ia32_kshiftrisi:
4518   case X86::BI__builtin_ia32_kshiftridi:
4519     i = 1; l = 0; u = 255;
4520     break;
4521   case X86::BI__builtin_ia32_vperm2f128_pd256:
4522   case X86::BI__builtin_ia32_vperm2f128_ps256:
4523   case X86::BI__builtin_ia32_vperm2f128_si256:
4524   case X86::BI__builtin_ia32_permti256:
4525   case X86::BI__builtin_ia32_pblendw128:
4526   case X86::BI__builtin_ia32_pblendw256:
4527   case X86::BI__builtin_ia32_blendps256:
4528   case X86::BI__builtin_ia32_pblendd256:
4529   case X86::BI__builtin_ia32_palignr128:
4530   case X86::BI__builtin_ia32_palignr256:
4531   case X86::BI__builtin_ia32_palignr512:
4532   case X86::BI__builtin_ia32_alignq512:
4533   case X86::BI__builtin_ia32_alignd512:
4534   case X86::BI__builtin_ia32_alignd128:
4535   case X86::BI__builtin_ia32_alignd256:
4536   case X86::BI__builtin_ia32_alignq128:
4537   case X86::BI__builtin_ia32_alignq256:
4538   case X86::BI__builtin_ia32_vcomisd:
4539   case X86::BI__builtin_ia32_vcomiss:
4540   case X86::BI__builtin_ia32_shuf_f32x4:
4541   case X86::BI__builtin_ia32_shuf_f64x2:
4542   case X86::BI__builtin_ia32_shuf_i32x4:
4543   case X86::BI__builtin_ia32_shuf_i64x2:
4544   case X86::BI__builtin_ia32_shufpd512:
4545   case X86::BI__builtin_ia32_shufps:
4546   case X86::BI__builtin_ia32_shufps256:
4547   case X86::BI__builtin_ia32_shufps512:
4548   case X86::BI__builtin_ia32_dbpsadbw128:
4549   case X86::BI__builtin_ia32_dbpsadbw256:
4550   case X86::BI__builtin_ia32_dbpsadbw512:
4551   case X86::BI__builtin_ia32_vpshldd128:
4552   case X86::BI__builtin_ia32_vpshldd256:
4553   case X86::BI__builtin_ia32_vpshldd512:
4554   case X86::BI__builtin_ia32_vpshldq128:
4555   case X86::BI__builtin_ia32_vpshldq256:
4556   case X86::BI__builtin_ia32_vpshldq512:
4557   case X86::BI__builtin_ia32_vpshldw128:
4558   case X86::BI__builtin_ia32_vpshldw256:
4559   case X86::BI__builtin_ia32_vpshldw512:
4560   case X86::BI__builtin_ia32_vpshrdd128:
4561   case X86::BI__builtin_ia32_vpshrdd256:
4562   case X86::BI__builtin_ia32_vpshrdd512:
4563   case X86::BI__builtin_ia32_vpshrdq128:
4564   case X86::BI__builtin_ia32_vpshrdq256:
4565   case X86::BI__builtin_ia32_vpshrdq512:
4566   case X86::BI__builtin_ia32_vpshrdw128:
4567   case X86::BI__builtin_ia32_vpshrdw256:
4568   case X86::BI__builtin_ia32_vpshrdw512:
4569     i = 2; l = 0; u = 255;
4570     break;
4571   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4572   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4573   case X86::BI__builtin_ia32_fixupimmps512_mask:
4574   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4575   case X86::BI__builtin_ia32_fixupimmsd_mask:
4576   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4577   case X86::BI__builtin_ia32_fixupimmss_mask:
4578   case X86::BI__builtin_ia32_fixupimmss_maskz:
4579   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4580   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4581   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4582   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4583   case X86::BI__builtin_ia32_fixupimmps128_mask:
4584   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4585   case X86::BI__builtin_ia32_fixupimmps256_mask:
4586   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4587   case X86::BI__builtin_ia32_pternlogd512_mask:
4588   case X86::BI__builtin_ia32_pternlogd512_maskz:
4589   case X86::BI__builtin_ia32_pternlogq512_mask:
4590   case X86::BI__builtin_ia32_pternlogq512_maskz:
4591   case X86::BI__builtin_ia32_pternlogd128_mask:
4592   case X86::BI__builtin_ia32_pternlogd128_maskz:
4593   case X86::BI__builtin_ia32_pternlogd256_mask:
4594   case X86::BI__builtin_ia32_pternlogd256_maskz:
4595   case X86::BI__builtin_ia32_pternlogq128_mask:
4596   case X86::BI__builtin_ia32_pternlogq128_maskz:
4597   case X86::BI__builtin_ia32_pternlogq256_mask:
4598   case X86::BI__builtin_ia32_pternlogq256_maskz:
4599     i = 3; l = 0; u = 255;
4600     break;
4601   case X86::BI__builtin_ia32_gatherpfdpd:
4602   case X86::BI__builtin_ia32_gatherpfdps:
4603   case X86::BI__builtin_ia32_gatherpfqpd:
4604   case X86::BI__builtin_ia32_gatherpfqps:
4605   case X86::BI__builtin_ia32_scatterpfdpd:
4606   case X86::BI__builtin_ia32_scatterpfdps:
4607   case X86::BI__builtin_ia32_scatterpfqpd:
4608   case X86::BI__builtin_ia32_scatterpfqps:
4609     i = 4; l = 2; u = 3;
4610     break;
4611   case X86::BI__builtin_ia32_reducesd_mask:
4612   case X86::BI__builtin_ia32_reducess_mask:
4613   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4614   case X86::BI__builtin_ia32_rndscaless_round_mask:
4615   case X86::BI__builtin_ia32_rndscalesh_round_mask:
4616   case X86::BI__builtin_ia32_reducesh_mask:
4617     i = 4; l = 0; u = 255;
4618     break;
4619   }
4620 
4621   // Note that we don't force a hard error on the range check here, allowing
4622   // template-generated or macro-generated dead code to potentially have out-of-
4623   // range values. These need to code generate, but don't need to necessarily
4624   // make any sense. We use a warning that defaults to an error.
4625   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4626 }
4627 
4628 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4629 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4630 /// Returns true when the format fits the function and the FormatStringInfo has
4631 /// been populated.
4632 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4633                                FormatStringInfo *FSI) {
4634   FSI->HasVAListArg = Format->getFirstArg() == 0;
4635   FSI->FormatIdx = Format->getFormatIdx() - 1;
4636   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4637 
4638   // The way the format attribute works in GCC, the implicit this argument
4639   // of member functions is counted. However, it doesn't appear in our own
4640   // lists, so decrement format_idx in that case.
4641   if (IsCXXMember) {
4642     if(FSI->FormatIdx == 0)
4643       return false;
4644     --FSI->FormatIdx;
4645     if (FSI->FirstDataArg != 0)
4646       --FSI->FirstDataArg;
4647   }
4648   return true;
4649 }
4650 
4651 /// Checks if a the given expression evaluates to null.
4652 ///
4653 /// Returns true if the value evaluates to null.
4654 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4655   // If the expression has non-null type, it doesn't evaluate to null.
4656   if (auto nullability
4657         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4658     if (*nullability == NullabilityKind::NonNull)
4659       return false;
4660   }
4661 
4662   // As a special case, transparent unions initialized with zero are
4663   // considered null for the purposes of the nonnull attribute.
4664   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4665     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4666       if (const CompoundLiteralExpr *CLE =
4667           dyn_cast<CompoundLiteralExpr>(Expr))
4668         if (const InitListExpr *ILE =
4669             dyn_cast<InitListExpr>(CLE->getInitializer()))
4670           Expr = ILE->getInit(0);
4671   }
4672 
4673   bool Result;
4674   return (!Expr->isValueDependent() &&
4675           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4676           !Result);
4677 }
4678 
4679 static void CheckNonNullArgument(Sema &S,
4680                                  const Expr *ArgExpr,
4681                                  SourceLocation CallSiteLoc) {
4682   if (CheckNonNullExpr(S, ArgExpr))
4683     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4684                           S.PDiag(diag::warn_null_arg)
4685                               << ArgExpr->getSourceRange());
4686 }
4687 
4688 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4689   FormatStringInfo FSI;
4690   if ((GetFormatStringType(Format) == FST_NSString) &&
4691       getFormatStringInfo(Format, false, &FSI)) {
4692     Idx = FSI.FormatIdx;
4693     return true;
4694   }
4695   return false;
4696 }
4697 
4698 /// Diagnose use of %s directive in an NSString which is being passed
4699 /// as formatting string to formatting method.
4700 static void
4701 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4702                                         const NamedDecl *FDecl,
4703                                         Expr **Args,
4704                                         unsigned NumArgs) {
4705   unsigned Idx = 0;
4706   bool Format = false;
4707   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4708   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4709     Idx = 2;
4710     Format = true;
4711   }
4712   else
4713     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4714       if (S.GetFormatNSStringIdx(I, Idx)) {
4715         Format = true;
4716         break;
4717       }
4718     }
4719   if (!Format || NumArgs <= Idx)
4720     return;
4721   const Expr *FormatExpr = Args[Idx];
4722   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4723     FormatExpr = CSCE->getSubExpr();
4724   const StringLiteral *FormatString;
4725   if (const ObjCStringLiteral *OSL =
4726       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4727     FormatString = OSL->getString();
4728   else
4729     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4730   if (!FormatString)
4731     return;
4732   if (S.FormatStringHasSArg(FormatString)) {
4733     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4734       << "%s" << 1 << 1;
4735     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4736       << FDecl->getDeclName();
4737   }
4738 }
4739 
4740 /// Determine whether the given type has a non-null nullability annotation.
4741 static bool isNonNullType(ASTContext &ctx, QualType type) {
4742   if (auto nullability = type->getNullability(ctx))
4743     return *nullability == NullabilityKind::NonNull;
4744 
4745   return false;
4746 }
4747 
4748 static void CheckNonNullArguments(Sema &S,
4749                                   const NamedDecl *FDecl,
4750                                   const FunctionProtoType *Proto,
4751                                   ArrayRef<const Expr *> Args,
4752                                   SourceLocation CallSiteLoc) {
4753   assert((FDecl || Proto) && "Need a function declaration or prototype");
4754 
4755   // Already checked by by constant evaluator.
4756   if (S.isConstantEvaluated())
4757     return;
4758   // Check the attributes attached to the method/function itself.
4759   llvm::SmallBitVector NonNullArgs;
4760   if (FDecl) {
4761     // Handle the nonnull attribute on the function/method declaration itself.
4762     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4763       if (!NonNull->args_size()) {
4764         // Easy case: all pointer arguments are nonnull.
4765         for (const auto *Arg : Args)
4766           if (S.isValidPointerAttrType(Arg->getType()))
4767             CheckNonNullArgument(S, Arg, CallSiteLoc);
4768         return;
4769       }
4770 
4771       for (const ParamIdx &Idx : NonNull->args()) {
4772         unsigned IdxAST = Idx.getASTIndex();
4773         if (IdxAST >= Args.size())
4774           continue;
4775         if (NonNullArgs.empty())
4776           NonNullArgs.resize(Args.size());
4777         NonNullArgs.set(IdxAST);
4778       }
4779     }
4780   }
4781 
4782   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4783     // Handle the nonnull attribute on the parameters of the
4784     // function/method.
4785     ArrayRef<ParmVarDecl*> parms;
4786     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4787       parms = FD->parameters();
4788     else
4789       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4790 
4791     unsigned ParamIndex = 0;
4792     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4793          I != E; ++I, ++ParamIndex) {
4794       const ParmVarDecl *PVD = *I;
4795       if (PVD->hasAttr<NonNullAttr>() ||
4796           isNonNullType(S.Context, PVD->getType())) {
4797         if (NonNullArgs.empty())
4798           NonNullArgs.resize(Args.size());
4799 
4800         NonNullArgs.set(ParamIndex);
4801       }
4802     }
4803   } else {
4804     // If we have a non-function, non-method declaration but no
4805     // function prototype, try to dig out the function prototype.
4806     if (!Proto) {
4807       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4808         QualType type = VD->getType().getNonReferenceType();
4809         if (auto pointerType = type->getAs<PointerType>())
4810           type = pointerType->getPointeeType();
4811         else if (auto blockType = type->getAs<BlockPointerType>())
4812           type = blockType->getPointeeType();
4813         // FIXME: data member pointers?
4814 
4815         // Dig out the function prototype, if there is one.
4816         Proto = type->getAs<FunctionProtoType>();
4817       }
4818     }
4819 
4820     // Fill in non-null argument information from the nullability
4821     // information on the parameter types (if we have them).
4822     if (Proto) {
4823       unsigned Index = 0;
4824       for (auto paramType : Proto->getParamTypes()) {
4825         if (isNonNullType(S.Context, paramType)) {
4826           if (NonNullArgs.empty())
4827             NonNullArgs.resize(Args.size());
4828 
4829           NonNullArgs.set(Index);
4830         }
4831 
4832         ++Index;
4833       }
4834     }
4835   }
4836 
4837   // Check for non-null arguments.
4838   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4839        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4840     if (NonNullArgs[ArgIndex])
4841       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4842   }
4843 }
4844 
4845 /// Warn if a pointer or reference argument passed to a function points to an
4846 /// object that is less aligned than the parameter. This can happen when
4847 /// creating a typedef with a lower alignment than the original type and then
4848 /// calling functions defined in terms of the original type.
4849 void Sema::CheckArgAlignment(SourceLocation Loc, NamedDecl *FDecl,
4850                              StringRef ParamName, QualType ArgTy,
4851                              QualType ParamTy) {
4852 
4853   // If a function accepts a pointer or reference type
4854   if (!ParamTy->isPointerType() && !ParamTy->isReferenceType())
4855     return;
4856 
4857   // If the parameter is a pointer type, get the pointee type for the
4858   // argument too. If the parameter is a reference type, don't try to get
4859   // the pointee type for the argument.
4860   if (ParamTy->isPointerType())
4861     ArgTy = ArgTy->getPointeeType();
4862 
4863   // Remove reference or pointer
4864   ParamTy = ParamTy->getPointeeType();
4865 
4866   // Find expected alignment, and the actual alignment of the passed object.
4867   // getTypeAlignInChars requires complete types
4868   if (ArgTy.isNull() || ParamTy->isIncompleteType() ||
4869       ArgTy->isIncompleteType() || ParamTy->isUndeducedType() ||
4870       ArgTy->isUndeducedType())
4871     return;
4872 
4873   CharUnits ParamAlign = Context.getTypeAlignInChars(ParamTy);
4874   CharUnits ArgAlign = Context.getTypeAlignInChars(ArgTy);
4875 
4876   // If the argument is less aligned than the parameter, there is a
4877   // potential alignment issue.
4878   if (ArgAlign < ParamAlign)
4879     Diag(Loc, diag::warn_param_mismatched_alignment)
4880         << (int)ArgAlign.getQuantity() << (int)ParamAlign.getQuantity()
4881         << ParamName << FDecl;
4882 }
4883 
4884 /// Handles the checks for format strings, non-POD arguments to vararg
4885 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4886 /// attributes.
4887 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4888                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4889                      bool IsMemberFunction, SourceLocation Loc,
4890                      SourceRange Range, VariadicCallType CallType) {
4891   // FIXME: We should check as much as we can in the template definition.
4892   if (CurContext->isDependentContext())
4893     return;
4894 
4895   // Printf and scanf checking.
4896   llvm::SmallBitVector CheckedVarArgs;
4897   if (FDecl) {
4898     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4899       // Only create vector if there are format attributes.
4900       CheckedVarArgs.resize(Args.size());
4901 
4902       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4903                            CheckedVarArgs);
4904     }
4905   }
4906 
4907   // Refuse POD arguments that weren't caught by the format string
4908   // checks above.
4909   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4910   if (CallType != VariadicDoesNotApply &&
4911       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4912     unsigned NumParams = Proto ? Proto->getNumParams()
4913                        : FDecl && isa<FunctionDecl>(FDecl)
4914                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4915                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4916                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4917                        : 0;
4918 
4919     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4920       // Args[ArgIdx] can be null in malformed code.
4921       if (const Expr *Arg = Args[ArgIdx]) {
4922         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4923           checkVariadicArgument(Arg, CallType);
4924       }
4925     }
4926   }
4927 
4928   if (FDecl || Proto) {
4929     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4930 
4931     // Type safety checking.
4932     if (FDecl) {
4933       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4934         CheckArgumentWithTypeTag(I, Args, Loc);
4935     }
4936   }
4937 
4938   // Check that passed arguments match the alignment of original arguments.
4939   // Try to get the missing prototype from the declaration.
4940   if (!Proto && FDecl) {
4941     const auto *FT = FDecl->getFunctionType();
4942     if (isa_and_nonnull<FunctionProtoType>(FT))
4943       Proto = cast<FunctionProtoType>(FDecl->getFunctionType());
4944   }
4945   if (Proto) {
4946     // For variadic functions, we may have more args than parameters.
4947     // For some K&R functions, we may have less args than parameters.
4948     const auto N = std::min<unsigned>(Proto->getNumParams(), Args.size());
4949     for (unsigned ArgIdx = 0; ArgIdx < N; ++ArgIdx) {
4950       // Args[ArgIdx] can be null in malformed code.
4951       if (const Expr *Arg = Args[ArgIdx]) {
4952         if (Arg->containsErrors())
4953           continue;
4954 
4955         QualType ParamTy = Proto->getParamType(ArgIdx);
4956         QualType ArgTy = Arg->getType();
4957         CheckArgAlignment(Arg->getExprLoc(), FDecl, std::to_string(ArgIdx + 1),
4958                           ArgTy, ParamTy);
4959       }
4960     }
4961   }
4962 
4963   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4964     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4965     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4966     if (!Arg->isValueDependent()) {
4967       Expr::EvalResult Align;
4968       if (Arg->EvaluateAsInt(Align, Context)) {
4969         const llvm::APSInt &I = Align.Val.getInt();
4970         if (!I.isPowerOf2())
4971           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4972               << Arg->getSourceRange();
4973 
4974         if (I > Sema::MaximumAlignment)
4975           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4976               << Arg->getSourceRange() << Sema::MaximumAlignment;
4977       }
4978     }
4979   }
4980 
4981   if (FD)
4982     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4983 }
4984 
4985 /// CheckConstructorCall - Check a constructor call for correctness and safety
4986 /// properties not enforced by the C type system.
4987 void Sema::CheckConstructorCall(FunctionDecl *FDecl, QualType ThisType,
4988                                 ArrayRef<const Expr *> Args,
4989                                 const FunctionProtoType *Proto,
4990                                 SourceLocation Loc) {
4991   VariadicCallType CallType =
4992       Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4993 
4994   auto *Ctor = cast<CXXConstructorDecl>(FDecl);
4995   CheckArgAlignment(Loc, FDecl, "'this'", Context.getPointerType(ThisType),
4996                     Context.getPointerType(Ctor->getThisObjectType()));
4997 
4998   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4999             Loc, SourceRange(), CallType);
5000 }
5001 
5002 /// CheckFunctionCall - Check a direct function call for various correctness
5003 /// and safety properties not strictly enforced by the C type system.
5004 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
5005                              const FunctionProtoType *Proto) {
5006   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
5007                               isa<CXXMethodDecl>(FDecl);
5008   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
5009                           IsMemberOperatorCall;
5010   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
5011                                                   TheCall->getCallee());
5012   Expr** Args = TheCall->getArgs();
5013   unsigned NumArgs = TheCall->getNumArgs();
5014 
5015   Expr *ImplicitThis = nullptr;
5016   if (IsMemberOperatorCall) {
5017     // If this is a call to a member operator, hide the first argument
5018     // from checkCall.
5019     // FIXME: Our choice of AST representation here is less than ideal.
5020     ImplicitThis = Args[0];
5021     ++Args;
5022     --NumArgs;
5023   } else if (IsMemberFunction)
5024     ImplicitThis =
5025         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
5026 
5027   if (ImplicitThis) {
5028     // ImplicitThis may or may not be a pointer, depending on whether . or -> is
5029     // used.
5030     QualType ThisType = ImplicitThis->getType();
5031     if (!ThisType->isPointerType()) {
5032       assert(!ThisType->isReferenceType());
5033       ThisType = Context.getPointerType(ThisType);
5034     }
5035 
5036     QualType ThisTypeFromDecl =
5037         Context.getPointerType(cast<CXXMethodDecl>(FDecl)->getThisObjectType());
5038 
5039     CheckArgAlignment(TheCall->getRParenLoc(), FDecl, "'this'", ThisType,
5040                       ThisTypeFromDecl);
5041   }
5042 
5043   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
5044             IsMemberFunction, TheCall->getRParenLoc(),
5045             TheCall->getCallee()->getSourceRange(), CallType);
5046 
5047   IdentifierInfo *FnInfo = FDecl->getIdentifier();
5048   // None of the checks below are needed for functions that don't have
5049   // simple names (e.g., C++ conversion functions).
5050   if (!FnInfo)
5051     return false;
5052 
5053   CheckTCBEnforcement(TheCall, FDecl);
5054 
5055   CheckAbsoluteValueFunction(TheCall, FDecl);
5056   CheckMaxUnsignedZero(TheCall, FDecl);
5057 
5058   if (getLangOpts().ObjC)
5059     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
5060 
5061   unsigned CMId = FDecl->getMemoryFunctionKind();
5062 
5063   // Handle memory setting and copying functions.
5064   switch (CMId) {
5065   case 0:
5066     return false;
5067   case Builtin::BIstrlcpy: // fallthrough
5068   case Builtin::BIstrlcat:
5069     CheckStrlcpycatArguments(TheCall, FnInfo);
5070     break;
5071   case Builtin::BIstrncat:
5072     CheckStrncatArguments(TheCall, FnInfo);
5073     break;
5074   case Builtin::BIfree:
5075     CheckFreeArguments(TheCall);
5076     break;
5077   default:
5078     CheckMemaccessArguments(TheCall, CMId, FnInfo);
5079   }
5080 
5081   return false;
5082 }
5083 
5084 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
5085                                ArrayRef<const Expr *> Args) {
5086   VariadicCallType CallType =
5087       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
5088 
5089   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
5090             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
5091             CallType);
5092 
5093   return false;
5094 }
5095 
5096 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
5097                             const FunctionProtoType *Proto) {
5098   QualType Ty;
5099   if (const auto *V = dyn_cast<VarDecl>(NDecl))
5100     Ty = V->getType().getNonReferenceType();
5101   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
5102     Ty = F->getType().getNonReferenceType();
5103   else
5104     return false;
5105 
5106   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
5107       !Ty->isFunctionProtoType())
5108     return false;
5109 
5110   VariadicCallType CallType;
5111   if (!Proto || !Proto->isVariadic()) {
5112     CallType = VariadicDoesNotApply;
5113   } else if (Ty->isBlockPointerType()) {
5114     CallType = VariadicBlock;
5115   } else { // Ty->isFunctionPointerType()
5116     CallType = VariadicFunction;
5117   }
5118 
5119   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
5120             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5121             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5122             TheCall->getCallee()->getSourceRange(), CallType);
5123 
5124   return false;
5125 }
5126 
5127 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
5128 /// such as function pointers returned from functions.
5129 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
5130   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
5131                                                   TheCall->getCallee());
5132   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
5133             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
5134             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
5135             TheCall->getCallee()->getSourceRange(), CallType);
5136 
5137   return false;
5138 }
5139 
5140 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
5141   if (!llvm::isValidAtomicOrderingCABI(Ordering))
5142     return false;
5143 
5144   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
5145   switch (Op) {
5146   case AtomicExpr::AO__c11_atomic_init:
5147   case AtomicExpr::AO__opencl_atomic_init:
5148     llvm_unreachable("There is no ordering argument for an init");
5149 
5150   case AtomicExpr::AO__c11_atomic_load:
5151   case AtomicExpr::AO__opencl_atomic_load:
5152   case AtomicExpr::AO__atomic_load_n:
5153   case AtomicExpr::AO__atomic_load:
5154     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
5155            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5156 
5157   case AtomicExpr::AO__c11_atomic_store:
5158   case AtomicExpr::AO__opencl_atomic_store:
5159   case AtomicExpr::AO__atomic_store:
5160   case AtomicExpr::AO__atomic_store_n:
5161     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
5162            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
5163            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
5164 
5165   default:
5166     return true;
5167   }
5168 }
5169 
5170 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
5171                                          AtomicExpr::AtomicOp Op) {
5172   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
5173   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5174   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
5175   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
5176                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
5177                          Op);
5178 }
5179 
5180 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
5181                                  SourceLocation RParenLoc, MultiExprArg Args,
5182                                  AtomicExpr::AtomicOp Op,
5183                                  AtomicArgumentOrder ArgOrder) {
5184   // All the non-OpenCL operations take one of the following forms.
5185   // The OpenCL operations take the __c11 forms with one extra argument for
5186   // synchronization scope.
5187   enum {
5188     // C    __c11_atomic_init(A *, C)
5189     Init,
5190 
5191     // C    __c11_atomic_load(A *, int)
5192     Load,
5193 
5194     // void __atomic_load(A *, CP, int)
5195     LoadCopy,
5196 
5197     // void __atomic_store(A *, CP, int)
5198     Copy,
5199 
5200     // C    __c11_atomic_add(A *, M, int)
5201     Arithmetic,
5202 
5203     // C    __atomic_exchange_n(A *, CP, int)
5204     Xchg,
5205 
5206     // void __atomic_exchange(A *, C *, CP, int)
5207     GNUXchg,
5208 
5209     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
5210     C11CmpXchg,
5211 
5212     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
5213     GNUCmpXchg
5214   } Form = Init;
5215 
5216   const unsigned NumForm = GNUCmpXchg + 1;
5217   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
5218   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
5219   // where:
5220   //   C is an appropriate type,
5221   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
5222   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
5223   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
5224   //   the int parameters are for orderings.
5225 
5226   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
5227       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
5228       "need to update code for modified forms");
5229   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
5230                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
5231                         AtomicExpr::AO__atomic_load,
5232                 "need to update code for modified C11 atomics");
5233   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
5234                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
5235   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
5236                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
5237                IsOpenCL;
5238   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
5239              Op == AtomicExpr::AO__atomic_store_n ||
5240              Op == AtomicExpr::AO__atomic_exchange_n ||
5241              Op == AtomicExpr::AO__atomic_compare_exchange_n;
5242   bool IsAddSub = false;
5243 
5244   switch (Op) {
5245   case AtomicExpr::AO__c11_atomic_init:
5246   case AtomicExpr::AO__opencl_atomic_init:
5247     Form = Init;
5248     break;
5249 
5250   case AtomicExpr::AO__c11_atomic_load:
5251   case AtomicExpr::AO__opencl_atomic_load:
5252   case AtomicExpr::AO__atomic_load_n:
5253     Form = Load;
5254     break;
5255 
5256   case AtomicExpr::AO__atomic_load:
5257     Form = LoadCopy;
5258     break;
5259 
5260   case AtomicExpr::AO__c11_atomic_store:
5261   case AtomicExpr::AO__opencl_atomic_store:
5262   case AtomicExpr::AO__atomic_store:
5263   case AtomicExpr::AO__atomic_store_n:
5264     Form = Copy;
5265     break;
5266 
5267   case AtomicExpr::AO__c11_atomic_fetch_add:
5268   case AtomicExpr::AO__c11_atomic_fetch_sub:
5269   case AtomicExpr::AO__opencl_atomic_fetch_add:
5270   case AtomicExpr::AO__opencl_atomic_fetch_sub:
5271   case AtomicExpr::AO__atomic_fetch_add:
5272   case AtomicExpr::AO__atomic_fetch_sub:
5273   case AtomicExpr::AO__atomic_add_fetch:
5274   case AtomicExpr::AO__atomic_sub_fetch:
5275     IsAddSub = true;
5276     Form = Arithmetic;
5277     break;
5278   case AtomicExpr::AO__c11_atomic_fetch_and:
5279   case AtomicExpr::AO__c11_atomic_fetch_or:
5280   case AtomicExpr::AO__c11_atomic_fetch_xor:
5281   case AtomicExpr::AO__opencl_atomic_fetch_and:
5282   case AtomicExpr::AO__opencl_atomic_fetch_or:
5283   case AtomicExpr::AO__opencl_atomic_fetch_xor:
5284   case AtomicExpr::AO__atomic_fetch_and:
5285   case AtomicExpr::AO__atomic_fetch_or:
5286   case AtomicExpr::AO__atomic_fetch_xor:
5287   case AtomicExpr::AO__atomic_fetch_nand:
5288   case AtomicExpr::AO__atomic_and_fetch:
5289   case AtomicExpr::AO__atomic_or_fetch:
5290   case AtomicExpr::AO__atomic_xor_fetch:
5291   case AtomicExpr::AO__atomic_nand_fetch:
5292     Form = Arithmetic;
5293     break;
5294   case AtomicExpr::AO__c11_atomic_fetch_min:
5295   case AtomicExpr::AO__c11_atomic_fetch_max:
5296   case AtomicExpr::AO__opencl_atomic_fetch_min:
5297   case AtomicExpr::AO__opencl_atomic_fetch_max:
5298   case AtomicExpr::AO__atomic_min_fetch:
5299   case AtomicExpr::AO__atomic_max_fetch:
5300   case AtomicExpr::AO__atomic_fetch_min:
5301   case AtomicExpr::AO__atomic_fetch_max:
5302     Form = Arithmetic;
5303     break;
5304 
5305   case AtomicExpr::AO__c11_atomic_exchange:
5306   case AtomicExpr::AO__opencl_atomic_exchange:
5307   case AtomicExpr::AO__atomic_exchange_n:
5308     Form = Xchg;
5309     break;
5310 
5311   case AtomicExpr::AO__atomic_exchange:
5312     Form = GNUXchg;
5313     break;
5314 
5315   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
5316   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
5317   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
5318   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
5319     Form = C11CmpXchg;
5320     break;
5321 
5322   case AtomicExpr::AO__atomic_compare_exchange:
5323   case AtomicExpr::AO__atomic_compare_exchange_n:
5324     Form = GNUCmpXchg;
5325     break;
5326   }
5327 
5328   unsigned AdjustedNumArgs = NumArgs[Form];
5329   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
5330     ++AdjustedNumArgs;
5331   // Check we have the right number of arguments.
5332   if (Args.size() < AdjustedNumArgs) {
5333     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
5334         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5335         << ExprRange;
5336     return ExprError();
5337   } else if (Args.size() > AdjustedNumArgs) {
5338     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
5339          diag::err_typecheck_call_too_many_args)
5340         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
5341         << ExprRange;
5342     return ExprError();
5343   }
5344 
5345   // Inspect the first argument of the atomic operation.
5346   Expr *Ptr = Args[0];
5347   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
5348   if (ConvertedPtr.isInvalid())
5349     return ExprError();
5350 
5351   Ptr = ConvertedPtr.get();
5352   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
5353   if (!pointerType) {
5354     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
5355         << Ptr->getType() << Ptr->getSourceRange();
5356     return ExprError();
5357   }
5358 
5359   // For a __c11 builtin, this should be a pointer to an _Atomic type.
5360   QualType AtomTy = pointerType->getPointeeType(); // 'A'
5361   QualType ValType = AtomTy; // 'C'
5362   if (IsC11) {
5363     if (!AtomTy->isAtomicType()) {
5364       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
5365           << Ptr->getType() << Ptr->getSourceRange();
5366       return ExprError();
5367     }
5368     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
5369         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
5370       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
5371           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
5372           << Ptr->getSourceRange();
5373       return ExprError();
5374     }
5375     ValType = AtomTy->castAs<AtomicType>()->getValueType();
5376   } else if (Form != Load && Form != LoadCopy) {
5377     if (ValType.isConstQualified()) {
5378       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
5379           << Ptr->getType() << Ptr->getSourceRange();
5380       return ExprError();
5381     }
5382   }
5383 
5384   // For an arithmetic operation, the implied arithmetic must be well-formed.
5385   if (Form == Arithmetic) {
5386     // gcc does not enforce these rules for GNU atomics, but we do so for
5387     // sanity.
5388     auto IsAllowedValueType = [&](QualType ValType) {
5389       if (ValType->isIntegerType())
5390         return true;
5391       if (ValType->isPointerType())
5392         return true;
5393       if (!ValType->isFloatingType())
5394         return false;
5395       // LLVM Parser does not allow atomicrmw with x86_fp80 type.
5396       if (ValType->isSpecificBuiltinType(BuiltinType::LongDouble) &&
5397           &Context.getTargetInfo().getLongDoubleFormat() ==
5398               &llvm::APFloat::x87DoubleExtended())
5399         return false;
5400       return true;
5401     };
5402     if (IsAddSub && !IsAllowedValueType(ValType)) {
5403       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_ptr_or_fp)
5404           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5405       return ExprError();
5406     }
5407     if (!IsAddSub && !ValType->isIntegerType()) {
5408       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
5409           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5410       return ExprError();
5411     }
5412     if (IsC11 && ValType->isPointerType() &&
5413         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
5414                             diag::err_incomplete_type)) {
5415       return ExprError();
5416     }
5417   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
5418     // For __atomic_*_n operations, the value type must be a scalar integral or
5419     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
5420     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
5421         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
5422     return ExprError();
5423   }
5424 
5425   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
5426       !AtomTy->isScalarType()) {
5427     // For GNU atomics, require a trivially-copyable type. This is not part of
5428     // the GNU atomics specification, but we enforce it for sanity.
5429     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
5430         << Ptr->getType() << Ptr->getSourceRange();
5431     return ExprError();
5432   }
5433 
5434   switch (ValType.getObjCLifetime()) {
5435   case Qualifiers::OCL_None:
5436   case Qualifiers::OCL_ExplicitNone:
5437     // okay
5438     break;
5439 
5440   case Qualifiers::OCL_Weak:
5441   case Qualifiers::OCL_Strong:
5442   case Qualifiers::OCL_Autoreleasing:
5443     // FIXME: Can this happen? By this point, ValType should be known
5444     // to be trivially copyable.
5445     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
5446         << ValType << Ptr->getSourceRange();
5447     return ExprError();
5448   }
5449 
5450   // All atomic operations have an overload which takes a pointer to a volatile
5451   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
5452   // into the result or the other operands. Similarly atomic_load takes a
5453   // pointer to a const 'A'.
5454   ValType.removeLocalVolatile();
5455   ValType.removeLocalConst();
5456   QualType ResultType = ValType;
5457   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
5458       Form == Init)
5459     ResultType = Context.VoidTy;
5460   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
5461     ResultType = Context.BoolTy;
5462 
5463   // The type of a parameter passed 'by value'. In the GNU atomics, such
5464   // arguments are actually passed as pointers.
5465   QualType ByValType = ValType; // 'CP'
5466   bool IsPassedByAddress = false;
5467   if (!IsC11 && !IsN) {
5468     ByValType = Ptr->getType();
5469     IsPassedByAddress = true;
5470   }
5471 
5472   SmallVector<Expr *, 5> APIOrderedArgs;
5473   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
5474     APIOrderedArgs.push_back(Args[0]);
5475     switch (Form) {
5476     case Init:
5477     case Load:
5478       APIOrderedArgs.push_back(Args[1]); // Val1/Order
5479       break;
5480     case LoadCopy:
5481     case Copy:
5482     case Arithmetic:
5483     case Xchg:
5484       APIOrderedArgs.push_back(Args[2]); // Val1
5485       APIOrderedArgs.push_back(Args[1]); // Order
5486       break;
5487     case GNUXchg:
5488       APIOrderedArgs.push_back(Args[2]); // Val1
5489       APIOrderedArgs.push_back(Args[3]); // Val2
5490       APIOrderedArgs.push_back(Args[1]); // Order
5491       break;
5492     case C11CmpXchg:
5493       APIOrderedArgs.push_back(Args[2]); // Val1
5494       APIOrderedArgs.push_back(Args[4]); // Val2
5495       APIOrderedArgs.push_back(Args[1]); // Order
5496       APIOrderedArgs.push_back(Args[3]); // OrderFail
5497       break;
5498     case GNUCmpXchg:
5499       APIOrderedArgs.push_back(Args[2]); // Val1
5500       APIOrderedArgs.push_back(Args[4]); // Val2
5501       APIOrderedArgs.push_back(Args[5]); // Weak
5502       APIOrderedArgs.push_back(Args[1]); // Order
5503       APIOrderedArgs.push_back(Args[3]); // OrderFail
5504       break;
5505     }
5506   } else
5507     APIOrderedArgs.append(Args.begin(), Args.end());
5508 
5509   // The first argument's non-CV pointer type is used to deduce the type of
5510   // subsequent arguments, except for:
5511   //  - weak flag (always converted to bool)
5512   //  - memory order (always converted to int)
5513   //  - scope  (always converted to int)
5514   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
5515     QualType Ty;
5516     if (i < NumVals[Form] + 1) {
5517       switch (i) {
5518       case 0:
5519         // The first argument is always a pointer. It has a fixed type.
5520         // It is always dereferenced, a nullptr is undefined.
5521         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5522         // Nothing else to do: we already know all we want about this pointer.
5523         continue;
5524       case 1:
5525         // The second argument is the non-atomic operand. For arithmetic, this
5526         // is always passed by value, and for a compare_exchange it is always
5527         // passed by address. For the rest, GNU uses by-address and C11 uses
5528         // by-value.
5529         assert(Form != Load);
5530         if (Form == Arithmetic && ValType->isPointerType())
5531           Ty = Context.getPointerDiffType();
5532         else if (Form == Init || Form == Arithmetic)
5533           Ty = ValType;
5534         else if (Form == Copy || Form == Xchg) {
5535           if (IsPassedByAddress) {
5536             // The value pointer is always dereferenced, a nullptr is undefined.
5537             CheckNonNullArgument(*this, APIOrderedArgs[i],
5538                                  ExprRange.getBegin());
5539           }
5540           Ty = ByValType;
5541         } else {
5542           Expr *ValArg = APIOrderedArgs[i];
5543           // The value pointer is always dereferenced, a nullptr is undefined.
5544           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5545           LangAS AS = LangAS::Default;
5546           // Keep address space of non-atomic pointer type.
5547           if (const PointerType *PtrTy =
5548                   ValArg->getType()->getAs<PointerType>()) {
5549             AS = PtrTy->getPointeeType().getAddressSpace();
5550           }
5551           Ty = Context.getPointerType(
5552               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5553         }
5554         break;
5555       case 2:
5556         // The third argument to compare_exchange / GNU exchange is the desired
5557         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5558         if (IsPassedByAddress)
5559           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5560         Ty = ByValType;
5561         break;
5562       case 3:
5563         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5564         Ty = Context.BoolTy;
5565         break;
5566       }
5567     } else {
5568       // The order(s) and scope are always converted to int.
5569       Ty = Context.IntTy;
5570     }
5571 
5572     InitializedEntity Entity =
5573         InitializedEntity::InitializeParameter(Context, Ty, false);
5574     ExprResult Arg = APIOrderedArgs[i];
5575     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5576     if (Arg.isInvalid())
5577       return true;
5578     APIOrderedArgs[i] = Arg.get();
5579   }
5580 
5581   // Permute the arguments into a 'consistent' order.
5582   SmallVector<Expr*, 5> SubExprs;
5583   SubExprs.push_back(Ptr);
5584   switch (Form) {
5585   case Init:
5586     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5587     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5588     break;
5589   case Load:
5590     SubExprs.push_back(APIOrderedArgs[1]); // Order
5591     break;
5592   case LoadCopy:
5593   case Copy:
5594   case Arithmetic:
5595   case Xchg:
5596     SubExprs.push_back(APIOrderedArgs[2]); // Order
5597     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5598     break;
5599   case GNUXchg:
5600     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5601     SubExprs.push_back(APIOrderedArgs[3]); // Order
5602     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5603     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5604     break;
5605   case C11CmpXchg:
5606     SubExprs.push_back(APIOrderedArgs[3]); // Order
5607     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5608     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5609     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5610     break;
5611   case GNUCmpXchg:
5612     SubExprs.push_back(APIOrderedArgs[4]); // Order
5613     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5614     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5615     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5616     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5617     break;
5618   }
5619 
5620   if (SubExprs.size() >= 2 && Form != Init) {
5621     if (Optional<llvm::APSInt> Result =
5622             SubExprs[1]->getIntegerConstantExpr(Context))
5623       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5624         Diag(SubExprs[1]->getBeginLoc(),
5625              diag::warn_atomic_op_has_invalid_memory_order)
5626             << SubExprs[1]->getSourceRange();
5627   }
5628 
5629   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5630     auto *Scope = Args[Args.size() - 1];
5631     if (Optional<llvm::APSInt> Result =
5632             Scope->getIntegerConstantExpr(Context)) {
5633       if (!ScopeModel->isValid(Result->getZExtValue()))
5634         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5635             << Scope->getSourceRange();
5636     }
5637     SubExprs.push_back(Scope);
5638   }
5639 
5640   AtomicExpr *AE = new (Context)
5641       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5642 
5643   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5644        Op == AtomicExpr::AO__c11_atomic_store ||
5645        Op == AtomicExpr::AO__opencl_atomic_load ||
5646        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5647       Context.AtomicUsesUnsupportedLibcall(AE))
5648     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5649         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5650              Op == AtomicExpr::AO__opencl_atomic_load)
5651                 ? 0
5652                 : 1);
5653 
5654   if (ValType->isExtIntType()) {
5655     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5656     return ExprError();
5657   }
5658 
5659   return AE;
5660 }
5661 
5662 /// checkBuiltinArgument - Given a call to a builtin function, perform
5663 /// normal type-checking on the given argument, updating the call in
5664 /// place.  This is useful when a builtin function requires custom
5665 /// type-checking for some of its arguments but not necessarily all of
5666 /// them.
5667 ///
5668 /// Returns true on error.
5669 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5670   FunctionDecl *Fn = E->getDirectCallee();
5671   assert(Fn && "builtin call without direct callee!");
5672 
5673   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5674   InitializedEntity Entity =
5675     InitializedEntity::InitializeParameter(S.Context, Param);
5676 
5677   ExprResult Arg = E->getArg(0);
5678   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5679   if (Arg.isInvalid())
5680     return true;
5681 
5682   E->setArg(ArgIndex, Arg.get());
5683   return false;
5684 }
5685 
5686 /// We have a call to a function like __sync_fetch_and_add, which is an
5687 /// overloaded function based on the pointer type of its first argument.
5688 /// The main BuildCallExpr routines have already promoted the types of
5689 /// arguments because all of these calls are prototyped as void(...).
5690 ///
5691 /// This function goes through and does final semantic checking for these
5692 /// builtins, as well as generating any warnings.
5693 ExprResult
5694 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5695   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5696   Expr *Callee = TheCall->getCallee();
5697   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5698   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5699 
5700   // Ensure that we have at least one argument to do type inference from.
5701   if (TheCall->getNumArgs() < 1) {
5702     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5703         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5704     return ExprError();
5705   }
5706 
5707   // Inspect the first argument of the atomic builtin.  This should always be
5708   // a pointer type, whose element is an integral scalar or pointer type.
5709   // Because it is a pointer type, we don't have to worry about any implicit
5710   // casts here.
5711   // FIXME: We don't allow floating point scalars as input.
5712   Expr *FirstArg = TheCall->getArg(0);
5713   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5714   if (FirstArgResult.isInvalid())
5715     return ExprError();
5716   FirstArg = FirstArgResult.get();
5717   TheCall->setArg(0, FirstArg);
5718 
5719   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5720   if (!pointerType) {
5721     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5722         << FirstArg->getType() << FirstArg->getSourceRange();
5723     return ExprError();
5724   }
5725 
5726   QualType ValType = pointerType->getPointeeType();
5727   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5728       !ValType->isBlockPointerType()) {
5729     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5730         << FirstArg->getType() << FirstArg->getSourceRange();
5731     return ExprError();
5732   }
5733 
5734   if (ValType.isConstQualified()) {
5735     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5736         << FirstArg->getType() << FirstArg->getSourceRange();
5737     return ExprError();
5738   }
5739 
5740   switch (ValType.getObjCLifetime()) {
5741   case Qualifiers::OCL_None:
5742   case Qualifiers::OCL_ExplicitNone:
5743     // okay
5744     break;
5745 
5746   case Qualifiers::OCL_Weak:
5747   case Qualifiers::OCL_Strong:
5748   case Qualifiers::OCL_Autoreleasing:
5749     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5750         << ValType << FirstArg->getSourceRange();
5751     return ExprError();
5752   }
5753 
5754   // Strip any qualifiers off ValType.
5755   ValType = ValType.getUnqualifiedType();
5756 
5757   // The majority of builtins return a value, but a few have special return
5758   // types, so allow them to override appropriately below.
5759   QualType ResultType = ValType;
5760 
5761   // We need to figure out which concrete builtin this maps onto.  For example,
5762   // __sync_fetch_and_add with a 2 byte object turns into
5763   // __sync_fetch_and_add_2.
5764 #define BUILTIN_ROW(x) \
5765   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5766     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5767 
5768   static const unsigned BuiltinIndices[][5] = {
5769     BUILTIN_ROW(__sync_fetch_and_add),
5770     BUILTIN_ROW(__sync_fetch_and_sub),
5771     BUILTIN_ROW(__sync_fetch_and_or),
5772     BUILTIN_ROW(__sync_fetch_and_and),
5773     BUILTIN_ROW(__sync_fetch_and_xor),
5774     BUILTIN_ROW(__sync_fetch_and_nand),
5775 
5776     BUILTIN_ROW(__sync_add_and_fetch),
5777     BUILTIN_ROW(__sync_sub_and_fetch),
5778     BUILTIN_ROW(__sync_and_and_fetch),
5779     BUILTIN_ROW(__sync_or_and_fetch),
5780     BUILTIN_ROW(__sync_xor_and_fetch),
5781     BUILTIN_ROW(__sync_nand_and_fetch),
5782 
5783     BUILTIN_ROW(__sync_val_compare_and_swap),
5784     BUILTIN_ROW(__sync_bool_compare_and_swap),
5785     BUILTIN_ROW(__sync_lock_test_and_set),
5786     BUILTIN_ROW(__sync_lock_release),
5787     BUILTIN_ROW(__sync_swap)
5788   };
5789 #undef BUILTIN_ROW
5790 
5791   // Determine the index of the size.
5792   unsigned SizeIndex;
5793   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5794   case 1: SizeIndex = 0; break;
5795   case 2: SizeIndex = 1; break;
5796   case 4: SizeIndex = 2; break;
5797   case 8: SizeIndex = 3; break;
5798   case 16: SizeIndex = 4; break;
5799   default:
5800     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5801         << FirstArg->getType() << FirstArg->getSourceRange();
5802     return ExprError();
5803   }
5804 
5805   // Each of these builtins has one pointer argument, followed by some number of
5806   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5807   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5808   // as the number of fixed args.
5809   unsigned BuiltinID = FDecl->getBuiltinID();
5810   unsigned BuiltinIndex, NumFixed = 1;
5811   bool WarnAboutSemanticsChange = false;
5812   switch (BuiltinID) {
5813   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5814   case Builtin::BI__sync_fetch_and_add:
5815   case Builtin::BI__sync_fetch_and_add_1:
5816   case Builtin::BI__sync_fetch_and_add_2:
5817   case Builtin::BI__sync_fetch_and_add_4:
5818   case Builtin::BI__sync_fetch_and_add_8:
5819   case Builtin::BI__sync_fetch_and_add_16:
5820     BuiltinIndex = 0;
5821     break;
5822 
5823   case Builtin::BI__sync_fetch_and_sub:
5824   case Builtin::BI__sync_fetch_and_sub_1:
5825   case Builtin::BI__sync_fetch_and_sub_2:
5826   case Builtin::BI__sync_fetch_and_sub_4:
5827   case Builtin::BI__sync_fetch_and_sub_8:
5828   case Builtin::BI__sync_fetch_and_sub_16:
5829     BuiltinIndex = 1;
5830     break;
5831 
5832   case Builtin::BI__sync_fetch_and_or:
5833   case Builtin::BI__sync_fetch_and_or_1:
5834   case Builtin::BI__sync_fetch_and_or_2:
5835   case Builtin::BI__sync_fetch_and_or_4:
5836   case Builtin::BI__sync_fetch_and_or_8:
5837   case Builtin::BI__sync_fetch_and_or_16:
5838     BuiltinIndex = 2;
5839     break;
5840 
5841   case Builtin::BI__sync_fetch_and_and:
5842   case Builtin::BI__sync_fetch_and_and_1:
5843   case Builtin::BI__sync_fetch_and_and_2:
5844   case Builtin::BI__sync_fetch_and_and_4:
5845   case Builtin::BI__sync_fetch_and_and_8:
5846   case Builtin::BI__sync_fetch_and_and_16:
5847     BuiltinIndex = 3;
5848     break;
5849 
5850   case Builtin::BI__sync_fetch_and_xor:
5851   case Builtin::BI__sync_fetch_and_xor_1:
5852   case Builtin::BI__sync_fetch_and_xor_2:
5853   case Builtin::BI__sync_fetch_and_xor_4:
5854   case Builtin::BI__sync_fetch_and_xor_8:
5855   case Builtin::BI__sync_fetch_and_xor_16:
5856     BuiltinIndex = 4;
5857     break;
5858 
5859   case Builtin::BI__sync_fetch_and_nand:
5860   case Builtin::BI__sync_fetch_and_nand_1:
5861   case Builtin::BI__sync_fetch_and_nand_2:
5862   case Builtin::BI__sync_fetch_and_nand_4:
5863   case Builtin::BI__sync_fetch_and_nand_8:
5864   case Builtin::BI__sync_fetch_and_nand_16:
5865     BuiltinIndex = 5;
5866     WarnAboutSemanticsChange = true;
5867     break;
5868 
5869   case Builtin::BI__sync_add_and_fetch:
5870   case Builtin::BI__sync_add_and_fetch_1:
5871   case Builtin::BI__sync_add_and_fetch_2:
5872   case Builtin::BI__sync_add_and_fetch_4:
5873   case Builtin::BI__sync_add_and_fetch_8:
5874   case Builtin::BI__sync_add_and_fetch_16:
5875     BuiltinIndex = 6;
5876     break;
5877 
5878   case Builtin::BI__sync_sub_and_fetch:
5879   case Builtin::BI__sync_sub_and_fetch_1:
5880   case Builtin::BI__sync_sub_and_fetch_2:
5881   case Builtin::BI__sync_sub_and_fetch_4:
5882   case Builtin::BI__sync_sub_and_fetch_8:
5883   case Builtin::BI__sync_sub_and_fetch_16:
5884     BuiltinIndex = 7;
5885     break;
5886 
5887   case Builtin::BI__sync_and_and_fetch:
5888   case Builtin::BI__sync_and_and_fetch_1:
5889   case Builtin::BI__sync_and_and_fetch_2:
5890   case Builtin::BI__sync_and_and_fetch_4:
5891   case Builtin::BI__sync_and_and_fetch_8:
5892   case Builtin::BI__sync_and_and_fetch_16:
5893     BuiltinIndex = 8;
5894     break;
5895 
5896   case Builtin::BI__sync_or_and_fetch:
5897   case Builtin::BI__sync_or_and_fetch_1:
5898   case Builtin::BI__sync_or_and_fetch_2:
5899   case Builtin::BI__sync_or_and_fetch_4:
5900   case Builtin::BI__sync_or_and_fetch_8:
5901   case Builtin::BI__sync_or_and_fetch_16:
5902     BuiltinIndex = 9;
5903     break;
5904 
5905   case Builtin::BI__sync_xor_and_fetch:
5906   case Builtin::BI__sync_xor_and_fetch_1:
5907   case Builtin::BI__sync_xor_and_fetch_2:
5908   case Builtin::BI__sync_xor_and_fetch_4:
5909   case Builtin::BI__sync_xor_and_fetch_8:
5910   case Builtin::BI__sync_xor_and_fetch_16:
5911     BuiltinIndex = 10;
5912     break;
5913 
5914   case Builtin::BI__sync_nand_and_fetch:
5915   case Builtin::BI__sync_nand_and_fetch_1:
5916   case Builtin::BI__sync_nand_and_fetch_2:
5917   case Builtin::BI__sync_nand_and_fetch_4:
5918   case Builtin::BI__sync_nand_and_fetch_8:
5919   case Builtin::BI__sync_nand_and_fetch_16:
5920     BuiltinIndex = 11;
5921     WarnAboutSemanticsChange = true;
5922     break;
5923 
5924   case Builtin::BI__sync_val_compare_and_swap:
5925   case Builtin::BI__sync_val_compare_and_swap_1:
5926   case Builtin::BI__sync_val_compare_and_swap_2:
5927   case Builtin::BI__sync_val_compare_and_swap_4:
5928   case Builtin::BI__sync_val_compare_and_swap_8:
5929   case Builtin::BI__sync_val_compare_and_swap_16:
5930     BuiltinIndex = 12;
5931     NumFixed = 2;
5932     break;
5933 
5934   case Builtin::BI__sync_bool_compare_and_swap:
5935   case Builtin::BI__sync_bool_compare_and_swap_1:
5936   case Builtin::BI__sync_bool_compare_and_swap_2:
5937   case Builtin::BI__sync_bool_compare_and_swap_4:
5938   case Builtin::BI__sync_bool_compare_and_swap_8:
5939   case Builtin::BI__sync_bool_compare_and_swap_16:
5940     BuiltinIndex = 13;
5941     NumFixed = 2;
5942     ResultType = Context.BoolTy;
5943     break;
5944 
5945   case Builtin::BI__sync_lock_test_and_set:
5946   case Builtin::BI__sync_lock_test_and_set_1:
5947   case Builtin::BI__sync_lock_test_and_set_2:
5948   case Builtin::BI__sync_lock_test_and_set_4:
5949   case Builtin::BI__sync_lock_test_and_set_8:
5950   case Builtin::BI__sync_lock_test_and_set_16:
5951     BuiltinIndex = 14;
5952     break;
5953 
5954   case Builtin::BI__sync_lock_release:
5955   case Builtin::BI__sync_lock_release_1:
5956   case Builtin::BI__sync_lock_release_2:
5957   case Builtin::BI__sync_lock_release_4:
5958   case Builtin::BI__sync_lock_release_8:
5959   case Builtin::BI__sync_lock_release_16:
5960     BuiltinIndex = 15;
5961     NumFixed = 0;
5962     ResultType = Context.VoidTy;
5963     break;
5964 
5965   case Builtin::BI__sync_swap:
5966   case Builtin::BI__sync_swap_1:
5967   case Builtin::BI__sync_swap_2:
5968   case Builtin::BI__sync_swap_4:
5969   case Builtin::BI__sync_swap_8:
5970   case Builtin::BI__sync_swap_16:
5971     BuiltinIndex = 16;
5972     break;
5973   }
5974 
5975   // Now that we know how many fixed arguments we expect, first check that we
5976   // have at least that many.
5977   if (TheCall->getNumArgs() < 1+NumFixed) {
5978     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5979         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5980         << Callee->getSourceRange();
5981     return ExprError();
5982   }
5983 
5984   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5985       << Callee->getSourceRange();
5986 
5987   if (WarnAboutSemanticsChange) {
5988     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5989         << Callee->getSourceRange();
5990   }
5991 
5992   // Get the decl for the concrete builtin from this, we can tell what the
5993   // concrete integer type we should convert to is.
5994   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5995   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5996   FunctionDecl *NewBuiltinDecl;
5997   if (NewBuiltinID == BuiltinID)
5998     NewBuiltinDecl = FDecl;
5999   else {
6000     // Perform builtin lookup to avoid redeclaring it.
6001     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
6002     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
6003     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
6004     assert(Res.getFoundDecl());
6005     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
6006     if (!NewBuiltinDecl)
6007       return ExprError();
6008   }
6009 
6010   // The first argument --- the pointer --- has a fixed type; we
6011   // deduce the types of the rest of the arguments accordingly.  Walk
6012   // the remaining arguments, converting them to the deduced value type.
6013   for (unsigned i = 0; i != NumFixed; ++i) {
6014     ExprResult Arg = TheCall->getArg(i+1);
6015 
6016     // GCC does an implicit conversion to the pointer or integer ValType.  This
6017     // can fail in some cases (1i -> int**), check for this error case now.
6018     // Initialize the argument.
6019     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6020                                                    ValType, /*consume*/ false);
6021     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6022     if (Arg.isInvalid())
6023       return ExprError();
6024 
6025     // Okay, we have something that *can* be converted to the right type.  Check
6026     // to see if there is a potentially weird extension going on here.  This can
6027     // happen when you do an atomic operation on something like an char* and
6028     // pass in 42.  The 42 gets converted to char.  This is even more strange
6029     // for things like 45.123 -> char, etc.
6030     // FIXME: Do this check.
6031     TheCall->setArg(i+1, Arg.get());
6032   }
6033 
6034   // Create a new DeclRefExpr to refer to the new decl.
6035   DeclRefExpr *NewDRE = DeclRefExpr::Create(
6036       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
6037       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
6038       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
6039 
6040   // Set the callee in the CallExpr.
6041   // FIXME: This loses syntactic information.
6042   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
6043   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
6044                                               CK_BuiltinFnToFnPtr);
6045   TheCall->setCallee(PromotedCall.get());
6046 
6047   // Change the result type of the call to match the original value type. This
6048   // is arbitrary, but the codegen for these builtins ins design to handle it
6049   // gracefully.
6050   TheCall->setType(ResultType);
6051 
6052   // Prohibit use of _ExtInt with atomic builtins.
6053   // The arguments would have already been converted to the first argument's
6054   // type, so only need to check the first argument.
6055   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
6056   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
6057     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
6058     return ExprError();
6059   }
6060 
6061   return TheCallResult;
6062 }
6063 
6064 /// SemaBuiltinNontemporalOverloaded - We have a call to
6065 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
6066 /// overloaded function based on the pointer type of its last argument.
6067 ///
6068 /// This function goes through and does final semantic checking for these
6069 /// builtins.
6070 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
6071   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
6072   DeclRefExpr *DRE =
6073       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6074   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6075   unsigned BuiltinID = FDecl->getBuiltinID();
6076   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
6077           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
6078          "Unexpected nontemporal load/store builtin!");
6079   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
6080   unsigned numArgs = isStore ? 2 : 1;
6081 
6082   // Ensure that we have the proper number of arguments.
6083   if (checkArgCount(*this, TheCall, numArgs))
6084     return ExprError();
6085 
6086   // Inspect the last argument of the nontemporal builtin.  This should always
6087   // be a pointer type, from which we imply the type of the memory access.
6088   // Because it is a pointer type, we don't have to worry about any implicit
6089   // casts here.
6090   Expr *PointerArg = TheCall->getArg(numArgs - 1);
6091   ExprResult PointerArgResult =
6092       DefaultFunctionArrayLvalueConversion(PointerArg);
6093 
6094   if (PointerArgResult.isInvalid())
6095     return ExprError();
6096   PointerArg = PointerArgResult.get();
6097   TheCall->setArg(numArgs - 1, PointerArg);
6098 
6099   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
6100   if (!pointerType) {
6101     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
6102         << PointerArg->getType() << PointerArg->getSourceRange();
6103     return ExprError();
6104   }
6105 
6106   QualType ValType = pointerType->getPointeeType();
6107 
6108   // Strip any qualifiers off ValType.
6109   ValType = ValType.getUnqualifiedType();
6110   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
6111       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
6112       !ValType->isVectorType()) {
6113     Diag(DRE->getBeginLoc(),
6114          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
6115         << PointerArg->getType() << PointerArg->getSourceRange();
6116     return ExprError();
6117   }
6118 
6119   if (!isStore) {
6120     TheCall->setType(ValType);
6121     return TheCallResult;
6122   }
6123 
6124   ExprResult ValArg = TheCall->getArg(0);
6125   InitializedEntity Entity = InitializedEntity::InitializeParameter(
6126       Context, ValType, /*consume*/ false);
6127   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
6128   if (ValArg.isInvalid())
6129     return ExprError();
6130 
6131   TheCall->setArg(0, ValArg.get());
6132   TheCall->setType(Context.VoidTy);
6133   return TheCallResult;
6134 }
6135 
6136 /// CheckObjCString - Checks that the argument to the builtin
6137 /// CFString constructor is correct
6138 /// Note: It might also make sense to do the UTF-16 conversion here (would
6139 /// simplify the backend).
6140 bool Sema::CheckObjCString(Expr *Arg) {
6141   Arg = Arg->IgnoreParenCasts();
6142   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
6143 
6144   if (!Literal || !Literal->isAscii()) {
6145     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
6146         << Arg->getSourceRange();
6147     return true;
6148   }
6149 
6150   if (Literal->containsNonAsciiOrNull()) {
6151     StringRef String = Literal->getString();
6152     unsigned NumBytes = String.size();
6153     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
6154     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
6155     llvm::UTF16 *ToPtr = &ToBuf[0];
6156 
6157     llvm::ConversionResult Result =
6158         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
6159                                  ToPtr + NumBytes, llvm::strictConversion);
6160     // Check for conversion failure.
6161     if (Result != llvm::conversionOK)
6162       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
6163           << Arg->getSourceRange();
6164   }
6165   return false;
6166 }
6167 
6168 /// CheckObjCString - Checks that the format string argument to the os_log()
6169 /// and os_trace() functions is correct, and converts it to const char *.
6170 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
6171   Arg = Arg->IgnoreParenCasts();
6172   auto *Literal = dyn_cast<StringLiteral>(Arg);
6173   if (!Literal) {
6174     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
6175       Literal = ObjcLiteral->getString();
6176     }
6177   }
6178 
6179   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
6180     return ExprError(
6181         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
6182         << Arg->getSourceRange());
6183   }
6184 
6185   ExprResult Result(Literal);
6186   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
6187   InitializedEntity Entity =
6188       InitializedEntity::InitializeParameter(Context, ResultTy, false);
6189   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
6190   return Result;
6191 }
6192 
6193 /// Check that the user is calling the appropriate va_start builtin for the
6194 /// target and calling convention.
6195 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
6196   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
6197   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
6198   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
6199                     TT.getArch() == llvm::Triple::aarch64_32);
6200   bool IsWindows = TT.isOSWindows();
6201   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
6202   if (IsX64 || IsAArch64) {
6203     CallingConv CC = CC_C;
6204     if (const FunctionDecl *FD = S.getCurFunctionDecl())
6205       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
6206     if (IsMSVAStart) {
6207       // Don't allow this in System V ABI functions.
6208       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
6209         return S.Diag(Fn->getBeginLoc(),
6210                       diag::err_ms_va_start_used_in_sysv_function);
6211     } else {
6212       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
6213       // On x64 Windows, don't allow this in System V ABI functions.
6214       // (Yes, that means there's no corresponding way to support variadic
6215       // System V ABI functions on Windows.)
6216       if ((IsWindows && CC == CC_X86_64SysV) ||
6217           (!IsWindows && CC == CC_Win64))
6218         return S.Diag(Fn->getBeginLoc(),
6219                       diag::err_va_start_used_in_wrong_abi_function)
6220                << !IsWindows;
6221     }
6222     return false;
6223   }
6224 
6225   if (IsMSVAStart)
6226     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
6227   return false;
6228 }
6229 
6230 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
6231                                              ParmVarDecl **LastParam = nullptr) {
6232   // Determine whether the current function, block, or obj-c method is variadic
6233   // and get its parameter list.
6234   bool IsVariadic = false;
6235   ArrayRef<ParmVarDecl *> Params;
6236   DeclContext *Caller = S.CurContext;
6237   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
6238     IsVariadic = Block->isVariadic();
6239     Params = Block->parameters();
6240   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
6241     IsVariadic = FD->isVariadic();
6242     Params = FD->parameters();
6243   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
6244     IsVariadic = MD->isVariadic();
6245     // FIXME: This isn't correct for methods (results in bogus warning).
6246     Params = MD->parameters();
6247   } else if (isa<CapturedDecl>(Caller)) {
6248     // We don't support va_start in a CapturedDecl.
6249     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
6250     return true;
6251   } else {
6252     // This must be some other declcontext that parses exprs.
6253     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
6254     return true;
6255   }
6256 
6257   if (!IsVariadic) {
6258     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
6259     return true;
6260   }
6261 
6262   if (LastParam)
6263     *LastParam = Params.empty() ? nullptr : Params.back();
6264 
6265   return false;
6266 }
6267 
6268 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
6269 /// for validity.  Emit an error and return true on failure; return false
6270 /// on success.
6271 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
6272   Expr *Fn = TheCall->getCallee();
6273 
6274   if (checkVAStartABI(*this, BuiltinID, Fn))
6275     return true;
6276 
6277   if (checkArgCount(*this, TheCall, 2))
6278     return true;
6279 
6280   // Type-check the first argument normally.
6281   if (checkBuiltinArgument(*this, TheCall, 0))
6282     return true;
6283 
6284   // Check that the current function is variadic, and get its last parameter.
6285   ParmVarDecl *LastParam;
6286   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
6287     return true;
6288 
6289   // Verify that the second argument to the builtin is the last argument of the
6290   // current function or method.
6291   bool SecondArgIsLastNamedArgument = false;
6292   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
6293 
6294   // These are valid if SecondArgIsLastNamedArgument is false after the next
6295   // block.
6296   QualType Type;
6297   SourceLocation ParamLoc;
6298   bool IsCRegister = false;
6299 
6300   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
6301     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
6302       SecondArgIsLastNamedArgument = PV == LastParam;
6303 
6304       Type = PV->getType();
6305       ParamLoc = PV->getLocation();
6306       IsCRegister =
6307           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
6308     }
6309   }
6310 
6311   if (!SecondArgIsLastNamedArgument)
6312     Diag(TheCall->getArg(1)->getBeginLoc(),
6313          diag::warn_second_arg_of_va_start_not_last_named_param);
6314   else if (IsCRegister || Type->isReferenceType() ||
6315            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
6316              // Promotable integers are UB, but enumerations need a bit of
6317              // extra checking to see what their promotable type actually is.
6318              if (!Type->isPromotableIntegerType())
6319                return false;
6320              if (!Type->isEnumeralType())
6321                return true;
6322              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
6323              return !(ED &&
6324                       Context.typesAreCompatible(ED->getPromotionType(), Type));
6325            }()) {
6326     unsigned Reason = 0;
6327     if (Type->isReferenceType())  Reason = 1;
6328     else if (IsCRegister)         Reason = 2;
6329     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
6330     Diag(ParamLoc, diag::note_parameter_type) << Type;
6331   }
6332 
6333   TheCall->setType(Context.VoidTy);
6334   return false;
6335 }
6336 
6337 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
6338   auto IsSuitablyTypedFormatArgument = [this](const Expr *Arg) -> bool {
6339     const LangOptions &LO = getLangOpts();
6340 
6341     if (LO.CPlusPlus)
6342       return Arg->getType()
6343                  .getCanonicalType()
6344                  .getTypePtr()
6345                  ->getPointeeType()
6346                  .withoutLocalFastQualifiers() == Context.CharTy;
6347 
6348     // In C, allow aliasing through `char *`, this is required for AArch64 at
6349     // least.
6350     return true;
6351   };
6352 
6353   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
6354   //                 const char *named_addr);
6355 
6356   Expr *Func = Call->getCallee();
6357 
6358   if (Call->getNumArgs() < 3)
6359     return Diag(Call->getEndLoc(),
6360                 diag::err_typecheck_call_too_few_args_at_least)
6361            << 0 /*function call*/ << 3 << Call->getNumArgs();
6362 
6363   // Type-check the first argument normally.
6364   if (checkBuiltinArgument(*this, Call, 0))
6365     return true;
6366 
6367   // Check that the current function is variadic.
6368   if (checkVAStartIsInVariadicFunction(*this, Func))
6369     return true;
6370 
6371   // __va_start on Windows does not validate the parameter qualifiers
6372 
6373   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
6374   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
6375 
6376   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
6377   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
6378 
6379   const QualType &ConstCharPtrTy =
6380       Context.getPointerType(Context.CharTy.withConst());
6381   if (!Arg1Ty->isPointerType() || !IsSuitablyTypedFormatArgument(Arg1))
6382     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6383         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
6384         << 0                                      /* qualifier difference */
6385         << 3                                      /* parameter mismatch */
6386         << 2 << Arg1->getType() << ConstCharPtrTy;
6387 
6388   const QualType SizeTy = Context.getSizeType();
6389   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
6390     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6391         << Arg2->getType() << SizeTy << 1 /* different class */
6392         << 0                              /* qualifier difference */
6393         << 3                              /* parameter mismatch */
6394         << 3 << Arg2->getType() << SizeTy;
6395 
6396   return false;
6397 }
6398 
6399 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
6400 /// friends.  This is declared to take (...), so we have to check everything.
6401 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
6402   if (checkArgCount(*this, TheCall, 2))
6403     return true;
6404 
6405   ExprResult OrigArg0 = TheCall->getArg(0);
6406   ExprResult OrigArg1 = TheCall->getArg(1);
6407 
6408   // Do standard promotions between the two arguments, returning their common
6409   // type.
6410   QualType Res = UsualArithmeticConversions(
6411       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
6412   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
6413     return true;
6414 
6415   // Make sure any conversions are pushed back into the call; this is
6416   // type safe since unordered compare builtins are declared as "_Bool
6417   // foo(...)".
6418   TheCall->setArg(0, OrigArg0.get());
6419   TheCall->setArg(1, OrigArg1.get());
6420 
6421   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
6422     return false;
6423 
6424   // If the common type isn't a real floating type, then the arguments were
6425   // invalid for this operation.
6426   if (Res.isNull() || !Res->isRealFloatingType())
6427     return Diag(OrigArg0.get()->getBeginLoc(),
6428                 diag::err_typecheck_call_invalid_ordered_compare)
6429            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
6430            << SourceRange(OrigArg0.get()->getBeginLoc(),
6431                           OrigArg1.get()->getEndLoc());
6432 
6433   return false;
6434 }
6435 
6436 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
6437 /// __builtin_isnan and friends.  This is declared to take (...), so we have
6438 /// to check everything. We expect the last argument to be a floating point
6439 /// value.
6440 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
6441   if (checkArgCount(*this, TheCall, NumArgs))
6442     return true;
6443 
6444   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
6445   // on all preceding parameters just being int.  Try all of those.
6446   for (unsigned i = 0; i < NumArgs - 1; ++i) {
6447     Expr *Arg = TheCall->getArg(i);
6448 
6449     if (Arg->isTypeDependent())
6450       return false;
6451 
6452     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
6453 
6454     if (Res.isInvalid())
6455       return true;
6456     TheCall->setArg(i, Res.get());
6457   }
6458 
6459   Expr *OrigArg = TheCall->getArg(NumArgs-1);
6460 
6461   if (OrigArg->isTypeDependent())
6462     return false;
6463 
6464   // Usual Unary Conversions will convert half to float, which we want for
6465   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
6466   // type how it is, but do normal L->Rvalue conversions.
6467   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
6468     OrigArg = UsualUnaryConversions(OrigArg).get();
6469   else
6470     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
6471   TheCall->setArg(NumArgs - 1, OrigArg);
6472 
6473   // This operation requires a non-_Complex floating-point number.
6474   if (!OrigArg->getType()->isRealFloatingType())
6475     return Diag(OrigArg->getBeginLoc(),
6476                 diag::err_typecheck_call_invalid_unary_fp)
6477            << OrigArg->getType() << OrigArg->getSourceRange();
6478 
6479   return false;
6480 }
6481 
6482 /// Perform semantic analysis for a call to __builtin_complex.
6483 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
6484   if (checkArgCount(*this, TheCall, 2))
6485     return true;
6486 
6487   bool Dependent = false;
6488   for (unsigned I = 0; I != 2; ++I) {
6489     Expr *Arg = TheCall->getArg(I);
6490     QualType T = Arg->getType();
6491     if (T->isDependentType()) {
6492       Dependent = true;
6493       continue;
6494     }
6495 
6496     // Despite supporting _Complex int, GCC requires a real floating point type
6497     // for the operands of __builtin_complex.
6498     if (!T->isRealFloatingType()) {
6499       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
6500              << Arg->getType() << Arg->getSourceRange();
6501     }
6502 
6503     ExprResult Converted = DefaultLvalueConversion(Arg);
6504     if (Converted.isInvalid())
6505       return true;
6506     TheCall->setArg(I, Converted.get());
6507   }
6508 
6509   if (Dependent) {
6510     TheCall->setType(Context.DependentTy);
6511     return false;
6512   }
6513 
6514   Expr *Real = TheCall->getArg(0);
6515   Expr *Imag = TheCall->getArg(1);
6516   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
6517     return Diag(Real->getBeginLoc(),
6518                 diag::err_typecheck_call_different_arg_types)
6519            << Real->getType() << Imag->getType()
6520            << Real->getSourceRange() << Imag->getSourceRange();
6521   }
6522 
6523   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
6524   // don't allow this builtin to form those types either.
6525   // FIXME: Should we allow these types?
6526   if (Real->getType()->isFloat16Type())
6527     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6528            << "_Float16";
6529   if (Real->getType()->isHalfType())
6530     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
6531            << "half";
6532 
6533   TheCall->setType(Context.getComplexType(Real->getType()));
6534   return false;
6535 }
6536 
6537 // Customized Sema Checking for VSX builtins that have the following signature:
6538 // vector [...] builtinName(vector [...], vector [...], const int);
6539 // Which takes the same type of vectors (any legal vector type) for the first
6540 // two arguments and takes compile time constant for the third argument.
6541 // Example builtins are :
6542 // vector double vec_xxpermdi(vector double, vector double, int);
6543 // vector short vec_xxsldwi(vector short, vector short, int);
6544 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6545   unsigned ExpectedNumArgs = 3;
6546   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6547     return true;
6548 
6549   // Check the third argument is a compile time constant
6550   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6551     return Diag(TheCall->getBeginLoc(),
6552                 diag::err_vsx_builtin_nonconstant_argument)
6553            << 3 /* argument index */ << TheCall->getDirectCallee()
6554            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6555                           TheCall->getArg(2)->getEndLoc());
6556 
6557   QualType Arg1Ty = TheCall->getArg(0)->getType();
6558   QualType Arg2Ty = TheCall->getArg(1)->getType();
6559 
6560   // Check the type of argument 1 and argument 2 are vectors.
6561   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6562   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6563       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6564     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6565            << TheCall->getDirectCallee()
6566            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6567                           TheCall->getArg(1)->getEndLoc());
6568   }
6569 
6570   // Check the first two arguments are the same type.
6571   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6572     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6573            << TheCall->getDirectCallee()
6574            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6575                           TheCall->getArg(1)->getEndLoc());
6576   }
6577 
6578   // When default clang type checking is turned off and the customized type
6579   // checking is used, the returning type of the function must be explicitly
6580   // set. Otherwise it is _Bool by default.
6581   TheCall->setType(Arg1Ty);
6582 
6583   return false;
6584 }
6585 
6586 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6587 // This is declared to take (...), so we have to check everything.
6588 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6589   if (TheCall->getNumArgs() < 2)
6590     return ExprError(Diag(TheCall->getEndLoc(),
6591                           diag::err_typecheck_call_too_few_args_at_least)
6592                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6593                      << TheCall->getSourceRange());
6594 
6595   // Determine which of the following types of shufflevector we're checking:
6596   // 1) unary, vector mask: (lhs, mask)
6597   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6598   QualType resType = TheCall->getArg(0)->getType();
6599   unsigned numElements = 0;
6600 
6601   if (!TheCall->getArg(0)->isTypeDependent() &&
6602       !TheCall->getArg(1)->isTypeDependent()) {
6603     QualType LHSType = TheCall->getArg(0)->getType();
6604     QualType RHSType = TheCall->getArg(1)->getType();
6605 
6606     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6607       return ExprError(
6608           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6609           << TheCall->getDirectCallee()
6610           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6611                          TheCall->getArg(1)->getEndLoc()));
6612 
6613     numElements = LHSType->castAs<VectorType>()->getNumElements();
6614     unsigned numResElements = TheCall->getNumArgs() - 2;
6615 
6616     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6617     // with mask.  If so, verify that RHS is an integer vector type with the
6618     // same number of elts as lhs.
6619     if (TheCall->getNumArgs() == 2) {
6620       if (!RHSType->hasIntegerRepresentation() ||
6621           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6622         return ExprError(Diag(TheCall->getBeginLoc(),
6623                               diag::err_vec_builtin_incompatible_vector)
6624                          << TheCall->getDirectCallee()
6625                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6626                                         TheCall->getArg(1)->getEndLoc()));
6627     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6628       return ExprError(Diag(TheCall->getBeginLoc(),
6629                             diag::err_vec_builtin_incompatible_vector)
6630                        << TheCall->getDirectCallee()
6631                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6632                                       TheCall->getArg(1)->getEndLoc()));
6633     } else if (numElements != numResElements) {
6634       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6635       resType = Context.getVectorType(eltType, numResElements,
6636                                       VectorType::GenericVector);
6637     }
6638   }
6639 
6640   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6641     if (TheCall->getArg(i)->isTypeDependent() ||
6642         TheCall->getArg(i)->isValueDependent())
6643       continue;
6644 
6645     Optional<llvm::APSInt> Result;
6646     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6647       return ExprError(Diag(TheCall->getBeginLoc(),
6648                             diag::err_shufflevector_nonconstant_argument)
6649                        << TheCall->getArg(i)->getSourceRange());
6650 
6651     // Allow -1 which will be translated to undef in the IR.
6652     if (Result->isSigned() && Result->isAllOnes())
6653       continue;
6654 
6655     if (Result->getActiveBits() > 64 ||
6656         Result->getZExtValue() >= numElements * 2)
6657       return ExprError(Diag(TheCall->getBeginLoc(),
6658                             diag::err_shufflevector_argument_too_large)
6659                        << TheCall->getArg(i)->getSourceRange());
6660   }
6661 
6662   SmallVector<Expr*, 32> exprs;
6663 
6664   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6665     exprs.push_back(TheCall->getArg(i));
6666     TheCall->setArg(i, nullptr);
6667   }
6668 
6669   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6670                                          TheCall->getCallee()->getBeginLoc(),
6671                                          TheCall->getRParenLoc());
6672 }
6673 
6674 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6675 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6676                                        SourceLocation BuiltinLoc,
6677                                        SourceLocation RParenLoc) {
6678   ExprValueKind VK = VK_PRValue;
6679   ExprObjectKind OK = OK_Ordinary;
6680   QualType DstTy = TInfo->getType();
6681   QualType SrcTy = E->getType();
6682 
6683   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6684     return ExprError(Diag(BuiltinLoc,
6685                           diag::err_convertvector_non_vector)
6686                      << E->getSourceRange());
6687   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6688     return ExprError(Diag(BuiltinLoc,
6689                           diag::err_convertvector_non_vector_type));
6690 
6691   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6692     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6693     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6694     if (SrcElts != DstElts)
6695       return ExprError(Diag(BuiltinLoc,
6696                             diag::err_convertvector_incompatible_vector)
6697                        << E->getSourceRange());
6698   }
6699 
6700   return new (Context)
6701       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6702 }
6703 
6704 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6705 // This is declared to take (const void*, ...) and can take two
6706 // optional constant int args.
6707 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6708   unsigned NumArgs = TheCall->getNumArgs();
6709 
6710   if (NumArgs > 3)
6711     return Diag(TheCall->getEndLoc(),
6712                 diag::err_typecheck_call_too_many_args_at_most)
6713            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6714 
6715   // Argument 0 is checked for us and the remaining arguments must be
6716   // constant integers.
6717   for (unsigned i = 1; i != NumArgs; ++i)
6718     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6719       return true;
6720 
6721   return false;
6722 }
6723 
6724 /// SemaBuiltinArithmeticFence - Handle __arithmetic_fence.
6725 bool Sema::SemaBuiltinArithmeticFence(CallExpr *TheCall) {
6726   if (!Context.getTargetInfo().checkArithmeticFenceSupported())
6727     return Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
6728            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6729   if (checkArgCount(*this, TheCall, 1))
6730     return true;
6731   Expr *Arg = TheCall->getArg(0);
6732   if (Arg->isInstantiationDependent())
6733     return false;
6734 
6735   QualType ArgTy = Arg->getType();
6736   if (!ArgTy->hasFloatingRepresentation())
6737     return Diag(TheCall->getEndLoc(), diag::err_typecheck_expect_flt_or_vector)
6738            << ArgTy;
6739   if (Arg->isLValue()) {
6740     ExprResult FirstArg = DefaultLvalueConversion(Arg);
6741     TheCall->setArg(0, FirstArg.get());
6742   }
6743   TheCall->setType(TheCall->getArg(0)->getType());
6744   return false;
6745 }
6746 
6747 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6748 // __assume does not evaluate its arguments, and should warn if its argument
6749 // has side effects.
6750 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6751   Expr *Arg = TheCall->getArg(0);
6752   if (Arg->isInstantiationDependent()) return false;
6753 
6754   if (Arg->HasSideEffects(Context))
6755     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6756         << Arg->getSourceRange()
6757         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6758 
6759   return false;
6760 }
6761 
6762 /// Handle __builtin_alloca_with_align. This is declared
6763 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6764 /// than 8.
6765 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6766   // The alignment must be a constant integer.
6767   Expr *Arg = TheCall->getArg(1);
6768 
6769   // We can't check the value of a dependent argument.
6770   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6771     if (const auto *UE =
6772             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6773       if (UE->getKind() == UETT_AlignOf ||
6774           UE->getKind() == UETT_PreferredAlignOf)
6775         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6776             << Arg->getSourceRange();
6777 
6778     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6779 
6780     if (!Result.isPowerOf2())
6781       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6782              << Arg->getSourceRange();
6783 
6784     if (Result < Context.getCharWidth())
6785       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6786              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6787 
6788     if (Result > std::numeric_limits<int32_t>::max())
6789       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6790              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6791   }
6792 
6793   return false;
6794 }
6795 
6796 /// Handle __builtin_assume_aligned. This is declared
6797 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6798 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6799   unsigned NumArgs = TheCall->getNumArgs();
6800 
6801   if (NumArgs > 3)
6802     return Diag(TheCall->getEndLoc(),
6803                 diag::err_typecheck_call_too_many_args_at_most)
6804            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6805 
6806   // The alignment must be a constant integer.
6807   Expr *Arg = TheCall->getArg(1);
6808 
6809   // We can't check the value of a dependent argument.
6810   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6811     llvm::APSInt Result;
6812     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6813       return true;
6814 
6815     if (!Result.isPowerOf2())
6816       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6817              << Arg->getSourceRange();
6818 
6819     if (Result > Sema::MaximumAlignment)
6820       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6821           << Arg->getSourceRange() << Sema::MaximumAlignment;
6822   }
6823 
6824   if (NumArgs > 2) {
6825     ExprResult Arg(TheCall->getArg(2));
6826     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6827       Context.getSizeType(), false);
6828     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6829     if (Arg.isInvalid()) return true;
6830     TheCall->setArg(2, Arg.get());
6831   }
6832 
6833   return false;
6834 }
6835 
6836 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6837   unsigned BuiltinID =
6838       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6839   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6840 
6841   unsigned NumArgs = TheCall->getNumArgs();
6842   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6843   if (NumArgs < NumRequiredArgs) {
6844     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6845            << 0 /* function call */ << NumRequiredArgs << NumArgs
6846            << TheCall->getSourceRange();
6847   }
6848   if (NumArgs >= NumRequiredArgs + 0x100) {
6849     return Diag(TheCall->getEndLoc(),
6850                 diag::err_typecheck_call_too_many_args_at_most)
6851            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6852            << TheCall->getSourceRange();
6853   }
6854   unsigned i = 0;
6855 
6856   // For formatting call, check buffer arg.
6857   if (!IsSizeCall) {
6858     ExprResult Arg(TheCall->getArg(i));
6859     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6860         Context, Context.VoidPtrTy, false);
6861     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6862     if (Arg.isInvalid())
6863       return true;
6864     TheCall->setArg(i, Arg.get());
6865     i++;
6866   }
6867 
6868   // Check string literal arg.
6869   unsigned FormatIdx = i;
6870   {
6871     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6872     if (Arg.isInvalid())
6873       return true;
6874     TheCall->setArg(i, Arg.get());
6875     i++;
6876   }
6877 
6878   // Make sure variadic args are scalar.
6879   unsigned FirstDataArg = i;
6880   while (i < NumArgs) {
6881     ExprResult Arg = DefaultVariadicArgumentPromotion(
6882         TheCall->getArg(i), VariadicFunction, nullptr);
6883     if (Arg.isInvalid())
6884       return true;
6885     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6886     if (ArgSize.getQuantity() >= 0x100) {
6887       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6888              << i << (int)ArgSize.getQuantity() << 0xff
6889              << TheCall->getSourceRange();
6890     }
6891     TheCall->setArg(i, Arg.get());
6892     i++;
6893   }
6894 
6895   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6896   // call to avoid duplicate diagnostics.
6897   if (!IsSizeCall) {
6898     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6899     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6900     bool Success = CheckFormatArguments(
6901         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6902         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6903         CheckedVarArgs);
6904     if (!Success)
6905       return true;
6906   }
6907 
6908   if (IsSizeCall) {
6909     TheCall->setType(Context.getSizeType());
6910   } else {
6911     TheCall->setType(Context.VoidPtrTy);
6912   }
6913   return false;
6914 }
6915 
6916 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6917 /// TheCall is a constant expression.
6918 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6919                                   llvm::APSInt &Result) {
6920   Expr *Arg = TheCall->getArg(ArgNum);
6921   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6922   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6923 
6924   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6925 
6926   Optional<llvm::APSInt> R;
6927   if (!(R = Arg->getIntegerConstantExpr(Context)))
6928     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6929            << FDecl->getDeclName() << Arg->getSourceRange();
6930   Result = *R;
6931   return false;
6932 }
6933 
6934 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6935 /// TheCall is a constant expression in the range [Low, High].
6936 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6937                                        int Low, int High, bool RangeIsError) {
6938   if (isConstantEvaluated())
6939     return false;
6940   llvm::APSInt Result;
6941 
6942   // We can't check the value of a dependent argument.
6943   Expr *Arg = TheCall->getArg(ArgNum);
6944   if (Arg->isTypeDependent() || Arg->isValueDependent())
6945     return false;
6946 
6947   // Check constant-ness first.
6948   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6949     return true;
6950 
6951   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6952     if (RangeIsError)
6953       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6954              << toString(Result, 10) << Low << High << Arg->getSourceRange();
6955     else
6956       // Defer the warning until we know if the code will be emitted so that
6957       // dead code can ignore this.
6958       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6959                           PDiag(diag::warn_argument_invalid_range)
6960                               << toString(Result, 10) << Low << High
6961                               << Arg->getSourceRange());
6962   }
6963 
6964   return false;
6965 }
6966 
6967 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6968 /// TheCall is a constant expression is a multiple of Num..
6969 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6970                                           unsigned Num) {
6971   llvm::APSInt Result;
6972 
6973   // We can't check the value of a dependent argument.
6974   Expr *Arg = TheCall->getArg(ArgNum);
6975   if (Arg->isTypeDependent() || Arg->isValueDependent())
6976     return false;
6977 
6978   // Check constant-ness first.
6979   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6980     return true;
6981 
6982   if (Result.getSExtValue() % Num != 0)
6983     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6984            << Num << Arg->getSourceRange();
6985 
6986   return false;
6987 }
6988 
6989 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6990 /// constant expression representing a power of 2.
6991 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
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   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
7004   // and only if x is a power of 2.
7005   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
7006     return false;
7007 
7008   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
7009          << Arg->getSourceRange();
7010 }
7011 
7012 static bool IsShiftedByte(llvm::APSInt Value) {
7013   if (Value.isNegative())
7014     return false;
7015 
7016   // Check if it's a shifted byte, by shifting it down
7017   while (true) {
7018     // If the value fits in the bottom byte, the check passes.
7019     if (Value < 0x100)
7020       return true;
7021 
7022     // Otherwise, if the value has _any_ bits in the bottom byte, the check
7023     // fails.
7024     if ((Value & 0xFF) != 0)
7025       return false;
7026 
7027     // If the bottom 8 bits are all 0, but something above that is nonzero,
7028     // then shifting the value right by 8 bits won't affect whether it's a
7029     // shifted byte or not. So do that, and go round again.
7030     Value >>= 8;
7031   }
7032 }
7033 
7034 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
7035 /// a constant expression representing an arbitrary byte value shifted left by
7036 /// a multiple of 8 bits.
7037 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
7038                                              unsigned ArgBits) {
7039   llvm::APSInt Result;
7040 
7041   // We can't check the value of a dependent argument.
7042   Expr *Arg = TheCall->getArg(ArgNum);
7043   if (Arg->isTypeDependent() || Arg->isValueDependent())
7044     return false;
7045 
7046   // Check constant-ness first.
7047   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7048     return true;
7049 
7050   // Truncate to the given size.
7051   Result = Result.getLoBits(ArgBits);
7052   Result.setIsUnsigned(true);
7053 
7054   if (IsShiftedByte(Result))
7055     return false;
7056 
7057   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
7058          << Arg->getSourceRange();
7059 }
7060 
7061 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
7062 /// TheCall is a constant expression representing either a shifted byte value,
7063 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
7064 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
7065 /// Arm MVE intrinsics.
7066 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
7067                                                    int ArgNum,
7068                                                    unsigned ArgBits) {
7069   llvm::APSInt Result;
7070 
7071   // We can't check the value of a dependent argument.
7072   Expr *Arg = TheCall->getArg(ArgNum);
7073   if (Arg->isTypeDependent() || Arg->isValueDependent())
7074     return false;
7075 
7076   // Check constant-ness first.
7077   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
7078     return true;
7079 
7080   // Truncate to the given size.
7081   Result = Result.getLoBits(ArgBits);
7082   Result.setIsUnsigned(true);
7083 
7084   // Check to see if it's in either of the required forms.
7085   if (IsShiftedByte(Result) ||
7086       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
7087     return false;
7088 
7089   return Diag(TheCall->getBeginLoc(),
7090               diag::err_argument_not_shifted_byte_or_xxff)
7091          << Arg->getSourceRange();
7092 }
7093 
7094 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
7095 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
7096   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
7097     if (checkArgCount(*this, TheCall, 2))
7098       return true;
7099     Expr *Arg0 = TheCall->getArg(0);
7100     Expr *Arg1 = TheCall->getArg(1);
7101 
7102     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7103     if (FirstArg.isInvalid())
7104       return true;
7105     QualType FirstArgType = FirstArg.get()->getType();
7106     if (!FirstArgType->isAnyPointerType())
7107       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7108                << "first" << FirstArgType << Arg0->getSourceRange();
7109     TheCall->setArg(0, FirstArg.get());
7110 
7111     ExprResult SecArg = DefaultLvalueConversion(Arg1);
7112     if (SecArg.isInvalid())
7113       return true;
7114     QualType SecArgType = SecArg.get()->getType();
7115     if (!SecArgType->isIntegerType())
7116       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7117                << "second" << SecArgType << Arg1->getSourceRange();
7118 
7119     // Derive the return type from the pointer argument.
7120     TheCall->setType(FirstArgType);
7121     return false;
7122   }
7123 
7124   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
7125     if (checkArgCount(*this, TheCall, 2))
7126       return true;
7127 
7128     Expr *Arg0 = TheCall->getArg(0);
7129     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7130     if (FirstArg.isInvalid())
7131       return true;
7132     QualType FirstArgType = FirstArg.get()->getType();
7133     if (!FirstArgType->isAnyPointerType())
7134       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7135                << "first" << FirstArgType << Arg0->getSourceRange();
7136     TheCall->setArg(0, FirstArg.get());
7137 
7138     // Derive the return type from the pointer argument.
7139     TheCall->setType(FirstArgType);
7140 
7141     // Second arg must be an constant in range [0,15]
7142     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7143   }
7144 
7145   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
7146     if (checkArgCount(*this, TheCall, 2))
7147       return true;
7148     Expr *Arg0 = TheCall->getArg(0);
7149     Expr *Arg1 = TheCall->getArg(1);
7150 
7151     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7152     if (FirstArg.isInvalid())
7153       return true;
7154     QualType FirstArgType = FirstArg.get()->getType();
7155     if (!FirstArgType->isAnyPointerType())
7156       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7157                << "first" << FirstArgType << Arg0->getSourceRange();
7158 
7159     QualType SecArgType = Arg1->getType();
7160     if (!SecArgType->isIntegerType())
7161       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
7162                << "second" << SecArgType << Arg1->getSourceRange();
7163     TheCall->setType(Context.IntTy);
7164     return false;
7165   }
7166 
7167   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
7168       BuiltinID == AArch64::BI__builtin_arm_stg) {
7169     if (checkArgCount(*this, TheCall, 1))
7170       return true;
7171     Expr *Arg0 = TheCall->getArg(0);
7172     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
7173     if (FirstArg.isInvalid())
7174       return true;
7175 
7176     QualType FirstArgType = FirstArg.get()->getType();
7177     if (!FirstArgType->isAnyPointerType())
7178       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
7179                << "first" << FirstArgType << Arg0->getSourceRange();
7180     TheCall->setArg(0, FirstArg.get());
7181 
7182     // Derive the return type from the pointer argument.
7183     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
7184       TheCall->setType(FirstArgType);
7185     return false;
7186   }
7187 
7188   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
7189     Expr *ArgA = TheCall->getArg(0);
7190     Expr *ArgB = TheCall->getArg(1);
7191 
7192     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
7193     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
7194 
7195     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
7196       return true;
7197 
7198     QualType ArgTypeA = ArgExprA.get()->getType();
7199     QualType ArgTypeB = ArgExprB.get()->getType();
7200 
7201     auto isNull = [&] (Expr *E) -> bool {
7202       return E->isNullPointerConstant(
7203                         Context, Expr::NPC_ValueDependentIsNotNull); };
7204 
7205     // argument should be either a pointer or null
7206     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
7207       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7208         << "first" << ArgTypeA << ArgA->getSourceRange();
7209 
7210     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
7211       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
7212         << "second" << ArgTypeB << ArgB->getSourceRange();
7213 
7214     // Ensure Pointee types are compatible
7215     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
7216         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
7217       QualType pointeeA = ArgTypeA->getPointeeType();
7218       QualType pointeeB = ArgTypeB->getPointeeType();
7219       if (!Context.typesAreCompatible(
7220              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
7221              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
7222         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
7223           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
7224           << ArgB->getSourceRange();
7225       }
7226     }
7227 
7228     // at least one argument should be pointer type
7229     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
7230       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
7231         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
7232 
7233     if (isNull(ArgA)) // adopt type of the other pointer
7234       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
7235 
7236     if (isNull(ArgB))
7237       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
7238 
7239     TheCall->setArg(0, ArgExprA.get());
7240     TheCall->setArg(1, ArgExprB.get());
7241     TheCall->setType(Context.LongLongTy);
7242     return false;
7243   }
7244   assert(false && "Unhandled ARM MTE intrinsic");
7245   return true;
7246 }
7247 
7248 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
7249 /// TheCall is an ARM/AArch64 special register string literal.
7250 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
7251                                     int ArgNum, unsigned ExpectedFieldNum,
7252                                     bool AllowName) {
7253   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
7254                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
7255                       BuiltinID == ARM::BI__builtin_arm_rsr ||
7256                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
7257                       BuiltinID == ARM::BI__builtin_arm_wsr ||
7258                       BuiltinID == ARM::BI__builtin_arm_wsrp;
7259   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
7260                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
7261                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
7262                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
7263                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
7264                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
7265   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
7266 
7267   // We can't check the value of a dependent argument.
7268   Expr *Arg = TheCall->getArg(ArgNum);
7269   if (Arg->isTypeDependent() || Arg->isValueDependent())
7270     return false;
7271 
7272   // Check if the argument is a string literal.
7273   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
7274     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
7275            << Arg->getSourceRange();
7276 
7277   // Check the type of special register given.
7278   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
7279   SmallVector<StringRef, 6> Fields;
7280   Reg.split(Fields, ":");
7281 
7282   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
7283     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7284            << Arg->getSourceRange();
7285 
7286   // If the string is the name of a register then we cannot check that it is
7287   // valid here but if the string is of one the forms described in ACLE then we
7288   // can check that the supplied fields are integers and within the valid
7289   // ranges.
7290   if (Fields.size() > 1) {
7291     bool FiveFields = Fields.size() == 5;
7292 
7293     bool ValidString = true;
7294     if (IsARMBuiltin) {
7295       ValidString &= Fields[0].startswith_insensitive("cp") ||
7296                      Fields[0].startswith_insensitive("p");
7297       if (ValidString)
7298         Fields[0] = Fields[0].drop_front(
7299             Fields[0].startswith_insensitive("cp") ? 2 : 1);
7300 
7301       ValidString &= Fields[2].startswith_insensitive("c");
7302       if (ValidString)
7303         Fields[2] = Fields[2].drop_front(1);
7304 
7305       if (FiveFields) {
7306         ValidString &= Fields[3].startswith_insensitive("c");
7307         if (ValidString)
7308           Fields[3] = Fields[3].drop_front(1);
7309       }
7310     }
7311 
7312     SmallVector<int, 5> Ranges;
7313     if (FiveFields)
7314       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
7315     else
7316       Ranges.append({15, 7, 15});
7317 
7318     for (unsigned i=0; i<Fields.size(); ++i) {
7319       int IntField;
7320       ValidString &= !Fields[i].getAsInteger(10, IntField);
7321       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
7322     }
7323 
7324     if (!ValidString)
7325       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
7326              << Arg->getSourceRange();
7327   } else if (IsAArch64Builtin && Fields.size() == 1) {
7328     // If the register name is one of those that appear in the condition below
7329     // and the special register builtin being used is one of the write builtins,
7330     // then we require that the argument provided for writing to the register
7331     // is an integer constant expression. This is because it will be lowered to
7332     // an MSR (immediate) instruction, so we need to know the immediate at
7333     // compile time.
7334     if (TheCall->getNumArgs() != 2)
7335       return false;
7336 
7337     std::string RegLower = Reg.lower();
7338     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
7339         RegLower != "pan" && RegLower != "uao")
7340       return false;
7341 
7342     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
7343   }
7344 
7345   return false;
7346 }
7347 
7348 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
7349 /// Emit an error and return true on failure; return false on success.
7350 /// TypeStr is a string containing the type descriptor of the value returned by
7351 /// the builtin and the descriptors of the expected type of the arguments.
7352 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, unsigned BuiltinID,
7353                                  const char *TypeStr) {
7354 
7355   assert((TypeStr[0] != '\0') &&
7356          "Invalid types in PPC MMA builtin declaration");
7357 
7358   switch (BuiltinID) {
7359   default:
7360     // This function is called in CheckPPCBuiltinFunctionCall where the
7361     // BuiltinID is guaranteed to be an MMA or pair vector memop builtin, here
7362     // we are isolating the pair vector memop builtins that can be used with mma
7363     // off so the default case is every builtin that requires mma and paired
7364     // vector memops.
7365     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7366                          diag::err_ppc_builtin_only_on_arch, "10") ||
7367         SemaFeatureCheck(*this, TheCall, "mma",
7368                          diag::err_ppc_builtin_only_on_arch, "10"))
7369       return true;
7370     break;
7371   case PPC::BI__builtin_vsx_lxvp:
7372   case PPC::BI__builtin_vsx_stxvp:
7373   case PPC::BI__builtin_vsx_assemble_pair:
7374   case PPC::BI__builtin_vsx_disassemble_pair:
7375     if (SemaFeatureCheck(*this, TheCall, "paired-vector-memops",
7376                          diag::err_ppc_builtin_only_on_arch, "10"))
7377       return true;
7378     break;
7379   }
7380 
7381   unsigned Mask = 0;
7382   unsigned ArgNum = 0;
7383 
7384   // The first type in TypeStr is the type of the value returned by the
7385   // builtin. So we first read that type and change the type of TheCall.
7386   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7387   TheCall->setType(type);
7388 
7389   while (*TypeStr != '\0') {
7390     Mask = 0;
7391     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7392     if (ArgNum >= TheCall->getNumArgs()) {
7393       ArgNum++;
7394       break;
7395     }
7396 
7397     Expr *Arg = TheCall->getArg(ArgNum);
7398     QualType PassedType = Arg->getType();
7399     QualType StrippedRVType = PassedType.getCanonicalType();
7400 
7401     // Strip Restrict/Volatile qualifiers.
7402     if (StrippedRVType.isRestrictQualified() ||
7403         StrippedRVType.isVolatileQualified())
7404       StrippedRVType = StrippedRVType.getCanonicalType().getUnqualifiedType();
7405 
7406     // The only case where the argument type and expected type are allowed to
7407     // mismatch is if the argument type is a non-void pointer and expected type
7408     // is a void pointer.
7409     if (StrippedRVType != ExpectedType)
7410       if (!(ExpectedType->isVoidPointerType() &&
7411             StrippedRVType->isPointerType()))
7412         return Diag(Arg->getBeginLoc(),
7413                     diag::err_typecheck_convert_incompatible)
7414                << PassedType << ExpectedType << 1 << 0 << 0;
7415 
7416     // If the value of the Mask is not 0, we have a constraint in the size of
7417     // the integer argument so here we ensure the argument is a constant that
7418     // is in the valid range.
7419     if (Mask != 0 &&
7420         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
7421       return true;
7422 
7423     ArgNum++;
7424   }
7425 
7426   // In case we exited early from the previous loop, there are other types to
7427   // read from TypeStr. So we need to read them all to ensure we have the right
7428   // number of arguments in TheCall and if it is not the case, to display a
7429   // better error message.
7430   while (*TypeStr != '\0') {
7431     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
7432     ArgNum++;
7433   }
7434   if (checkArgCount(*this, TheCall, ArgNum))
7435     return true;
7436 
7437   return false;
7438 }
7439 
7440 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
7441 /// This checks that the target supports __builtin_longjmp and
7442 /// that val is a constant 1.
7443 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
7444   if (!Context.getTargetInfo().hasSjLjLowering())
7445     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
7446            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7447 
7448   Expr *Arg = TheCall->getArg(1);
7449   llvm::APSInt Result;
7450 
7451   // TODO: This is less than ideal. Overload this to take a value.
7452   if (SemaBuiltinConstantArg(TheCall, 1, Result))
7453     return true;
7454 
7455   if (Result != 1)
7456     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
7457            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
7458 
7459   return false;
7460 }
7461 
7462 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
7463 /// This checks that the target supports __builtin_setjmp.
7464 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
7465   if (!Context.getTargetInfo().hasSjLjLowering())
7466     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
7467            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
7468   return false;
7469 }
7470 
7471 namespace {
7472 
7473 class UncoveredArgHandler {
7474   enum { Unknown = -1, AllCovered = -2 };
7475 
7476   signed FirstUncoveredArg = Unknown;
7477   SmallVector<const Expr *, 4> DiagnosticExprs;
7478 
7479 public:
7480   UncoveredArgHandler() = default;
7481 
7482   bool hasUncoveredArg() const {
7483     return (FirstUncoveredArg >= 0);
7484   }
7485 
7486   unsigned getUncoveredArg() const {
7487     assert(hasUncoveredArg() && "no uncovered argument");
7488     return FirstUncoveredArg;
7489   }
7490 
7491   void setAllCovered() {
7492     // A string has been found with all arguments covered, so clear out
7493     // the diagnostics.
7494     DiagnosticExprs.clear();
7495     FirstUncoveredArg = AllCovered;
7496   }
7497 
7498   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
7499     assert(NewFirstUncoveredArg >= 0 && "Outside range");
7500 
7501     // Don't update if a previous string covers all arguments.
7502     if (FirstUncoveredArg == AllCovered)
7503       return;
7504 
7505     // UncoveredArgHandler tracks the highest uncovered argument index
7506     // and with it all the strings that match this index.
7507     if (NewFirstUncoveredArg == FirstUncoveredArg)
7508       DiagnosticExprs.push_back(StrExpr);
7509     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
7510       DiagnosticExprs.clear();
7511       DiagnosticExprs.push_back(StrExpr);
7512       FirstUncoveredArg = NewFirstUncoveredArg;
7513     }
7514   }
7515 
7516   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
7517 };
7518 
7519 enum StringLiteralCheckType {
7520   SLCT_NotALiteral,
7521   SLCT_UncheckedLiteral,
7522   SLCT_CheckedLiteral
7523 };
7524 
7525 } // namespace
7526 
7527 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
7528                                      BinaryOperatorKind BinOpKind,
7529                                      bool AddendIsRight) {
7530   unsigned BitWidth = Offset.getBitWidth();
7531   unsigned AddendBitWidth = Addend.getBitWidth();
7532   // There might be negative interim results.
7533   if (Addend.isUnsigned()) {
7534     Addend = Addend.zext(++AddendBitWidth);
7535     Addend.setIsSigned(true);
7536   }
7537   // Adjust the bit width of the APSInts.
7538   if (AddendBitWidth > BitWidth) {
7539     Offset = Offset.sext(AddendBitWidth);
7540     BitWidth = AddendBitWidth;
7541   } else if (BitWidth > AddendBitWidth) {
7542     Addend = Addend.sext(BitWidth);
7543   }
7544 
7545   bool Ov = false;
7546   llvm::APSInt ResOffset = Offset;
7547   if (BinOpKind == BO_Add)
7548     ResOffset = Offset.sadd_ov(Addend, Ov);
7549   else {
7550     assert(AddendIsRight && BinOpKind == BO_Sub &&
7551            "operator must be add or sub with addend on the right");
7552     ResOffset = Offset.ssub_ov(Addend, Ov);
7553   }
7554 
7555   // We add an offset to a pointer here so we should support an offset as big as
7556   // possible.
7557   if (Ov) {
7558     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
7559            "index (intermediate) result too big");
7560     Offset = Offset.sext(2 * BitWidth);
7561     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
7562     return;
7563   }
7564 
7565   Offset = ResOffset;
7566 }
7567 
7568 namespace {
7569 
7570 // This is a wrapper class around StringLiteral to support offsetted string
7571 // literals as format strings. It takes the offset into account when returning
7572 // the string and its length or the source locations to display notes correctly.
7573 class FormatStringLiteral {
7574   const StringLiteral *FExpr;
7575   int64_t Offset;
7576 
7577  public:
7578   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
7579       : FExpr(fexpr), Offset(Offset) {}
7580 
7581   StringRef getString() const {
7582     return FExpr->getString().drop_front(Offset);
7583   }
7584 
7585   unsigned getByteLength() const {
7586     return FExpr->getByteLength() - getCharByteWidth() * Offset;
7587   }
7588 
7589   unsigned getLength() const { return FExpr->getLength() - Offset; }
7590   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7591 
7592   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7593 
7594   QualType getType() const { return FExpr->getType(); }
7595 
7596   bool isAscii() const { return FExpr->isAscii(); }
7597   bool isWide() const { return FExpr->isWide(); }
7598   bool isUTF8() const { return FExpr->isUTF8(); }
7599   bool isUTF16() const { return FExpr->isUTF16(); }
7600   bool isUTF32() const { return FExpr->isUTF32(); }
7601   bool isPascal() const { return FExpr->isPascal(); }
7602 
7603   SourceLocation getLocationOfByte(
7604       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7605       const TargetInfo &Target, unsigned *StartToken = nullptr,
7606       unsigned *StartTokenByteOffset = nullptr) const {
7607     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7608                                     StartToken, StartTokenByteOffset);
7609   }
7610 
7611   SourceLocation getBeginLoc() const LLVM_READONLY {
7612     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7613   }
7614 
7615   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7616 };
7617 
7618 }  // namespace
7619 
7620 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7621                               const Expr *OrigFormatExpr,
7622                               ArrayRef<const Expr *> Args,
7623                               bool HasVAListArg, unsigned format_idx,
7624                               unsigned firstDataArg,
7625                               Sema::FormatStringType Type,
7626                               bool inFunctionCall,
7627                               Sema::VariadicCallType CallType,
7628                               llvm::SmallBitVector &CheckedVarArgs,
7629                               UncoveredArgHandler &UncoveredArg,
7630                               bool IgnoreStringsWithoutSpecifiers);
7631 
7632 // Determine if an expression is a string literal or constant string.
7633 // If this function returns false on the arguments to a function expecting a
7634 // format string, we will usually need to emit a warning.
7635 // True string literals are then checked by CheckFormatString.
7636 static StringLiteralCheckType
7637 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7638                       bool HasVAListArg, unsigned format_idx,
7639                       unsigned firstDataArg, Sema::FormatStringType Type,
7640                       Sema::VariadicCallType CallType, bool InFunctionCall,
7641                       llvm::SmallBitVector &CheckedVarArgs,
7642                       UncoveredArgHandler &UncoveredArg,
7643                       llvm::APSInt Offset,
7644                       bool IgnoreStringsWithoutSpecifiers = false) {
7645   if (S.isConstantEvaluated())
7646     return SLCT_NotALiteral;
7647  tryAgain:
7648   assert(Offset.isSigned() && "invalid offset");
7649 
7650   if (E->isTypeDependent() || E->isValueDependent())
7651     return SLCT_NotALiteral;
7652 
7653   E = E->IgnoreParenCasts();
7654 
7655   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7656     // Technically -Wformat-nonliteral does not warn about this case.
7657     // The behavior of printf and friends in this case is implementation
7658     // dependent.  Ideally if the format string cannot be null then
7659     // it should have a 'nonnull' attribute in the function prototype.
7660     return SLCT_UncheckedLiteral;
7661 
7662   switch (E->getStmtClass()) {
7663   case Stmt::BinaryConditionalOperatorClass:
7664   case Stmt::ConditionalOperatorClass: {
7665     // The expression is a literal if both sub-expressions were, and it was
7666     // completely checked only if both sub-expressions were checked.
7667     const AbstractConditionalOperator *C =
7668         cast<AbstractConditionalOperator>(E);
7669 
7670     // Determine whether it is necessary to check both sub-expressions, for
7671     // example, because the condition expression is a constant that can be
7672     // evaluated at compile time.
7673     bool CheckLeft = true, CheckRight = true;
7674 
7675     bool Cond;
7676     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7677                                                  S.isConstantEvaluated())) {
7678       if (Cond)
7679         CheckRight = false;
7680       else
7681         CheckLeft = false;
7682     }
7683 
7684     // We need to maintain the offsets for the right and the left hand side
7685     // separately to check if every possible indexed expression is a valid
7686     // string literal. They might have different offsets for different string
7687     // literals in the end.
7688     StringLiteralCheckType Left;
7689     if (!CheckLeft)
7690       Left = SLCT_UncheckedLiteral;
7691     else {
7692       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7693                                    HasVAListArg, format_idx, firstDataArg,
7694                                    Type, CallType, InFunctionCall,
7695                                    CheckedVarArgs, UncoveredArg, Offset,
7696                                    IgnoreStringsWithoutSpecifiers);
7697       if (Left == SLCT_NotALiteral || !CheckRight) {
7698         return Left;
7699       }
7700     }
7701 
7702     StringLiteralCheckType Right = checkFormatStringExpr(
7703         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7704         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7705         IgnoreStringsWithoutSpecifiers);
7706 
7707     return (CheckLeft && Left < Right) ? Left : Right;
7708   }
7709 
7710   case Stmt::ImplicitCastExprClass:
7711     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7712     goto tryAgain;
7713 
7714   case Stmt::OpaqueValueExprClass:
7715     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7716       E = src;
7717       goto tryAgain;
7718     }
7719     return SLCT_NotALiteral;
7720 
7721   case Stmt::PredefinedExprClass:
7722     // While __func__, etc., are technically not string literals, they
7723     // cannot contain format specifiers and thus are not a security
7724     // liability.
7725     return SLCT_UncheckedLiteral;
7726 
7727   case Stmt::DeclRefExprClass: {
7728     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7729 
7730     // As an exception, do not flag errors for variables binding to
7731     // const string literals.
7732     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7733       bool isConstant = false;
7734       QualType T = DR->getType();
7735 
7736       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7737         isConstant = AT->getElementType().isConstant(S.Context);
7738       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7739         isConstant = T.isConstant(S.Context) &&
7740                      PT->getPointeeType().isConstant(S.Context);
7741       } else if (T->isObjCObjectPointerType()) {
7742         // In ObjC, there is usually no "const ObjectPointer" type,
7743         // so don't check if the pointee type is constant.
7744         isConstant = T.isConstant(S.Context);
7745       }
7746 
7747       if (isConstant) {
7748         if (const Expr *Init = VD->getAnyInitializer()) {
7749           // Look through initializers like const char c[] = { "foo" }
7750           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7751             if (InitList->isStringLiteralInit())
7752               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7753           }
7754           return checkFormatStringExpr(S, Init, Args,
7755                                        HasVAListArg, format_idx,
7756                                        firstDataArg, Type, CallType,
7757                                        /*InFunctionCall*/ false, CheckedVarArgs,
7758                                        UncoveredArg, Offset);
7759         }
7760       }
7761 
7762       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7763       // special check to see if the format string is a function parameter
7764       // of the function calling the printf function.  If the function
7765       // has an attribute indicating it is a printf-like function, then we
7766       // should suppress warnings concerning non-literals being used in a call
7767       // to a vprintf function.  For example:
7768       //
7769       // void
7770       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7771       //      va_list ap;
7772       //      va_start(ap, fmt);
7773       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7774       //      ...
7775       // }
7776       if (HasVAListArg) {
7777         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7778           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7779             int PVIndex = PV->getFunctionScopeIndex() + 1;
7780             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7781               // adjust for implicit parameter
7782               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7783                 if (MD->isInstance())
7784                   ++PVIndex;
7785               // We also check if the formats are compatible.
7786               // We can't pass a 'scanf' string to a 'printf' function.
7787               if (PVIndex == PVFormat->getFormatIdx() &&
7788                   Type == S.GetFormatStringType(PVFormat))
7789                 return SLCT_UncheckedLiteral;
7790             }
7791           }
7792         }
7793       }
7794     }
7795 
7796     return SLCT_NotALiteral;
7797   }
7798 
7799   case Stmt::CallExprClass:
7800   case Stmt::CXXMemberCallExprClass: {
7801     const CallExpr *CE = cast<CallExpr>(E);
7802     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7803       bool IsFirst = true;
7804       StringLiteralCheckType CommonResult;
7805       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7806         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7807         StringLiteralCheckType Result = checkFormatStringExpr(
7808             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7809             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7810             IgnoreStringsWithoutSpecifiers);
7811         if (IsFirst) {
7812           CommonResult = Result;
7813           IsFirst = false;
7814         }
7815       }
7816       if (!IsFirst)
7817         return CommonResult;
7818 
7819       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7820         unsigned BuiltinID = FD->getBuiltinID();
7821         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7822             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7823           const Expr *Arg = CE->getArg(0);
7824           return checkFormatStringExpr(S, Arg, Args,
7825                                        HasVAListArg, format_idx,
7826                                        firstDataArg, Type, CallType,
7827                                        InFunctionCall, CheckedVarArgs,
7828                                        UncoveredArg, Offset,
7829                                        IgnoreStringsWithoutSpecifiers);
7830         }
7831       }
7832     }
7833 
7834     return SLCT_NotALiteral;
7835   }
7836   case Stmt::ObjCMessageExprClass: {
7837     const auto *ME = cast<ObjCMessageExpr>(E);
7838     if (const auto *MD = ME->getMethodDecl()) {
7839       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7840         // As a special case heuristic, if we're using the method -[NSBundle
7841         // localizedStringForKey:value:table:], ignore any key strings that lack
7842         // format specifiers. The idea is that if the key doesn't have any
7843         // format specifiers then its probably just a key to map to the
7844         // localized strings. If it does have format specifiers though, then its
7845         // likely that the text of the key is the format string in the
7846         // programmer's language, and should be checked.
7847         const ObjCInterfaceDecl *IFace;
7848         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7849             IFace->getIdentifier()->isStr("NSBundle") &&
7850             MD->getSelector().isKeywordSelector(
7851                 {"localizedStringForKey", "value", "table"})) {
7852           IgnoreStringsWithoutSpecifiers = true;
7853         }
7854 
7855         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7856         return checkFormatStringExpr(
7857             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7858             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7859             IgnoreStringsWithoutSpecifiers);
7860       }
7861     }
7862 
7863     return SLCT_NotALiteral;
7864   }
7865   case Stmt::ObjCStringLiteralClass:
7866   case Stmt::StringLiteralClass: {
7867     const StringLiteral *StrE = nullptr;
7868 
7869     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7870       StrE = ObjCFExpr->getString();
7871     else
7872       StrE = cast<StringLiteral>(E);
7873 
7874     if (StrE) {
7875       if (Offset.isNegative() || Offset > StrE->getLength()) {
7876         // TODO: It would be better to have an explicit warning for out of
7877         // bounds literals.
7878         return SLCT_NotALiteral;
7879       }
7880       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7881       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7882                         firstDataArg, Type, InFunctionCall, CallType,
7883                         CheckedVarArgs, UncoveredArg,
7884                         IgnoreStringsWithoutSpecifiers);
7885       return SLCT_CheckedLiteral;
7886     }
7887 
7888     return SLCT_NotALiteral;
7889   }
7890   case Stmt::BinaryOperatorClass: {
7891     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7892 
7893     // A string literal + an int offset is still a string literal.
7894     if (BinOp->isAdditiveOp()) {
7895       Expr::EvalResult LResult, RResult;
7896 
7897       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7898           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7899       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7900           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7901 
7902       if (LIsInt != RIsInt) {
7903         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7904 
7905         if (LIsInt) {
7906           if (BinOpKind == BO_Add) {
7907             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7908             E = BinOp->getRHS();
7909             goto tryAgain;
7910           }
7911         } else {
7912           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7913           E = BinOp->getLHS();
7914           goto tryAgain;
7915         }
7916       }
7917     }
7918 
7919     return SLCT_NotALiteral;
7920   }
7921   case Stmt::UnaryOperatorClass: {
7922     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7923     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7924     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7925       Expr::EvalResult IndexResult;
7926       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7927                                        Expr::SE_NoSideEffects,
7928                                        S.isConstantEvaluated())) {
7929         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7930                    /*RHS is int*/ true);
7931         E = ASE->getBase();
7932         goto tryAgain;
7933       }
7934     }
7935 
7936     return SLCT_NotALiteral;
7937   }
7938 
7939   default:
7940     return SLCT_NotALiteral;
7941   }
7942 }
7943 
7944 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7945   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7946       .Case("scanf", FST_Scanf)
7947       .Cases("printf", "printf0", FST_Printf)
7948       .Cases("NSString", "CFString", FST_NSString)
7949       .Case("strftime", FST_Strftime)
7950       .Case("strfmon", FST_Strfmon)
7951       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7952       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7953       .Case("os_trace", FST_OSLog)
7954       .Case("os_log", FST_OSLog)
7955       .Default(FST_Unknown);
7956 }
7957 
7958 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7959 /// functions) for correct use of format strings.
7960 /// Returns true if a format string has been fully checked.
7961 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7962                                 ArrayRef<const Expr *> Args,
7963                                 bool IsCXXMember,
7964                                 VariadicCallType CallType,
7965                                 SourceLocation Loc, SourceRange Range,
7966                                 llvm::SmallBitVector &CheckedVarArgs) {
7967   FormatStringInfo FSI;
7968   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7969     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7970                                 FSI.FirstDataArg, GetFormatStringType(Format),
7971                                 CallType, Loc, Range, CheckedVarArgs);
7972   return false;
7973 }
7974 
7975 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7976                                 bool HasVAListArg, unsigned format_idx,
7977                                 unsigned firstDataArg, FormatStringType Type,
7978                                 VariadicCallType CallType,
7979                                 SourceLocation Loc, SourceRange Range,
7980                                 llvm::SmallBitVector &CheckedVarArgs) {
7981   // CHECK: printf/scanf-like function is called with no format string.
7982   if (format_idx >= Args.size()) {
7983     Diag(Loc, diag::warn_missing_format_string) << Range;
7984     return false;
7985   }
7986 
7987   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7988 
7989   // CHECK: format string is not a string literal.
7990   //
7991   // Dynamically generated format strings are difficult to
7992   // automatically vet at compile time.  Requiring that format strings
7993   // are string literals: (1) permits the checking of format strings by
7994   // the compiler and thereby (2) can practically remove the source of
7995   // many format string exploits.
7996 
7997   // Format string can be either ObjC string (e.g. @"%d") or
7998   // C string (e.g. "%d")
7999   // ObjC string uses the same format specifiers as C string, so we can use
8000   // the same format string checking logic for both ObjC and C strings.
8001   UncoveredArgHandler UncoveredArg;
8002   StringLiteralCheckType CT =
8003       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
8004                             format_idx, firstDataArg, Type, CallType,
8005                             /*IsFunctionCall*/ true, CheckedVarArgs,
8006                             UncoveredArg,
8007                             /*no string offset*/ llvm::APSInt(64, false) = 0);
8008 
8009   // Generate a diagnostic where an uncovered argument is detected.
8010   if (UncoveredArg.hasUncoveredArg()) {
8011     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
8012     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
8013     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
8014   }
8015 
8016   if (CT != SLCT_NotALiteral)
8017     // Literal format string found, check done!
8018     return CT == SLCT_CheckedLiteral;
8019 
8020   // Strftime is particular as it always uses a single 'time' argument,
8021   // so it is safe to pass a non-literal string.
8022   if (Type == FST_Strftime)
8023     return false;
8024 
8025   // Do not emit diag when the string param is a macro expansion and the
8026   // format is either NSString or CFString. This is a hack to prevent
8027   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
8028   // which are usually used in place of NS and CF string literals.
8029   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
8030   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
8031     return false;
8032 
8033   // If there are no arguments specified, warn with -Wformat-security, otherwise
8034   // warn only with -Wformat-nonliteral.
8035   if (Args.size() == firstDataArg) {
8036     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
8037       << OrigFormatExpr->getSourceRange();
8038     switch (Type) {
8039     default:
8040       break;
8041     case FST_Kprintf:
8042     case FST_FreeBSDKPrintf:
8043     case FST_Printf:
8044       Diag(FormatLoc, diag::note_format_security_fixit)
8045         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
8046       break;
8047     case FST_NSString:
8048       Diag(FormatLoc, diag::note_format_security_fixit)
8049         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
8050       break;
8051     }
8052   } else {
8053     Diag(FormatLoc, diag::warn_format_nonliteral)
8054       << OrigFormatExpr->getSourceRange();
8055   }
8056   return false;
8057 }
8058 
8059 namespace {
8060 
8061 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
8062 protected:
8063   Sema &S;
8064   const FormatStringLiteral *FExpr;
8065   const Expr *OrigFormatExpr;
8066   const Sema::FormatStringType FSType;
8067   const unsigned FirstDataArg;
8068   const unsigned NumDataArgs;
8069   const char *Beg; // Start of format string.
8070   const bool HasVAListArg;
8071   ArrayRef<const Expr *> Args;
8072   unsigned FormatIdx;
8073   llvm::SmallBitVector CoveredArgs;
8074   bool usesPositionalArgs = false;
8075   bool atFirstArg = true;
8076   bool inFunctionCall;
8077   Sema::VariadicCallType CallType;
8078   llvm::SmallBitVector &CheckedVarArgs;
8079   UncoveredArgHandler &UncoveredArg;
8080 
8081 public:
8082   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
8083                      const Expr *origFormatExpr,
8084                      const Sema::FormatStringType type, unsigned firstDataArg,
8085                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
8086                      ArrayRef<const Expr *> Args, unsigned formatIdx,
8087                      bool inFunctionCall, Sema::VariadicCallType callType,
8088                      llvm::SmallBitVector &CheckedVarArgs,
8089                      UncoveredArgHandler &UncoveredArg)
8090       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
8091         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
8092         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
8093         inFunctionCall(inFunctionCall), CallType(callType),
8094         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
8095     CoveredArgs.resize(numDataArgs);
8096     CoveredArgs.reset();
8097   }
8098 
8099   void DoneProcessing();
8100 
8101   void HandleIncompleteSpecifier(const char *startSpecifier,
8102                                  unsigned specifierLen) override;
8103 
8104   void HandleInvalidLengthModifier(
8105                            const analyze_format_string::FormatSpecifier &FS,
8106                            const analyze_format_string::ConversionSpecifier &CS,
8107                            const char *startSpecifier, unsigned specifierLen,
8108                            unsigned DiagID);
8109 
8110   void HandleNonStandardLengthModifier(
8111                     const analyze_format_string::FormatSpecifier &FS,
8112                     const char *startSpecifier, unsigned specifierLen);
8113 
8114   void HandleNonStandardConversionSpecifier(
8115                     const analyze_format_string::ConversionSpecifier &CS,
8116                     const char *startSpecifier, unsigned specifierLen);
8117 
8118   void HandlePosition(const char *startPos, unsigned posLen) override;
8119 
8120   void HandleInvalidPosition(const char *startSpecifier,
8121                              unsigned specifierLen,
8122                              analyze_format_string::PositionContext p) override;
8123 
8124   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
8125 
8126   void HandleNullChar(const char *nullCharacter) override;
8127 
8128   template <typename Range>
8129   static void
8130   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
8131                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
8132                        bool IsStringLocation, Range StringRange,
8133                        ArrayRef<FixItHint> Fixit = None);
8134 
8135 protected:
8136   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
8137                                         const char *startSpec,
8138                                         unsigned specifierLen,
8139                                         const char *csStart, unsigned csLen);
8140 
8141   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
8142                                          const char *startSpec,
8143                                          unsigned specifierLen);
8144 
8145   SourceRange getFormatStringRange();
8146   CharSourceRange getSpecifierRange(const char *startSpecifier,
8147                                     unsigned specifierLen);
8148   SourceLocation getLocationOfByte(const char *x);
8149 
8150   const Expr *getDataArg(unsigned i) const;
8151 
8152   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
8153                     const analyze_format_string::ConversionSpecifier &CS,
8154                     const char *startSpecifier, unsigned specifierLen,
8155                     unsigned argIndex);
8156 
8157   template <typename Range>
8158   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
8159                             bool IsStringLocation, Range StringRange,
8160                             ArrayRef<FixItHint> Fixit = None);
8161 };
8162 
8163 } // namespace
8164 
8165 SourceRange CheckFormatHandler::getFormatStringRange() {
8166   return OrigFormatExpr->getSourceRange();
8167 }
8168 
8169 CharSourceRange CheckFormatHandler::
8170 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
8171   SourceLocation Start = getLocationOfByte(startSpecifier);
8172   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
8173 
8174   // Advance the end SourceLocation by one due to half-open ranges.
8175   End = End.getLocWithOffset(1);
8176 
8177   return CharSourceRange::getCharRange(Start, End);
8178 }
8179 
8180 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
8181   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
8182                                   S.getLangOpts(), S.Context.getTargetInfo());
8183 }
8184 
8185 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
8186                                                    unsigned specifierLen){
8187   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
8188                        getLocationOfByte(startSpecifier),
8189                        /*IsStringLocation*/true,
8190                        getSpecifierRange(startSpecifier, specifierLen));
8191 }
8192 
8193 void CheckFormatHandler::HandleInvalidLengthModifier(
8194     const analyze_format_string::FormatSpecifier &FS,
8195     const analyze_format_string::ConversionSpecifier &CS,
8196     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
8197   using namespace analyze_format_string;
8198 
8199   const LengthModifier &LM = FS.getLengthModifier();
8200   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8201 
8202   // See if we know how to fix this length modifier.
8203   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8204   if (FixedLM) {
8205     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8206                          getLocationOfByte(LM.getStart()),
8207                          /*IsStringLocation*/true,
8208                          getSpecifierRange(startSpecifier, specifierLen));
8209 
8210     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8211       << FixedLM->toString()
8212       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8213 
8214   } else {
8215     FixItHint Hint;
8216     if (DiagID == diag::warn_format_nonsensical_length)
8217       Hint = FixItHint::CreateRemoval(LMRange);
8218 
8219     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
8220                          getLocationOfByte(LM.getStart()),
8221                          /*IsStringLocation*/true,
8222                          getSpecifierRange(startSpecifier, specifierLen),
8223                          Hint);
8224   }
8225 }
8226 
8227 void CheckFormatHandler::HandleNonStandardLengthModifier(
8228     const analyze_format_string::FormatSpecifier &FS,
8229     const char *startSpecifier, unsigned specifierLen) {
8230   using namespace analyze_format_string;
8231 
8232   const LengthModifier &LM = FS.getLengthModifier();
8233   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
8234 
8235   // See if we know how to fix this length modifier.
8236   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
8237   if (FixedLM) {
8238     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8239                            << LM.toString() << 0,
8240                          getLocationOfByte(LM.getStart()),
8241                          /*IsStringLocation*/true,
8242                          getSpecifierRange(startSpecifier, specifierLen));
8243 
8244     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
8245       << FixedLM->toString()
8246       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
8247 
8248   } else {
8249     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8250                            << LM.toString() << 0,
8251                          getLocationOfByte(LM.getStart()),
8252                          /*IsStringLocation*/true,
8253                          getSpecifierRange(startSpecifier, specifierLen));
8254   }
8255 }
8256 
8257 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
8258     const analyze_format_string::ConversionSpecifier &CS,
8259     const char *startSpecifier, unsigned specifierLen) {
8260   using namespace analyze_format_string;
8261 
8262   // See if we know how to fix this conversion specifier.
8263   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
8264   if (FixedCS) {
8265     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8266                           << CS.toString() << /*conversion specifier*/1,
8267                          getLocationOfByte(CS.getStart()),
8268                          /*IsStringLocation*/true,
8269                          getSpecifierRange(startSpecifier, specifierLen));
8270 
8271     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
8272     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
8273       << FixedCS->toString()
8274       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
8275   } else {
8276     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
8277                           << CS.toString() << /*conversion specifier*/1,
8278                          getLocationOfByte(CS.getStart()),
8279                          /*IsStringLocation*/true,
8280                          getSpecifierRange(startSpecifier, specifierLen));
8281   }
8282 }
8283 
8284 void CheckFormatHandler::HandlePosition(const char *startPos,
8285                                         unsigned posLen) {
8286   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
8287                                getLocationOfByte(startPos),
8288                                /*IsStringLocation*/true,
8289                                getSpecifierRange(startPos, posLen));
8290 }
8291 
8292 void
8293 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
8294                                      analyze_format_string::PositionContext p) {
8295   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
8296                          << (unsigned) p,
8297                        getLocationOfByte(startPos), /*IsStringLocation*/true,
8298                        getSpecifierRange(startPos, posLen));
8299 }
8300 
8301 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
8302                                             unsigned posLen) {
8303   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
8304                                getLocationOfByte(startPos),
8305                                /*IsStringLocation*/true,
8306                                getSpecifierRange(startPos, posLen));
8307 }
8308 
8309 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
8310   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
8311     // The presence of a null character is likely an error.
8312     EmitFormatDiagnostic(
8313       S.PDiag(diag::warn_printf_format_string_contains_null_char),
8314       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
8315       getFormatStringRange());
8316   }
8317 }
8318 
8319 // Note that this may return NULL if there was an error parsing or building
8320 // one of the argument expressions.
8321 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
8322   return Args[FirstDataArg + i];
8323 }
8324 
8325 void CheckFormatHandler::DoneProcessing() {
8326   // Does the number of data arguments exceed the number of
8327   // format conversions in the format string?
8328   if (!HasVAListArg) {
8329       // Find any arguments that weren't covered.
8330     CoveredArgs.flip();
8331     signed notCoveredArg = CoveredArgs.find_first();
8332     if (notCoveredArg >= 0) {
8333       assert((unsigned)notCoveredArg < NumDataArgs);
8334       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
8335     } else {
8336       UncoveredArg.setAllCovered();
8337     }
8338   }
8339 }
8340 
8341 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
8342                                    const Expr *ArgExpr) {
8343   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
8344          "Invalid state");
8345 
8346   if (!ArgExpr)
8347     return;
8348 
8349   SourceLocation Loc = ArgExpr->getBeginLoc();
8350 
8351   if (S.getSourceManager().isInSystemMacro(Loc))
8352     return;
8353 
8354   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
8355   for (auto E : DiagnosticExprs)
8356     PDiag << E->getSourceRange();
8357 
8358   CheckFormatHandler::EmitFormatDiagnostic(
8359                                   S, IsFunctionCall, DiagnosticExprs[0],
8360                                   PDiag, Loc, /*IsStringLocation*/false,
8361                                   DiagnosticExprs[0]->getSourceRange());
8362 }
8363 
8364 bool
8365 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
8366                                                      SourceLocation Loc,
8367                                                      const char *startSpec,
8368                                                      unsigned specifierLen,
8369                                                      const char *csStart,
8370                                                      unsigned csLen) {
8371   bool keepGoing = true;
8372   if (argIndex < NumDataArgs) {
8373     // Consider the argument coverered, even though the specifier doesn't
8374     // make sense.
8375     CoveredArgs.set(argIndex);
8376   }
8377   else {
8378     // If argIndex exceeds the number of data arguments we
8379     // don't issue a warning because that is just a cascade of warnings (and
8380     // they may have intended '%%' anyway). We don't want to continue processing
8381     // the format string after this point, however, as we will like just get
8382     // gibberish when trying to match arguments.
8383     keepGoing = false;
8384   }
8385 
8386   StringRef Specifier(csStart, csLen);
8387 
8388   // If the specifier in non-printable, it could be the first byte of a UTF-8
8389   // sequence. In that case, print the UTF-8 code point. If not, print the byte
8390   // hex value.
8391   std::string CodePointStr;
8392   if (!llvm::sys::locale::isPrint(*csStart)) {
8393     llvm::UTF32 CodePoint;
8394     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
8395     const llvm::UTF8 *E =
8396         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
8397     llvm::ConversionResult Result =
8398         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
8399 
8400     if (Result != llvm::conversionOK) {
8401       unsigned char FirstChar = *csStart;
8402       CodePoint = (llvm::UTF32)FirstChar;
8403     }
8404 
8405     llvm::raw_string_ostream OS(CodePointStr);
8406     if (CodePoint < 256)
8407       OS << "\\x" << llvm::format("%02x", CodePoint);
8408     else if (CodePoint <= 0xFFFF)
8409       OS << "\\u" << llvm::format("%04x", CodePoint);
8410     else
8411       OS << "\\U" << llvm::format("%08x", CodePoint);
8412     OS.flush();
8413     Specifier = CodePointStr;
8414   }
8415 
8416   EmitFormatDiagnostic(
8417       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
8418       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
8419 
8420   return keepGoing;
8421 }
8422 
8423 void
8424 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
8425                                                       const char *startSpec,
8426                                                       unsigned specifierLen) {
8427   EmitFormatDiagnostic(
8428     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
8429     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
8430 }
8431 
8432 bool
8433 CheckFormatHandler::CheckNumArgs(
8434   const analyze_format_string::FormatSpecifier &FS,
8435   const analyze_format_string::ConversionSpecifier &CS,
8436   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
8437 
8438   if (argIndex >= NumDataArgs) {
8439     PartialDiagnostic PDiag = FS.usesPositionalArg()
8440       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
8441            << (argIndex+1) << NumDataArgs)
8442       : S.PDiag(diag::warn_printf_insufficient_data_args);
8443     EmitFormatDiagnostic(
8444       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
8445       getSpecifierRange(startSpecifier, specifierLen));
8446 
8447     // Since more arguments than conversion tokens are given, by extension
8448     // all arguments are covered, so mark this as so.
8449     UncoveredArg.setAllCovered();
8450     return false;
8451   }
8452   return true;
8453 }
8454 
8455 template<typename Range>
8456 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
8457                                               SourceLocation Loc,
8458                                               bool IsStringLocation,
8459                                               Range StringRange,
8460                                               ArrayRef<FixItHint> FixIt) {
8461   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
8462                        Loc, IsStringLocation, StringRange, FixIt);
8463 }
8464 
8465 /// If the format string is not within the function call, emit a note
8466 /// so that the function call and string are in diagnostic messages.
8467 ///
8468 /// \param InFunctionCall if true, the format string is within the function
8469 /// call and only one diagnostic message will be produced.  Otherwise, an
8470 /// extra note will be emitted pointing to location of the format string.
8471 ///
8472 /// \param ArgumentExpr the expression that is passed as the format string
8473 /// argument in the function call.  Used for getting locations when two
8474 /// diagnostics are emitted.
8475 ///
8476 /// \param PDiag the callee should already have provided any strings for the
8477 /// diagnostic message.  This function only adds locations and fixits
8478 /// to diagnostics.
8479 ///
8480 /// \param Loc primary location for diagnostic.  If two diagnostics are
8481 /// required, one will be at Loc and a new SourceLocation will be created for
8482 /// the other one.
8483 ///
8484 /// \param IsStringLocation if true, Loc points to the format string should be
8485 /// used for the note.  Otherwise, Loc points to the argument list and will
8486 /// be used with PDiag.
8487 ///
8488 /// \param StringRange some or all of the string to highlight.  This is
8489 /// templated so it can accept either a CharSourceRange or a SourceRange.
8490 ///
8491 /// \param FixIt optional fix it hint for the format string.
8492 template <typename Range>
8493 void CheckFormatHandler::EmitFormatDiagnostic(
8494     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
8495     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
8496     Range StringRange, ArrayRef<FixItHint> FixIt) {
8497   if (InFunctionCall) {
8498     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
8499     D << StringRange;
8500     D << FixIt;
8501   } else {
8502     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
8503       << ArgumentExpr->getSourceRange();
8504 
8505     const Sema::SemaDiagnosticBuilder &Note =
8506       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
8507              diag::note_format_string_defined);
8508 
8509     Note << StringRange;
8510     Note << FixIt;
8511   }
8512 }
8513 
8514 //===--- CHECK: Printf format string checking ------------------------------===//
8515 
8516 namespace {
8517 
8518 class CheckPrintfHandler : public CheckFormatHandler {
8519 public:
8520   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
8521                      const Expr *origFormatExpr,
8522                      const Sema::FormatStringType type, unsigned firstDataArg,
8523                      unsigned numDataArgs, bool isObjC, const char *beg,
8524                      bool hasVAListArg, ArrayRef<const Expr *> Args,
8525                      unsigned formatIdx, bool inFunctionCall,
8526                      Sema::VariadicCallType CallType,
8527                      llvm::SmallBitVector &CheckedVarArgs,
8528                      UncoveredArgHandler &UncoveredArg)
8529       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8530                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8531                            inFunctionCall, CallType, CheckedVarArgs,
8532                            UncoveredArg) {}
8533 
8534   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
8535 
8536   /// Returns true if '%@' specifiers are allowed in the format string.
8537   bool allowsObjCArg() const {
8538     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
8539            FSType == Sema::FST_OSTrace;
8540   }
8541 
8542   bool HandleInvalidPrintfConversionSpecifier(
8543                                       const analyze_printf::PrintfSpecifier &FS,
8544                                       const char *startSpecifier,
8545                                       unsigned specifierLen) override;
8546 
8547   void handleInvalidMaskType(StringRef MaskType) override;
8548 
8549   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
8550                              const char *startSpecifier,
8551                              unsigned specifierLen) override;
8552   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8553                        const char *StartSpecifier,
8554                        unsigned SpecifierLen,
8555                        const Expr *E);
8556 
8557   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
8558                     const char *startSpecifier, unsigned specifierLen);
8559   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
8560                            const analyze_printf::OptionalAmount &Amt,
8561                            unsigned type,
8562                            const char *startSpecifier, unsigned specifierLen);
8563   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8564                   const analyze_printf::OptionalFlag &flag,
8565                   const char *startSpecifier, unsigned specifierLen);
8566   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
8567                          const analyze_printf::OptionalFlag &ignoredFlag,
8568                          const analyze_printf::OptionalFlag &flag,
8569                          const char *startSpecifier, unsigned specifierLen);
8570   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
8571                            const Expr *E);
8572 
8573   void HandleEmptyObjCModifierFlag(const char *startFlag,
8574                                    unsigned flagLen) override;
8575 
8576   void HandleInvalidObjCModifierFlag(const char *startFlag,
8577                                             unsigned flagLen) override;
8578 
8579   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
8580                                            const char *flagsEnd,
8581                                            const char *conversionPosition)
8582                                              override;
8583 };
8584 
8585 } // namespace
8586 
8587 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
8588                                       const analyze_printf::PrintfSpecifier &FS,
8589                                       const char *startSpecifier,
8590                                       unsigned specifierLen) {
8591   const analyze_printf::PrintfConversionSpecifier &CS =
8592     FS.getConversionSpecifier();
8593 
8594   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8595                                           getLocationOfByte(CS.getStart()),
8596                                           startSpecifier, specifierLen,
8597                                           CS.getStart(), CS.getLength());
8598 }
8599 
8600 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8601   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8602 }
8603 
8604 bool CheckPrintfHandler::HandleAmount(
8605                                const analyze_format_string::OptionalAmount &Amt,
8606                                unsigned k, const char *startSpecifier,
8607                                unsigned specifierLen) {
8608   if (Amt.hasDataArgument()) {
8609     if (!HasVAListArg) {
8610       unsigned argIndex = Amt.getArgIndex();
8611       if (argIndex >= NumDataArgs) {
8612         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8613                                << k,
8614                              getLocationOfByte(Amt.getStart()),
8615                              /*IsStringLocation*/true,
8616                              getSpecifierRange(startSpecifier, specifierLen));
8617         // Don't do any more checking.  We will just emit
8618         // spurious errors.
8619         return false;
8620       }
8621 
8622       // Type check the data argument.  It should be an 'int'.
8623       // Although not in conformance with C99, we also allow the argument to be
8624       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8625       // doesn't emit a warning for that case.
8626       CoveredArgs.set(argIndex);
8627       const Expr *Arg = getDataArg(argIndex);
8628       if (!Arg)
8629         return false;
8630 
8631       QualType T = Arg->getType();
8632 
8633       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8634       assert(AT.isValid());
8635 
8636       if (!AT.matchesType(S.Context, T)) {
8637         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8638                                << k << AT.getRepresentativeTypeName(S.Context)
8639                                << T << Arg->getSourceRange(),
8640                              getLocationOfByte(Amt.getStart()),
8641                              /*IsStringLocation*/true,
8642                              getSpecifierRange(startSpecifier, specifierLen));
8643         // Don't do any more checking.  We will just emit
8644         // spurious errors.
8645         return false;
8646       }
8647     }
8648   }
8649   return true;
8650 }
8651 
8652 void CheckPrintfHandler::HandleInvalidAmount(
8653                                       const analyze_printf::PrintfSpecifier &FS,
8654                                       const analyze_printf::OptionalAmount &Amt,
8655                                       unsigned type,
8656                                       const char *startSpecifier,
8657                                       unsigned specifierLen) {
8658   const analyze_printf::PrintfConversionSpecifier &CS =
8659     FS.getConversionSpecifier();
8660 
8661   FixItHint fixit =
8662     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8663       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8664                                  Amt.getConstantLength()))
8665       : FixItHint();
8666 
8667   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8668                          << type << CS.toString(),
8669                        getLocationOfByte(Amt.getStart()),
8670                        /*IsStringLocation*/true,
8671                        getSpecifierRange(startSpecifier, specifierLen),
8672                        fixit);
8673 }
8674 
8675 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8676                                     const analyze_printf::OptionalFlag &flag,
8677                                     const char *startSpecifier,
8678                                     unsigned specifierLen) {
8679   // Warn about pointless flag with a fixit removal.
8680   const analyze_printf::PrintfConversionSpecifier &CS =
8681     FS.getConversionSpecifier();
8682   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8683                          << flag.toString() << CS.toString(),
8684                        getLocationOfByte(flag.getPosition()),
8685                        /*IsStringLocation*/true,
8686                        getSpecifierRange(startSpecifier, specifierLen),
8687                        FixItHint::CreateRemoval(
8688                          getSpecifierRange(flag.getPosition(), 1)));
8689 }
8690 
8691 void CheckPrintfHandler::HandleIgnoredFlag(
8692                                 const analyze_printf::PrintfSpecifier &FS,
8693                                 const analyze_printf::OptionalFlag &ignoredFlag,
8694                                 const analyze_printf::OptionalFlag &flag,
8695                                 const char *startSpecifier,
8696                                 unsigned specifierLen) {
8697   // Warn about ignored flag with a fixit removal.
8698   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8699                          << ignoredFlag.toString() << flag.toString(),
8700                        getLocationOfByte(ignoredFlag.getPosition()),
8701                        /*IsStringLocation*/true,
8702                        getSpecifierRange(startSpecifier, specifierLen),
8703                        FixItHint::CreateRemoval(
8704                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8705 }
8706 
8707 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8708                                                      unsigned flagLen) {
8709   // Warn about an empty flag.
8710   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8711                        getLocationOfByte(startFlag),
8712                        /*IsStringLocation*/true,
8713                        getSpecifierRange(startFlag, flagLen));
8714 }
8715 
8716 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8717                                                        unsigned flagLen) {
8718   // Warn about an invalid flag.
8719   auto Range = getSpecifierRange(startFlag, flagLen);
8720   StringRef flag(startFlag, flagLen);
8721   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8722                       getLocationOfByte(startFlag),
8723                       /*IsStringLocation*/true,
8724                       Range, FixItHint::CreateRemoval(Range));
8725 }
8726 
8727 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8728     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8729     // Warn about using '[...]' without a '@' conversion.
8730     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8731     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8732     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8733                          getLocationOfByte(conversionPosition),
8734                          /*IsStringLocation*/true,
8735                          Range, FixItHint::CreateRemoval(Range));
8736 }
8737 
8738 // Determines if the specified is a C++ class or struct containing
8739 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8740 // "c_str()").
8741 template<typename MemberKind>
8742 static llvm::SmallPtrSet<MemberKind*, 1>
8743 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8744   const RecordType *RT = Ty->getAs<RecordType>();
8745   llvm::SmallPtrSet<MemberKind*, 1> Results;
8746 
8747   if (!RT)
8748     return Results;
8749   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8750   if (!RD || !RD->getDefinition())
8751     return Results;
8752 
8753   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8754                  Sema::LookupMemberName);
8755   R.suppressDiagnostics();
8756 
8757   // We just need to include all members of the right kind turned up by the
8758   // filter, at this point.
8759   if (S.LookupQualifiedName(R, RT->getDecl()))
8760     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8761       NamedDecl *decl = (*I)->getUnderlyingDecl();
8762       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8763         Results.insert(FK);
8764     }
8765   return Results;
8766 }
8767 
8768 /// Check if we could call '.c_str()' on an object.
8769 ///
8770 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8771 /// allow the call, or if it would be ambiguous).
8772 bool Sema::hasCStrMethod(const Expr *E) {
8773   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8774 
8775   MethodSet Results =
8776       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8777   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8778        MI != ME; ++MI)
8779     if ((*MI)->getMinRequiredArguments() == 0)
8780       return true;
8781   return false;
8782 }
8783 
8784 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8785 // better diagnostic if so. AT is assumed to be valid.
8786 // Returns true when a c_str() conversion method is found.
8787 bool CheckPrintfHandler::checkForCStrMembers(
8788     const analyze_printf::ArgType &AT, const Expr *E) {
8789   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8790 
8791   MethodSet Results =
8792       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8793 
8794   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8795        MI != ME; ++MI) {
8796     const CXXMethodDecl *Method = *MI;
8797     if (Method->getMinRequiredArguments() == 0 &&
8798         AT.matchesType(S.Context, Method->getReturnType())) {
8799       // FIXME: Suggest parens if the expression needs them.
8800       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8801       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8802           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8803       return true;
8804     }
8805   }
8806 
8807   return false;
8808 }
8809 
8810 bool
8811 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8812                                             &FS,
8813                                           const char *startSpecifier,
8814                                           unsigned specifierLen) {
8815   using namespace analyze_format_string;
8816   using namespace analyze_printf;
8817 
8818   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8819 
8820   if (FS.consumesDataArgument()) {
8821     if (atFirstArg) {
8822         atFirstArg = false;
8823         usesPositionalArgs = FS.usesPositionalArg();
8824     }
8825     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8826       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8827                                         startSpecifier, specifierLen);
8828       return false;
8829     }
8830   }
8831 
8832   // First check if the field width, precision, and conversion specifier
8833   // have matching data arguments.
8834   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8835                     startSpecifier, specifierLen)) {
8836     return false;
8837   }
8838 
8839   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8840                     startSpecifier, specifierLen)) {
8841     return false;
8842   }
8843 
8844   if (!CS.consumesDataArgument()) {
8845     // FIXME: Technically specifying a precision or field width here
8846     // makes no sense.  Worth issuing a warning at some point.
8847     return true;
8848   }
8849 
8850   // Consume the argument.
8851   unsigned argIndex = FS.getArgIndex();
8852   if (argIndex < NumDataArgs) {
8853     // The check to see if the argIndex is valid will come later.
8854     // We set the bit here because we may exit early from this
8855     // function if we encounter some other error.
8856     CoveredArgs.set(argIndex);
8857   }
8858 
8859   // FreeBSD kernel extensions.
8860   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8861       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8862     // We need at least two arguments.
8863     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8864       return false;
8865 
8866     // Claim the second argument.
8867     CoveredArgs.set(argIndex + 1);
8868 
8869     // Type check the first argument (int for %b, pointer for %D)
8870     const Expr *Ex = getDataArg(argIndex);
8871     const analyze_printf::ArgType &AT =
8872       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8873         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8874     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8875       EmitFormatDiagnostic(
8876           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8877               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8878               << false << Ex->getSourceRange(),
8879           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8880           getSpecifierRange(startSpecifier, specifierLen));
8881 
8882     // Type check the second argument (char * for both %b and %D)
8883     Ex = getDataArg(argIndex + 1);
8884     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8885     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8886       EmitFormatDiagnostic(
8887           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8888               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8889               << false << Ex->getSourceRange(),
8890           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8891           getSpecifierRange(startSpecifier, specifierLen));
8892 
8893      return true;
8894   }
8895 
8896   // Check for using an Objective-C specific conversion specifier
8897   // in a non-ObjC literal.
8898   if (!allowsObjCArg() && CS.isObjCArg()) {
8899     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8900                                                   specifierLen);
8901   }
8902 
8903   // %P can only be used with os_log.
8904   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8905     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8906                                                   specifierLen);
8907   }
8908 
8909   // %n is not allowed with os_log.
8910   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8911     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8912                          getLocationOfByte(CS.getStart()),
8913                          /*IsStringLocation*/ false,
8914                          getSpecifierRange(startSpecifier, specifierLen));
8915 
8916     return true;
8917   }
8918 
8919   // Only scalars are allowed for os_trace.
8920   if (FSType == Sema::FST_OSTrace &&
8921       (CS.getKind() == ConversionSpecifier::PArg ||
8922        CS.getKind() == ConversionSpecifier::sArg ||
8923        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8924     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8925                                                   specifierLen);
8926   }
8927 
8928   // Check for use of public/private annotation outside of os_log().
8929   if (FSType != Sema::FST_OSLog) {
8930     if (FS.isPublic().isSet()) {
8931       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8932                                << "public",
8933                            getLocationOfByte(FS.isPublic().getPosition()),
8934                            /*IsStringLocation*/ false,
8935                            getSpecifierRange(startSpecifier, specifierLen));
8936     }
8937     if (FS.isPrivate().isSet()) {
8938       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8939                                << "private",
8940                            getLocationOfByte(FS.isPrivate().getPosition()),
8941                            /*IsStringLocation*/ false,
8942                            getSpecifierRange(startSpecifier, specifierLen));
8943     }
8944   }
8945 
8946   // Check for invalid use of field width
8947   if (!FS.hasValidFieldWidth()) {
8948     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8949         startSpecifier, specifierLen);
8950   }
8951 
8952   // Check for invalid use of precision
8953   if (!FS.hasValidPrecision()) {
8954     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8955         startSpecifier, specifierLen);
8956   }
8957 
8958   // Precision is mandatory for %P specifier.
8959   if (CS.getKind() == ConversionSpecifier::PArg &&
8960       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8961     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8962                          getLocationOfByte(startSpecifier),
8963                          /*IsStringLocation*/ false,
8964                          getSpecifierRange(startSpecifier, specifierLen));
8965   }
8966 
8967   // Check each flag does not conflict with any other component.
8968   if (!FS.hasValidThousandsGroupingPrefix())
8969     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8970   if (!FS.hasValidLeadingZeros())
8971     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8972   if (!FS.hasValidPlusPrefix())
8973     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8974   if (!FS.hasValidSpacePrefix())
8975     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8976   if (!FS.hasValidAlternativeForm())
8977     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8978   if (!FS.hasValidLeftJustified())
8979     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8980 
8981   // Check that flags are not ignored by another flag
8982   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8983     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8984         startSpecifier, specifierLen);
8985   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8986     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8987             startSpecifier, specifierLen);
8988 
8989   // Check the length modifier is valid with the given conversion specifier.
8990   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8991                                  S.getLangOpts()))
8992     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8993                                 diag::warn_format_nonsensical_length);
8994   else if (!FS.hasStandardLengthModifier())
8995     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8996   else if (!FS.hasStandardLengthConversionCombination())
8997     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8998                                 diag::warn_format_non_standard_conversion_spec);
8999 
9000   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9001     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9002 
9003   // The remaining checks depend on the data arguments.
9004   if (HasVAListArg)
9005     return true;
9006 
9007   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9008     return false;
9009 
9010   const Expr *Arg = getDataArg(argIndex);
9011   if (!Arg)
9012     return true;
9013 
9014   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
9015 }
9016 
9017 static bool requiresParensToAddCast(const Expr *E) {
9018   // FIXME: We should have a general way to reason about operator
9019   // precedence and whether parens are actually needed here.
9020   // Take care of a few common cases where they aren't.
9021   const Expr *Inside = E->IgnoreImpCasts();
9022   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
9023     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
9024 
9025   switch (Inside->getStmtClass()) {
9026   case Stmt::ArraySubscriptExprClass:
9027   case Stmt::CallExprClass:
9028   case Stmt::CharacterLiteralClass:
9029   case Stmt::CXXBoolLiteralExprClass:
9030   case Stmt::DeclRefExprClass:
9031   case Stmt::FloatingLiteralClass:
9032   case Stmt::IntegerLiteralClass:
9033   case Stmt::MemberExprClass:
9034   case Stmt::ObjCArrayLiteralClass:
9035   case Stmt::ObjCBoolLiteralExprClass:
9036   case Stmt::ObjCBoxedExprClass:
9037   case Stmt::ObjCDictionaryLiteralClass:
9038   case Stmt::ObjCEncodeExprClass:
9039   case Stmt::ObjCIvarRefExprClass:
9040   case Stmt::ObjCMessageExprClass:
9041   case Stmt::ObjCPropertyRefExprClass:
9042   case Stmt::ObjCStringLiteralClass:
9043   case Stmt::ObjCSubscriptRefExprClass:
9044   case Stmt::ParenExprClass:
9045   case Stmt::StringLiteralClass:
9046   case Stmt::UnaryOperatorClass:
9047     return false;
9048   default:
9049     return true;
9050   }
9051 }
9052 
9053 static std::pair<QualType, StringRef>
9054 shouldNotPrintDirectly(const ASTContext &Context,
9055                        QualType IntendedTy,
9056                        const Expr *E) {
9057   // Use a 'while' to peel off layers of typedefs.
9058   QualType TyTy = IntendedTy;
9059   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
9060     StringRef Name = UserTy->getDecl()->getName();
9061     QualType CastTy = llvm::StringSwitch<QualType>(Name)
9062       .Case("CFIndex", Context.getNSIntegerType())
9063       .Case("NSInteger", Context.getNSIntegerType())
9064       .Case("NSUInteger", Context.getNSUIntegerType())
9065       .Case("SInt32", Context.IntTy)
9066       .Case("UInt32", Context.UnsignedIntTy)
9067       .Default(QualType());
9068 
9069     if (!CastTy.isNull())
9070       return std::make_pair(CastTy, Name);
9071 
9072     TyTy = UserTy->desugar();
9073   }
9074 
9075   // Strip parens if necessary.
9076   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
9077     return shouldNotPrintDirectly(Context,
9078                                   PE->getSubExpr()->getType(),
9079                                   PE->getSubExpr());
9080 
9081   // If this is a conditional expression, then its result type is constructed
9082   // via usual arithmetic conversions and thus there might be no necessary
9083   // typedef sugar there.  Recurse to operands to check for NSInteger &
9084   // Co. usage condition.
9085   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
9086     QualType TrueTy, FalseTy;
9087     StringRef TrueName, FalseName;
9088 
9089     std::tie(TrueTy, TrueName) =
9090       shouldNotPrintDirectly(Context,
9091                              CO->getTrueExpr()->getType(),
9092                              CO->getTrueExpr());
9093     std::tie(FalseTy, FalseName) =
9094       shouldNotPrintDirectly(Context,
9095                              CO->getFalseExpr()->getType(),
9096                              CO->getFalseExpr());
9097 
9098     if (TrueTy == FalseTy)
9099       return std::make_pair(TrueTy, TrueName);
9100     else if (TrueTy.isNull())
9101       return std::make_pair(FalseTy, FalseName);
9102     else if (FalseTy.isNull())
9103       return std::make_pair(TrueTy, TrueName);
9104   }
9105 
9106   return std::make_pair(QualType(), StringRef());
9107 }
9108 
9109 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
9110 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
9111 /// type do not count.
9112 static bool
9113 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
9114   QualType From = ICE->getSubExpr()->getType();
9115   QualType To = ICE->getType();
9116   // It's an integer promotion if the destination type is the promoted
9117   // source type.
9118   if (ICE->getCastKind() == CK_IntegralCast &&
9119       From->isPromotableIntegerType() &&
9120       S.Context.getPromotedIntegerType(From) == To)
9121     return true;
9122   // Look through vector types, since we do default argument promotion for
9123   // those in OpenCL.
9124   if (const auto *VecTy = From->getAs<ExtVectorType>())
9125     From = VecTy->getElementType();
9126   if (const auto *VecTy = To->getAs<ExtVectorType>())
9127     To = VecTy->getElementType();
9128   // It's a floating promotion if the source type is a lower rank.
9129   return ICE->getCastKind() == CK_FloatingCast &&
9130          S.Context.getFloatingTypeOrder(From, To) < 0;
9131 }
9132 
9133 bool
9134 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
9135                                     const char *StartSpecifier,
9136                                     unsigned SpecifierLen,
9137                                     const Expr *E) {
9138   using namespace analyze_format_string;
9139   using namespace analyze_printf;
9140 
9141   // Now type check the data expression that matches the
9142   // format specifier.
9143   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
9144   if (!AT.isValid())
9145     return true;
9146 
9147   QualType ExprTy = E->getType();
9148   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
9149     ExprTy = TET->getUnderlyingExpr()->getType();
9150   }
9151 
9152   // Diagnose attempts to print a boolean value as a character. Unlike other
9153   // -Wformat diagnostics, this is fine from a type perspective, but it still
9154   // doesn't make sense.
9155   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
9156       E->isKnownToHaveBooleanValue()) {
9157     const CharSourceRange &CSR =
9158         getSpecifierRange(StartSpecifier, SpecifierLen);
9159     SmallString<4> FSString;
9160     llvm::raw_svector_ostream os(FSString);
9161     FS.toString(os);
9162     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
9163                              << FSString,
9164                          E->getExprLoc(), false, CSR);
9165     return true;
9166   }
9167 
9168   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
9169   if (Match == analyze_printf::ArgType::Match)
9170     return true;
9171 
9172   // Look through argument promotions for our error message's reported type.
9173   // This includes the integral and floating promotions, but excludes array
9174   // and function pointer decay (seeing that an argument intended to be a
9175   // string has type 'char [6]' is probably more confusing than 'char *') and
9176   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
9177   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
9178     if (isArithmeticArgumentPromotion(S, ICE)) {
9179       E = ICE->getSubExpr();
9180       ExprTy = E->getType();
9181 
9182       // Check if we didn't match because of an implicit cast from a 'char'
9183       // or 'short' to an 'int'.  This is done because printf is a varargs
9184       // function.
9185       if (ICE->getType() == S.Context.IntTy ||
9186           ICE->getType() == S.Context.UnsignedIntTy) {
9187         // All further checking is done on the subexpression
9188         const analyze_printf::ArgType::MatchKind ImplicitMatch =
9189             AT.matchesType(S.Context, ExprTy);
9190         if (ImplicitMatch == analyze_printf::ArgType::Match)
9191           return true;
9192         if (ImplicitMatch == ArgType::NoMatchPedantic ||
9193             ImplicitMatch == ArgType::NoMatchTypeConfusion)
9194           Match = ImplicitMatch;
9195       }
9196     }
9197   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
9198     // Special case for 'a', which has type 'int' in C.
9199     // Note, however, that we do /not/ want to treat multibyte constants like
9200     // 'MooV' as characters! This form is deprecated but still exists. In
9201     // addition, don't treat expressions as of type 'char' if one byte length
9202     // modifier is provided.
9203     if (ExprTy == S.Context.IntTy &&
9204         FS.getLengthModifier().getKind() != LengthModifier::AsChar)
9205       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
9206         ExprTy = S.Context.CharTy;
9207   }
9208 
9209   // Look through enums to their underlying type.
9210   bool IsEnum = false;
9211   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
9212     ExprTy = EnumTy->getDecl()->getIntegerType();
9213     IsEnum = true;
9214   }
9215 
9216   // %C in an Objective-C context prints a unichar, not a wchar_t.
9217   // If the argument is an integer of some kind, believe the %C and suggest
9218   // a cast instead of changing the conversion specifier.
9219   QualType IntendedTy = ExprTy;
9220   if (isObjCContext() &&
9221       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
9222     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
9223         !ExprTy->isCharType()) {
9224       // 'unichar' is defined as a typedef of unsigned short, but we should
9225       // prefer using the typedef if it is visible.
9226       IntendedTy = S.Context.UnsignedShortTy;
9227 
9228       // While we are here, check if the value is an IntegerLiteral that happens
9229       // to be within the valid range.
9230       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
9231         const llvm::APInt &V = IL->getValue();
9232         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
9233           return true;
9234       }
9235 
9236       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
9237                           Sema::LookupOrdinaryName);
9238       if (S.LookupName(Result, S.getCurScope())) {
9239         NamedDecl *ND = Result.getFoundDecl();
9240         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
9241           if (TD->getUnderlyingType() == IntendedTy)
9242             IntendedTy = S.Context.getTypedefType(TD);
9243       }
9244     }
9245   }
9246 
9247   // Special-case some of Darwin's platform-independence types by suggesting
9248   // casts to primitive types that are known to be large enough.
9249   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
9250   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
9251     QualType CastTy;
9252     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
9253     if (!CastTy.isNull()) {
9254       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
9255       // (long in ASTContext). Only complain to pedants.
9256       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
9257           (AT.isSizeT() || AT.isPtrdiffT()) &&
9258           AT.matchesType(S.Context, CastTy))
9259         Match = ArgType::NoMatchPedantic;
9260       IntendedTy = CastTy;
9261       ShouldNotPrintDirectly = true;
9262     }
9263   }
9264 
9265   // We may be able to offer a FixItHint if it is a supported type.
9266   PrintfSpecifier fixedFS = FS;
9267   bool Success =
9268       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
9269 
9270   if (Success) {
9271     // Get the fix string from the fixed format specifier
9272     SmallString<16> buf;
9273     llvm::raw_svector_ostream os(buf);
9274     fixedFS.toString(os);
9275 
9276     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
9277 
9278     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
9279       unsigned Diag;
9280       switch (Match) {
9281       case ArgType::Match: llvm_unreachable("expected non-matching");
9282       case ArgType::NoMatchPedantic:
9283         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9284         break;
9285       case ArgType::NoMatchTypeConfusion:
9286         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9287         break;
9288       case ArgType::NoMatch:
9289         Diag = diag::warn_format_conversion_argument_type_mismatch;
9290         break;
9291       }
9292 
9293       // In this case, the specifier is wrong and should be changed to match
9294       // the argument.
9295       EmitFormatDiagnostic(S.PDiag(Diag)
9296                                << AT.getRepresentativeTypeName(S.Context)
9297                                << IntendedTy << IsEnum << E->getSourceRange(),
9298                            E->getBeginLoc(),
9299                            /*IsStringLocation*/ false, SpecRange,
9300                            FixItHint::CreateReplacement(SpecRange, os.str()));
9301     } else {
9302       // The canonical type for formatting this value is different from the
9303       // actual type of the expression. (This occurs, for example, with Darwin's
9304       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
9305       // should be printed as 'long' for 64-bit compatibility.)
9306       // Rather than emitting a normal format/argument mismatch, we want to
9307       // add a cast to the recommended type (and correct the format string
9308       // if necessary).
9309       SmallString<16> CastBuf;
9310       llvm::raw_svector_ostream CastFix(CastBuf);
9311       CastFix << "(";
9312       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
9313       CastFix << ")";
9314 
9315       SmallVector<FixItHint,4> Hints;
9316       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
9317         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
9318 
9319       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
9320         // If there's already a cast present, just replace it.
9321         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
9322         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
9323 
9324       } else if (!requiresParensToAddCast(E)) {
9325         // If the expression has high enough precedence,
9326         // just write the C-style cast.
9327         Hints.push_back(
9328             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9329       } else {
9330         // Otherwise, add parens around the expression as well as the cast.
9331         CastFix << "(";
9332         Hints.push_back(
9333             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
9334 
9335         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
9336         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
9337       }
9338 
9339       if (ShouldNotPrintDirectly) {
9340         // The expression has a type that should not be printed directly.
9341         // We extract the name from the typedef because we don't want to show
9342         // the underlying type in the diagnostic.
9343         StringRef Name;
9344         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
9345           Name = TypedefTy->getDecl()->getName();
9346         else
9347           Name = CastTyName;
9348         unsigned Diag = Match == ArgType::NoMatchPedantic
9349                             ? diag::warn_format_argument_needs_cast_pedantic
9350                             : diag::warn_format_argument_needs_cast;
9351         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
9352                                            << E->getSourceRange(),
9353                              E->getBeginLoc(), /*IsStringLocation=*/false,
9354                              SpecRange, Hints);
9355       } else {
9356         // In this case, the expression could be printed using a different
9357         // specifier, but we've decided that the specifier is probably correct
9358         // and we should cast instead. Just use the normal warning message.
9359         EmitFormatDiagnostic(
9360             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
9361                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
9362                 << E->getSourceRange(),
9363             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
9364       }
9365     }
9366   } else {
9367     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
9368                                                    SpecifierLen);
9369     // Since the warning for passing non-POD types to variadic functions
9370     // was deferred until now, we emit a warning for non-POD
9371     // arguments here.
9372     switch (S.isValidVarArgType(ExprTy)) {
9373     case Sema::VAK_Valid:
9374     case Sema::VAK_ValidInCXX11: {
9375       unsigned Diag;
9376       switch (Match) {
9377       case ArgType::Match: llvm_unreachable("expected non-matching");
9378       case ArgType::NoMatchPedantic:
9379         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
9380         break;
9381       case ArgType::NoMatchTypeConfusion:
9382         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
9383         break;
9384       case ArgType::NoMatch:
9385         Diag = diag::warn_format_conversion_argument_type_mismatch;
9386         break;
9387       }
9388 
9389       EmitFormatDiagnostic(
9390           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
9391                         << IsEnum << CSR << E->getSourceRange(),
9392           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9393       break;
9394     }
9395     case Sema::VAK_Undefined:
9396     case Sema::VAK_MSVCUndefined:
9397       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
9398                                << S.getLangOpts().CPlusPlus11 << ExprTy
9399                                << CallType
9400                                << AT.getRepresentativeTypeName(S.Context) << CSR
9401                                << E->getSourceRange(),
9402                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9403       checkForCStrMembers(AT, E);
9404       break;
9405 
9406     case Sema::VAK_Invalid:
9407       if (ExprTy->isObjCObjectType())
9408         EmitFormatDiagnostic(
9409             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
9410                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
9411                 << AT.getRepresentativeTypeName(S.Context) << CSR
9412                 << E->getSourceRange(),
9413             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
9414       else
9415         // FIXME: If this is an initializer list, suggest removing the braces
9416         // or inserting a cast to the target type.
9417         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
9418             << isa<InitListExpr>(E) << ExprTy << CallType
9419             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
9420       break;
9421     }
9422 
9423     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
9424            "format string specifier index out of range");
9425     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
9426   }
9427 
9428   return true;
9429 }
9430 
9431 //===--- CHECK: Scanf format string checking ------------------------------===//
9432 
9433 namespace {
9434 
9435 class CheckScanfHandler : public CheckFormatHandler {
9436 public:
9437   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
9438                     const Expr *origFormatExpr, Sema::FormatStringType type,
9439                     unsigned firstDataArg, unsigned numDataArgs,
9440                     const char *beg, bool hasVAListArg,
9441                     ArrayRef<const Expr *> Args, unsigned formatIdx,
9442                     bool inFunctionCall, Sema::VariadicCallType CallType,
9443                     llvm::SmallBitVector &CheckedVarArgs,
9444                     UncoveredArgHandler &UncoveredArg)
9445       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
9446                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
9447                            inFunctionCall, CallType, CheckedVarArgs,
9448                            UncoveredArg) {}
9449 
9450   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
9451                             const char *startSpecifier,
9452                             unsigned specifierLen) override;
9453 
9454   bool HandleInvalidScanfConversionSpecifier(
9455           const analyze_scanf::ScanfSpecifier &FS,
9456           const char *startSpecifier,
9457           unsigned specifierLen) override;
9458 
9459   void HandleIncompleteScanList(const char *start, const char *end) override;
9460 };
9461 
9462 } // namespace
9463 
9464 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
9465                                                  const char *end) {
9466   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
9467                        getLocationOfByte(end), /*IsStringLocation*/true,
9468                        getSpecifierRange(start, end - start));
9469 }
9470 
9471 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
9472                                         const analyze_scanf::ScanfSpecifier &FS,
9473                                         const char *startSpecifier,
9474                                         unsigned specifierLen) {
9475   const analyze_scanf::ScanfConversionSpecifier &CS =
9476     FS.getConversionSpecifier();
9477 
9478   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
9479                                           getLocationOfByte(CS.getStart()),
9480                                           startSpecifier, specifierLen,
9481                                           CS.getStart(), CS.getLength());
9482 }
9483 
9484 bool CheckScanfHandler::HandleScanfSpecifier(
9485                                        const analyze_scanf::ScanfSpecifier &FS,
9486                                        const char *startSpecifier,
9487                                        unsigned specifierLen) {
9488   using namespace analyze_scanf;
9489   using namespace analyze_format_string;
9490 
9491   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
9492 
9493   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
9494   // be used to decide if we are using positional arguments consistently.
9495   if (FS.consumesDataArgument()) {
9496     if (atFirstArg) {
9497       atFirstArg = false;
9498       usesPositionalArgs = FS.usesPositionalArg();
9499     }
9500     else if (usesPositionalArgs != FS.usesPositionalArg()) {
9501       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
9502                                         startSpecifier, specifierLen);
9503       return false;
9504     }
9505   }
9506 
9507   // Check if the field with is non-zero.
9508   const OptionalAmount &Amt = FS.getFieldWidth();
9509   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
9510     if (Amt.getConstantAmount() == 0) {
9511       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
9512                                                    Amt.getConstantLength());
9513       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
9514                            getLocationOfByte(Amt.getStart()),
9515                            /*IsStringLocation*/true, R,
9516                            FixItHint::CreateRemoval(R));
9517     }
9518   }
9519 
9520   if (!FS.consumesDataArgument()) {
9521     // FIXME: Technically specifying a precision or field width here
9522     // makes no sense.  Worth issuing a warning at some point.
9523     return true;
9524   }
9525 
9526   // Consume the argument.
9527   unsigned argIndex = FS.getArgIndex();
9528   if (argIndex < NumDataArgs) {
9529       // The check to see if the argIndex is valid will come later.
9530       // We set the bit here because we may exit early from this
9531       // function if we encounter some other error.
9532     CoveredArgs.set(argIndex);
9533   }
9534 
9535   // Check the length modifier is valid with the given conversion specifier.
9536   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
9537                                  S.getLangOpts()))
9538     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9539                                 diag::warn_format_nonsensical_length);
9540   else if (!FS.hasStandardLengthModifier())
9541     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
9542   else if (!FS.hasStandardLengthConversionCombination())
9543     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
9544                                 diag::warn_format_non_standard_conversion_spec);
9545 
9546   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
9547     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
9548 
9549   // The remaining checks depend on the data arguments.
9550   if (HasVAListArg)
9551     return true;
9552 
9553   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
9554     return false;
9555 
9556   // Check that the argument type matches the format specifier.
9557   const Expr *Ex = getDataArg(argIndex);
9558   if (!Ex)
9559     return true;
9560 
9561   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
9562 
9563   if (!AT.isValid()) {
9564     return true;
9565   }
9566 
9567   analyze_format_string::ArgType::MatchKind Match =
9568       AT.matchesType(S.Context, Ex->getType());
9569   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
9570   if (Match == analyze_format_string::ArgType::Match)
9571     return true;
9572 
9573   ScanfSpecifier fixedFS = FS;
9574   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
9575                                  S.getLangOpts(), S.Context);
9576 
9577   unsigned Diag =
9578       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
9579                : diag::warn_format_conversion_argument_type_mismatch;
9580 
9581   if (Success) {
9582     // Get the fix string from the fixed format specifier.
9583     SmallString<128> buf;
9584     llvm::raw_svector_ostream os(buf);
9585     fixedFS.toString(os);
9586 
9587     EmitFormatDiagnostic(
9588         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
9589                       << Ex->getType() << false << Ex->getSourceRange(),
9590         Ex->getBeginLoc(),
9591         /*IsStringLocation*/ false,
9592         getSpecifierRange(startSpecifier, specifierLen),
9593         FixItHint::CreateReplacement(
9594             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9595   } else {
9596     EmitFormatDiagnostic(S.PDiag(Diag)
9597                              << AT.getRepresentativeTypeName(S.Context)
9598                              << Ex->getType() << false << Ex->getSourceRange(),
9599                          Ex->getBeginLoc(),
9600                          /*IsStringLocation*/ false,
9601                          getSpecifierRange(startSpecifier, specifierLen));
9602   }
9603 
9604   return true;
9605 }
9606 
9607 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9608                               const Expr *OrigFormatExpr,
9609                               ArrayRef<const Expr *> Args,
9610                               bool HasVAListArg, unsigned format_idx,
9611                               unsigned firstDataArg,
9612                               Sema::FormatStringType Type,
9613                               bool inFunctionCall,
9614                               Sema::VariadicCallType CallType,
9615                               llvm::SmallBitVector &CheckedVarArgs,
9616                               UncoveredArgHandler &UncoveredArg,
9617                               bool IgnoreStringsWithoutSpecifiers) {
9618   // CHECK: is the format string a wide literal?
9619   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9620     CheckFormatHandler::EmitFormatDiagnostic(
9621         S, inFunctionCall, Args[format_idx],
9622         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9623         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9624     return;
9625   }
9626 
9627   // Str - The format string.  NOTE: this is NOT null-terminated!
9628   StringRef StrRef = FExpr->getString();
9629   const char *Str = StrRef.data();
9630   // Account for cases where the string literal is truncated in a declaration.
9631   const ConstantArrayType *T =
9632     S.Context.getAsConstantArrayType(FExpr->getType());
9633   assert(T && "String literal not of constant array type!");
9634   size_t TypeSize = T->getSize().getZExtValue();
9635   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9636   const unsigned numDataArgs = Args.size() - firstDataArg;
9637 
9638   if (IgnoreStringsWithoutSpecifiers &&
9639       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9640           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9641     return;
9642 
9643   // Emit a warning if the string literal is truncated and does not contain an
9644   // embedded null character.
9645   if (TypeSize <= StrRef.size() && !StrRef.substr(0, TypeSize).contains('\0')) {
9646     CheckFormatHandler::EmitFormatDiagnostic(
9647         S, inFunctionCall, Args[format_idx],
9648         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9649         FExpr->getBeginLoc(),
9650         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9651     return;
9652   }
9653 
9654   // CHECK: empty format string?
9655   if (StrLen == 0 && numDataArgs > 0) {
9656     CheckFormatHandler::EmitFormatDiagnostic(
9657         S, inFunctionCall, Args[format_idx],
9658         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9659         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9660     return;
9661   }
9662 
9663   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9664       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9665       Type == Sema::FST_OSTrace) {
9666     CheckPrintfHandler H(
9667         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9668         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9669         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9670         CheckedVarArgs, UncoveredArg);
9671 
9672     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9673                                                   S.getLangOpts(),
9674                                                   S.Context.getTargetInfo(),
9675                                             Type == Sema::FST_FreeBSDKPrintf))
9676       H.DoneProcessing();
9677   } else if (Type == Sema::FST_Scanf) {
9678     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9679                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9680                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9681 
9682     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9683                                                  S.getLangOpts(),
9684                                                  S.Context.getTargetInfo()))
9685       H.DoneProcessing();
9686   } // TODO: handle other formats
9687 }
9688 
9689 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9690   // Str - The format string.  NOTE: this is NOT null-terminated!
9691   StringRef StrRef = FExpr->getString();
9692   const char *Str = StrRef.data();
9693   // Account for cases where the string literal is truncated in a declaration.
9694   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9695   assert(T && "String literal not of constant array type!");
9696   size_t TypeSize = T->getSize().getZExtValue();
9697   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9698   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9699                                                          getLangOpts(),
9700                                                          Context.getTargetInfo());
9701 }
9702 
9703 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9704 
9705 // Returns the related absolute value function that is larger, of 0 if one
9706 // does not exist.
9707 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9708   switch (AbsFunction) {
9709   default:
9710     return 0;
9711 
9712   case Builtin::BI__builtin_abs:
9713     return Builtin::BI__builtin_labs;
9714   case Builtin::BI__builtin_labs:
9715     return Builtin::BI__builtin_llabs;
9716   case Builtin::BI__builtin_llabs:
9717     return 0;
9718 
9719   case Builtin::BI__builtin_fabsf:
9720     return Builtin::BI__builtin_fabs;
9721   case Builtin::BI__builtin_fabs:
9722     return Builtin::BI__builtin_fabsl;
9723   case Builtin::BI__builtin_fabsl:
9724     return 0;
9725 
9726   case Builtin::BI__builtin_cabsf:
9727     return Builtin::BI__builtin_cabs;
9728   case Builtin::BI__builtin_cabs:
9729     return Builtin::BI__builtin_cabsl;
9730   case Builtin::BI__builtin_cabsl:
9731     return 0;
9732 
9733   case Builtin::BIabs:
9734     return Builtin::BIlabs;
9735   case Builtin::BIlabs:
9736     return Builtin::BIllabs;
9737   case Builtin::BIllabs:
9738     return 0;
9739 
9740   case Builtin::BIfabsf:
9741     return Builtin::BIfabs;
9742   case Builtin::BIfabs:
9743     return Builtin::BIfabsl;
9744   case Builtin::BIfabsl:
9745     return 0;
9746 
9747   case Builtin::BIcabsf:
9748    return Builtin::BIcabs;
9749   case Builtin::BIcabs:
9750     return Builtin::BIcabsl;
9751   case Builtin::BIcabsl:
9752     return 0;
9753   }
9754 }
9755 
9756 // Returns the argument type of the absolute value function.
9757 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9758                                              unsigned AbsType) {
9759   if (AbsType == 0)
9760     return QualType();
9761 
9762   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9763   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9764   if (Error != ASTContext::GE_None)
9765     return QualType();
9766 
9767   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9768   if (!FT)
9769     return QualType();
9770 
9771   if (FT->getNumParams() != 1)
9772     return QualType();
9773 
9774   return FT->getParamType(0);
9775 }
9776 
9777 // Returns the best absolute value function, or zero, based on type and
9778 // current absolute value function.
9779 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9780                                    unsigned AbsFunctionKind) {
9781   unsigned BestKind = 0;
9782   uint64_t ArgSize = Context.getTypeSize(ArgType);
9783   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9784        Kind = getLargerAbsoluteValueFunction(Kind)) {
9785     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9786     if (Context.getTypeSize(ParamType) >= ArgSize) {
9787       if (BestKind == 0)
9788         BestKind = Kind;
9789       else if (Context.hasSameType(ParamType, ArgType)) {
9790         BestKind = Kind;
9791         break;
9792       }
9793     }
9794   }
9795   return BestKind;
9796 }
9797 
9798 enum AbsoluteValueKind {
9799   AVK_Integer,
9800   AVK_Floating,
9801   AVK_Complex
9802 };
9803 
9804 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9805   if (T->isIntegralOrEnumerationType())
9806     return AVK_Integer;
9807   if (T->isRealFloatingType())
9808     return AVK_Floating;
9809   if (T->isAnyComplexType())
9810     return AVK_Complex;
9811 
9812   llvm_unreachable("Type not integer, floating, or complex");
9813 }
9814 
9815 // Changes the absolute value function to a different type.  Preserves whether
9816 // the function is a builtin.
9817 static unsigned changeAbsFunction(unsigned AbsKind,
9818                                   AbsoluteValueKind ValueKind) {
9819   switch (ValueKind) {
9820   case AVK_Integer:
9821     switch (AbsKind) {
9822     default:
9823       return 0;
9824     case Builtin::BI__builtin_fabsf:
9825     case Builtin::BI__builtin_fabs:
9826     case Builtin::BI__builtin_fabsl:
9827     case Builtin::BI__builtin_cabsf:
9828     case Builtin::BI__builtin_cabs:
9829     case Builtin::BI__builtin_cabsl:
9830       return Builtin::BI__builtin_abs;
9831     case Builtin::BIfabsf:
9832     case Builtin::BIfabs:
9833     case Builtin::BIfabsl:
9834     case Builtin::BIcabsf:
9835     case Builtin::BIcabs:
9836     case Builtin::BIcabsl:
9837       return Builtin::BIabs;
9838     }
9839   case AVK_Floating:
9840     switch (AbsKind) {
9841     default:
9842       return 0;
9843     case Builtin::BI__builtin_abs:
9844     case Builtin::BI__builtin_labs:
9845     case Builtin::BI__builtin_llabs:
9846     case Builtin::BI__builtin_cabsf:
9847     case Builtin::BI__builtin_cabs:
9848     case Builtin::BI__builtin_cabsl:
9849       return Builtin::BI__builtin_fabsf;
9850     case Builtin::BIabs:
9851     case Builtin::BIlabs:
9852     case Builtin::BIllabs:
9853     case Builtin::BIcabsf:
9854     case Builtin::BIcabs:
9855     case Builtin::BIcabsl:
9856       return Builtin::BIfabsf;
9857     }
9858   case AVK_Complex:
9859     switch (AbsKind) {
9860     default:
9861       return 0;
9862     case Builtin::BI__builtin_abs:
9863     case Builtin::BI__builtin_labs:
9864     case Builtin::BI__builtin_llabs:
9865     case Builtin::BI__builtin_fabsf:
9866     case Builtin::BI__builtin_fabs:
9867     case Builtin::BI__builtin_fabsl:
9868       return Builtin::BI__builtin_cabsf;
9869     case Builtin::BIabs:
9870     case Builtin::BIlabs:
9871     case Builtin::BIllabs:
9872     case Builtin::BIfabsf:
9873     case Builtin::BIfabs:
9874     case Builtin::BIfabsl:
9875       return Builtin::BIcabsf;
9876     }
9877   }
9878   llvm_unreachable("Unable to convert function");
9879 }
9880 
9881 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9882   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9883   if (!FnInfo)
9884     return 0;
9885 
9886   switch (FDecl->getBuiltinID()) {
9887   default:
9888     return 0;
9889   case Builtin::BI__builtin_abs:
9890   case Builtin::BI__builtin_fabs:
9891   case Builtin::BI__builtin_fabsf:
9892   case Builtin::BI__builtin_fabsl:
9893   case Builtin::BI__builtin_labs:
9894   case Builtin::BI__builtin_llabs:
9895   case Builtin::BI__builtin_cabs:
9896   case Builtin::BI__builtin_cabsf:
9897   case Builtin::BI__builtin_cabsl:
9898   case Builtin::BIabs:
9899   case Builtin::BIlabs:
9900   case Builtin::BIllabs:
9901   case Builtin::BIfabs:
9902   case Builtin::BIfabsf:
9903   case Builtin::BIfabsl:
9904   case Builtin::BIcabs:
9905   case Builtin::BIcabsf:
9906   case Builtin::BIcabsl:
9907     return FDecl->getBuiltinID();
9908   }
9909   llvm_unreachable("Unknown Builtin type");
9910 }
9911 
9912 // If the replacement is valid, emit a note with replacement function.
9913 // Additionally, suggest including the proper header if not already included.
9914 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9915                             unsigned AbsKind, QualType ArgType) {
9916   bool EmitHeaderHint = true;
9917   const char *HeaderName = nullptr;
9918   const char *FunctionName = nullptr;
9919   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9920     FunctionName = "std::abs";
9921     if (ArgType->isIntegralOrEnumerationType()) {
9922       HeaderName = "cstdlib";
9923     } else if (ArgType->isRealFloatingType()) {
9924       HeaderName = "cmath";
9925     } else {
9926       llvm_unreachable("Invalid Type");
9927     }
9928 
9929     // Lookup all std::abs
9930     if (NamespaceDecl *Std = S.getStdNamespace()) {
9931       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9932       R.suppressDiagnostics();
9933       S.LookupQualifiedName(R, Std);
9934 
9935       for (const auto *I : R) {
9936         const FunctionDecl *FDecl = nullptr;
9937         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9938           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9939         } else {
9940           FDecl = dyn_cast<FunctionDecl>(I);
9941         }
9942         if (!FDecl)
9943           continue;
9944 
9945         // Found std::abs(), check that they are the right ones.
9946         if (FDecl->getNumParams() != 1)
9947           continue;
9948 
9949         // Check that the parameter type can handle the argument.
9950         QualType ParamType = FDecl->getParamDecl(0)->getType();
9951         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9952             S.Context.getTypeSize(ArgType) <=
9953                 S.Context.getTypeSize(ParamType)) {
9954           // Found a function, don't need the header hint.
9955           EmitHeaderHint = false;
9956           break;
9957         }
9958       }
9959     }
9960   } else {
9961     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9962     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9963 
9964     if (HeaderName) {
9965       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9966       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9967       R.suppressDiagnostics();
9968       S.LookupName(R, S.getCurScope());
9969 
9970       if (R.isSingleResult()) {
9971         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9972         if (FD && FD->getBuiltinID() == AbsKind) {
9973           EmitHeaderHint = false;
9974         } else {
9975           return;
9976         }
9977       } else if (!R.empty()) {
9978         return;
9979       }
9980     }
9981   }
9982 
9983   S.Diag(Loc, diag::note_replace_abs_function)
9984       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9985 
9986   if (!HeaderName)
9987     return;
9988 
9989   if (!EmitHeaderHint)
9990     return;
9991 
9992   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9993                                                     << FunctionName;
9994 }
9995 
9996 template <std::size_t StrLen>
9997 static bool IsStdFunction(const FunctionDecl *FDecl,
9998                           const char (&Str)[StrLen]) {
9999   if (!FDecl)
10000     return false;
10001   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
10002     return false;
10003   if (!FDecl->isInStdNamespace())
10004     return false;
10005 
10006   return true;
10007 }
10008 
10009 // Warn when using the wrong abs() function.
10010 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
10011                                       const FunctionDecl *FDecl) {
10012   if (Call->getNumArgs() != 1)
10013     return;
10014 
10015   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
10016   bool IsStdAbs = IsStdFunction(FDecl, "abs");
10017   if (AbsKind == 0 && !IsStdAbs)
10018     return;
10019 
10020   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10021   QualType ParamType = Call->getArg(0)->getType();
10022 
10023   // Unsigned types cannot be negative.  Suggest removing the absolute value
10024   // function call.
10025   if (ArgType->isUnsignedIntegerType()) {
10026     const char *FunctionName =
10027         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
10028     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
10029     Diag(Call->getExprLoc(), diag::note_remove_abs)
10030         << FunctionName
10031         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
10032     return;
10033   }
10034 
10035   // Taking the absolute value of a pointer is very suspicious, they probably
10036   // wanted to index into an array, dereference a pointer, call a function, etc.
10037   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
10038     unsigned DiagType = 0;
10039     if (ArgType->isFunctionType())
10040       DiagType = 1;
10041     else if (ArgType->isArrayType())
10042       DiagType = 2;
10043 
10044     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
10045     return;
10046   }
10047 
10048   // std::abs has overloads which prevent most of the absolute value problems
10049   // from occurring.
10050   if (IsStdAbs)
10051     return;
10052 
10053   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
10054   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
10055 
10056   // The argument and parameter are the same kind.  Check if they are the right
10057   // size.
10058   if (ArgValueKind == ParamValueKind) {
10059     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
10060       return;
10061 
10062     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
10063     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
10064         << FDecl << ArgType << ParamType;
10065 
10066     if (NewAbsKind == 0)
10067       return;
10068 
10069     emitReplacement(*this, Call->getExprLoc(),
10070                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10071     return;
10072   }
10073 
10074   // ArgValueKind != ParamValueKind
10075   // The wrong type of absolute value function was used.  Attempt to find the
10076   // proper one.
10077   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
10078   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
10079   if (NewAbsKind == 0)
10080     return;
10081 
10082   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
10083       << FDecl << ParamValueKind << ArgValueKind;
10084 
10085   emitReplacement(*this, Call->getExprLoc(),
10086                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
10087 }
10088 
10089 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
10090 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
10091                                 const FunctionDecl *FDecl) {
10092   if (!Call || !FDecl) return;
10093 
10094   // Ignore template specializations and macros.
10095   if (inTemplateInstantiation()) return;
10096   if (Call->getExprLoc().isMacroID()) return;
10097 
10098   // Only care about the one template argument, two function parameter std::max
10099   if (Call->getNumArgs() != 2) return;
10100   if (!IsStdFunction(FDecl, "max")) return;
10101   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
10102   if (!ArgList) return;
10103   if (ArgList->size() != 1) return;
10104 
10105   // Check that template type argument is unsigned integer.
10106   const auto& TA = ArgList->get(0);
10107   if (TA.getKind() != TemplateArgument::Type) return;
10108   QualType ArgType = TA.getAsType();
10109   if (!ArgType->isUnsignedIntegerType()) return;
10110 
10111   // See if either argument is a literal zero.
10112   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
10113     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
10114     if (!MTE) return false;
10115     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
10116     if (!Num) return false;
10117     if (Num->getValue() != 0) return false;
10118     return true;
10119   };
10120 
10121   const Expr *FirstArg = Call->getArg(0);
10122   const Expr *SecondArg = Call->getArg(1);
10123   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
10124   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
10125 
10126   // Only warn when exactly one argument is zero.
10127   if (IsFirstArgZero == IsSecondArgZero) return;
10128 
10129   SourceRange FirstRange = FirstArg->getSourceRange();
10130   SourceRange SecondRange = SecondArg->getSourceRange();
10131 
10132   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
10133 
10134   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
10135       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
10136 
10137   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
10138   SourceRange RemovalRange;
10139   if (IsFirstArgZero) {
10140     RemovalRange = SourceRange(FirstRange.getBegin(),
10141                                SecondRange.getBegin().getLocWithOffset(-1));
10142   } else {
10143     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
10144                                SecondRange.getEnd());
10145   }
10146 
10147   Diag(Call->getExprLoc(), diag::note_remove_max_call)
10148         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
10149         << FixItHint::CreateRemoval(RemovalRange);
10150 }
10151 
10152 //===--- CHECK: Standard memory functions ---------------------------------===//
10153 
10154 /// Takes the expression passed to the size_t parameter of functions
10155 /// such as memcmp, strncat, etc and warns if it's a comparison.
10156 ///
10157 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
10158 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
10159                                            IdentifierInfo *FnName,
10160                                            SourceLocation FnLoc,
10161                                            SourceLocation RParenLoc) {
10162   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
10163   if (!Size)
10164     return false;
10165 
10166   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
10167   if (!Size->isComparisonOp() && !Size->isLogicalOp())
10168     return false;
10169 
10170   SourceRange SizeRange = Size->getSourceRange();
10171   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
10172       << SizeRange << FnName;
10173   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
10174       << FnName
10175       << FixItHint::CreateInsertion(
10176              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
10177       << FixItHint::CreateRemoval(RParenLoc);
10178   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
10179       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
10180       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
10181                                     ")");
10182 
10183   return true;
10184 }
10185 
10186 /// Determine whether the given type is or contains a dynamic class type
10187 /// (e.g., whether it has a vtable).
10188 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
10189                                                      bool &IsContained) {
10190   // Look through array types while ignoring qualifiers.
10191   const Type *Ty = T->getBaseElementTypeUnsafe();
10192   IsContained = false;
10193 
10194   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
10195   RD = RD ? RD->getDefinition() : nullptr;
10196   if (!RD || RD->isInvalidDecl())
10197     return nullptr;
10198 
10199   if (RD->isDynamicClass())
10200     return RD;
10201 
10202   // Check all the fields.  If any bases were dynamic, the class is dynamic.
10203   // It's impossible for a class to transitively contain itself by value, so
10204   // infinite recursion is impossible.
10205   for (auto *FD : RD->fields()) {
10206     bool SubContained;
10207     if (const CXXRecordDecl *ContainedRD =
10208             getContainedDynamicClass(FD->getType(), SubContained)) {
10209       IsContained = true;
10210       return ContainedRD;
10211     }
10212   }
10213 
10214   return nullptr;
10215 }
10216 
10217 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
10218   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
10219     if (Unary->getKind() == UETT_SizeOf)
10220       return Unary;
10221   return nullptr;
10222 }
10223 
10224 /// If E is a sizeof expression, returns its argument expression,
10225 /// otherwise returns NULL.
10226 static const Expr *getSizeOfExprArg(const Expr *E) {
10227   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10228     if (!SizeOf->isArgumentType())
10229       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
10230   return nullptr;
10231 }
10232 
10233 /// If E is a sizeof expression, returns its argument type.
10234 static QualType getSizeOfArgType(const Expr *E) {
10235   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
10236     return SizeOf->getTypeOfArgument();
10237   return QualType();
10238 }
10239 
10240 namespace {
10241 
10242 struct SearchNonTrivialToInitializeField
10243     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
10244   using Super =
10245       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
10246 
10247   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
10248 
10249   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
10250                      SourceLocation SL) {
10251     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10252       asDerived().visitArray(PDIK, AT, SL);
10253       return;
10254     }
10255 
10256     Super::visitWithKind(PDIK, FT, SL);
10257   }
10258 
10259   void visitARCStrong(QualType FT, SourceLocation SL) {
10260     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10261   }
10262   void visitARCWeak(QualType FT, SourceLocation SL) {
10263     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
10264   }
10265   void visitStruct(QualType FT, SourceLocation SL) {
10266     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10267       visit(FD->getType(), FD->getLocation());
10268   }
10269   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
10270                   const ArrayType *AT, SourceLocation SL) {
10271     visit(getContext().getBaseElementType(AT), SL);
10272   }
10273   void visitTrivial(QualType FT, SourceLocation SL) {}
10274 
10275   static void diag(QualType RT, const Expr *E, Sema &S) {
10276     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
10277   }
10278 
10279   ASTContext &getContext() { return S.getASTContext(); }
10280 
10281   const Expr *E;
10282   Sema &S;
10283 };
10284 
10285 struct SearchNonTrivialToCopyField
10286     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
10287   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
10288 
10289   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
10290 
10291   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
10292                      SourceLocation SL) {
10293     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
10294       asDerived().visitArray(PCK, AT, SL);
10295       return;
10296     }
10297 
10298     Super::visitWithKind(PCK, FT, SL);
10299   }
10300 
10301   void visitARCStrong(QualType FT, SourceLocation SL) {
10302     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10303   }
10304   void visitARCWeak(QualType FT, SourceLocation SL) {
10305     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
10306   }
10307   void visitStruct(QualType FT, SourceLocation SL) {
10308     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
10309       visit(FD->getType(), FD->getLocation());
10310   }
10311   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
10312                   SourceLocation SL) {
10313     visit(getContext().getBaseElementType(AT), SL);
10314   }
10315   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
10316                 SourceLocation SL) {}
10317   void visitTrivial(QualType FT, SourceLocation SL) {}
10318   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
10319 
10320   static void diag(QualType RT, const Expr *E, Sema &S) {
10321     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
10322   }
10323 
10324   ASTContext &getContext() { return S.getASTContext(); }
10325 
10326   const Expr *E;
10327   Sema &S;
10328 };
10329 
10330 }
10331 
10332 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
10333 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
10334   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
10335 
10336   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
10337     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
10338       return false;
10339 
10340     return doesExprLikelyComputeSize(BO->getLHS()) ||
10341            doesExprLikelyComputeSize(BO->getRHS());
10342   }
10343 
10344   return getAsSizeOfExpr(SizeofExpr) != nullptr;
10345 }
10346 
10347 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
10348 ///
10349 /// \code
10350 ///   #define MACRO 0
10351 ///   foo(MACRO);
10352 ///   foo(0);
10353 /// \endcode
10354 ///
10355 /// This should return true for the first call to foo, but not for the second
10356 /// (regardless of whether foo is a macro or function).
10357 static bool isArgumentExpandedFromMacro(SourceManager &SM,
10358                                         SourceLocation CallLoc,
10359                                         SourceLocation ArgLoc) {
10360   if (!CallLoc.isMacroID())
10361     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
10362 
10363   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
10364          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
10365 }
10366 
10367 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
10368 /// last two arguments transposed.
10369 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
10370   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
10371     return;
10372 
10373   const Expr *SizeArg =
10374     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
10375 
10376   auto isLiteralZero = [](const Expr *E) {
10377     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
10378   };
10379 
10380   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
10381   SourceLocation CallLoc = Call->getRParenLoc();
10382   SourceManager &SM = S.getSourceManager();
10383   if (isLiteralZero(SizeArg) &&
10384       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
10385 
10386     SourceLocation DiagLoc = SizeArg->getExprLoc();
10387 
10388     // Some platforms #define bzero to __builtin_memset. See if this is the
10389     // case, and if so, emit a better diagnostic.
10390     if (BId == Builtin::BIbzero ||
10391         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
10392                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
10393       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
10394       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
10395     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
10396       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
10397       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
10398     }
10399     return;
10400   }
10401 
10402   // If the second argument to a memset is a sizeof expression and the third
10403   // isn't, this is also likely an error. This should catch
10404   // 'memset(buf, sizeof(buf), 0xff)'.
10405   if (BId == Builtin::BImemset &&
10406       doesExprLikelyComputeSize(Call->getArg(1)) &&
10407       !doesExprLikelyComputeSize(Call->getArg(2))) {
10408     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
10409     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
10410     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
10411     return;
10412   }
10413 }
10414 
10415 /// Check for dangerous or invalid arguments to memset().
10416 ///
10417 /// This issues warnings on known problematic, dangerous or unspecified
10418 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
10419 /// function calls.
10420 ///
10421 /// \param Call The call expression to diagnose.
10422 void Sema::CheckMemaccessArguments(const CallExpr *Call,
10423                                    unsigned BId,
10424                                    IdentifierInfo *FnName) {
10425   assert(BId != 0);
10426 
10427   // It is possible to have a non-standard definition of memset.  Validate
10428   // we have enough arguments, and if not, abort further checking.
10429   unsigned ExpectedNumArgs =
10430       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
10431   if (Call->getNumArgs() < ExpectedNumArgs)
10432     return;
10433 
10434   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
10435                       BId == Builtin::BIstrndup ? 1 : 2);
10436   unsigned LenArg =
10437       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
10438   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
10439 
10440   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
10441                                      Call->getBeginLoc(), Call->getRParenLoc()))
10442     return;
10443 
10444   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
10445   CheckMemaccessSize(*this, BId, Call);
10446 
10447   // We have special checking when the length is a sizeof expression.
10448   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
10449   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
10450   llvm::FoldingSetNodeID SizeOfArgID;
10451 
10452   // Although widely used, 'bzero' is not a standard function. Be more strict
10453   // with the argument types before allowing diagnostics and only allow the
10454   // form bzero(ptr, sizeof(...)).
10455   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
10456   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
10457     return;
10458 
10459   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
10460     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
10461     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
10462 
10463     QualType DestTy = Dest->getType();
10464     QualType PointeeTy;
10465     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
10466       PointeeTy = DestPtrTy->getPointeeType();
10467 
10468       // Never warn about void type pointers. This can be used to suppress
10469       // false positives.
10470       if (PointeeTy->isVoidType())
10471         continue;
10472 
10473       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
10474       // actually comparing the expressions for equality. Because computing the
10475       // expression IDs can be expensive, we only do this if the diagnostic is
10476       // enabled.
10477       if (SizeOfArg &&
10478           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
10479                            SizeOfArg->getExprLoc())) {
10480         // We only compute IDs for expressions if the warning is enabled, and
10481         // cache the sizeof arg's ID.
10482         if (SizeOfArgID == llvm::FoldingSetNodeID())
10483           SizeOfArg->Profile(SizeOfArgID, Context, true);
10484         llvm::FoldingSetNodeID DestID;
10485         Dest->Profile(DestID, Context, true);
10486         if (DestID == SizeOfArgID) {
10487           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
10488           //       over sizeof(src) as well.
10489           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
10490           StringRef ReadableName = FnName->getName();
10491 
10492           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
10493             if (UnaryOp->getOpcode() == UO_AddrOf)
10494               ActionIdx = 1; // If its an address-of operator, just remove it.
10495           if (!PointeeTy->isIncompleteType() &&
10496               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
10497             ActionIdx = 2; // If the pointee's size is sizeof(char),
10498                            // suggest an explicit length.
10499 
10500           // If the function is defined as a builtin macro, do not show macro
10501           // expansion.
10502           SourceLocation SL = SizeOfArg->getExprLoc();
10503           SourceRange DSR = Dest->getSourceRange();
10504           SourceRange SSR = SizeOfArg->getSourceRange();
10505           SourceManager &SM = getSourceManager();
10506 
10507           if (SM.isMacroArgExpansion(SL)) {
10508             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
10509             SL = SM.getSpellingLoc(SL);
10510             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
10511                              SM.getSpellingLoc(DSR.getEnd()));
10512             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
10513                              SM.getSpellingLoc(SSR.getEnd()));
10514           }
10515 
10516           DiagRuntimeBehavior(SL, SizeOfArg,
10517                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
10518                                 << ReadableName
10519                                 << PointeeTy
10520                                 << DestTy
10521                                 << DSR
10522                                 << SSR);
10523           DiagRuntimeBehavior(SL, SizeOfArg,
10524                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
10525                                 << ActionIdx
10526                                 << SSR);
10527 
10528           break;
10529         }
10530       }
10531 
10532       // Also check for cases where the sizeof argument is the exact same
10533       // type as the memory argument, and where it points to a user-defined
10534       // record type.
10535       if (SizeOfArgTy != QualType()) {
10536         if (PointeeTy->isRecordType() &&
10537             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
10538           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
10539                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
10540                                 << FnName << SizeOfArgTy << ArgIdx
10541                                 << PointeeTy << Dest->getSourceRange()
10542                                 << LenExpr->getSourceRange());
10543           break;
10544         }
10545       }
10546     } else if (DestTy->isArrayType()) {
10547       PointeeTy = DestTy;
10548     }
10549 
10550     if (PointeeTy == QualType())
10551       continue;
10552 
10553     // Always complain about dynamic classes.
10554     bool IsContained;
10555     if (const CXXRecordDecl *ContainedRD =
10556             getContainedDynamicClass(PointeeTy, IsContained)) {
10557 
10558       unsigned OperationType = 0;
10559       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
10560       // "overwritten" if we're warning about the destination for any call
10561       // but memcmp; otherwise a verb appropriate to the call.
10562       if (ArgIdx != 0 || IsCmp) {
10563         if (BId == Builtin::BImemcpy)
10564           OperationType = 1;
10565         else if(BId == Builtin::BImemmove)
10566           OperationType = 2;
10567         else if (IsCmp)
10568           OperationType = 3;
10569       }
10570 
10571       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10572                           PDiag(diag::warn_dyn_class_memaccess)
10573                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
10574                               << IsContained << ContainedRD << OperationType
10575                               << Call->getCallee()->getSourceRange());
10576     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
10577              BId != Builtin::BImemset)
10578       DiagRuntimeBehavior(
10579         Dest->getExprLoc(), Dest,
10580         PDiag(diag::warn_arc_object_memaccess)
10581           << ArgIdx << FnName << PointeeTy
10582           << Call->getCallee()->getSourceRange());
10583     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
10584       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
10585           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
10586         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10587                             PDiag(diag::warn_cstruct_memaccess)
10588                                 << ArgIdx << FnName << PointeeTy << 0);
10589         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
10590       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
10591                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
10592         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10593                             PDiag(diag::warn_cstruct_memaccess)
10594                                 << ArgIdx << FnName << PointeeTy << 1);
10595         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10596       } else {
10597         continue;
10598       }
10599     } else
10600       continue;
10601 
10602     DiagRuntimeBehavior(
10603       Dest->getExprLoc(), Dest,
10604       PDiag(diag::note_bad_memaccess_silence)
10605         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10606     break;
10607   }
10608 }
10609 
10610 // A little helper routine: ignore addition and subtraction of integer literals.
10611 // This intentionally does not ignore all integer constant expressions because
10612 // we don't want to remove sizeof().
10613 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10614   Ex = Ex->IgnoreParenCasts();
10615 
10616   while (true) {
10617     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10618     if (!BO || !BO->isAdditiveOp())
10619       break;
10620 
10621     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10622     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10623 
10624     if (isa<IntegerLiteral>(RHS))
10625       Ex = LHS;
10626     else if (isa<IntegerLiteral>(LHS))
10627       Ex = RHS;
10628     else
10629       break;
10630   }
10631 
10632   return Ex;
10633 }
10634 
10635 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10636                                                       ASTContext &Context) {
10637   // Only handle constant-sized or VLAs, but not flexible members.
10638   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10639     // Only issue the FIXIT for arrays of size > 1.
10640     if (CAT->getSize().getSExtValue() <= 1)
10641       return false;
10642   } else if (!Ty->isVariableArrayType()) {
10643     return false;
10644   }
10645   return true;
10646 }
10647 
10648 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10649 // be the size of the source, instead of the destination.
10650 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10651                                     IdentifierInfo *FnName) {
10652 
10653   // Don't crash if the user has the wrong number of arguments
10654   unsigned NumArgs = Call->getNumArgs();
10655   if ((NumArgs != 3) && (NumArgs != 4))
10656     return;
10657 
10658   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10659   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10660   const Expr *CompareWithSrc = nullptr;
10661 
10662   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10663                                      Call->getBeginLoc(), Call->getRParenLoc()))
10664     return;
10665 
10666   // Look for 'strlcpy(dst, x, sizeof(x))'
10667   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10668     CompareWithSrc = Ex;
10669   else {
10670     // Look for 'strlcpy(dst, x, strlen(x))'
10671     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10672       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10673           SizeCall->getNumArgs() == 1)
10674         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10675     }
10676   }
10677 
10678   if (!CompareWithSrc)
10679     return;
10680 
10681   // Determine if the argument to sizeof/strlen is equal to the source
10682   // argument.  In principle there's all kinds of things you could do
10683   // here, for instance creating an == expression and evaluating it with
10684   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10685   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10686   if (!SrcArgDRE)
10687     return;
10688 
10689   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10690   if (!CompareWithSrcDRE ||
10691       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10692     return;
10693 
10694   const Expr *OriginalSizeArg = Call->getArg(2);
10695   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10696       << OriginalSizeArg->getSourceRange() << FnName;
10697 
10698   // Output a FIXIT hint if the destination is an array (rather than a
10699   // pointer to an array).  This could be enhanced to handle some
10700   // pointers if we know the actual size, like if DstArg is 'array+2'
10701   // we could say 'sizeof(array)-2'.
10702   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10703   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10704     return;
10705 
10706   SmallString<128> sizeString;
10707   llvm::raw_svector_ostream OS(sizeString);
10708   OS << "sizeof(";
10709   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10710   OS << ")";
10711 
10712   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10713       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10714                                       OS.str());
10715 }
10716 
10717 /// Check if two expressions refer to the same declaration.
10718 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10719   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10720     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10721       return D1->getDecl() == D2->getDecl();
10722   return false;
10723 }
10724 
10725 static const Expr *getStrlenExprArg(const Expr *E) {
10726   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10727     const FunctionDecl *FD = CE->getDirectCallee();
10728     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10729       return nullptr;
10730     return CE->getArg(0)->IgnoreParenCasts();
10731   }
10732   return nullptr;
10733 }
10734 
10735 // Warn on anti-patterns as the 'size' argument to strncat.
10736 // The correct size argument should look like following:
10737 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10738 void Sema::CheckStrncatArguments(const CallExpr *CE,
10739                                  IdentifierInfo *FnName) {
10740   // Don't crash if the user has the wrong number of arguments.
10741   if (CE->getNumArgs() < 3)
10742     return;
10743   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10744   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10745   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10746 
10747   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10748                                      CE->getRParenLoc()))
10749     return;
10750 
10751   // Identify common expressions, which are wrongly used as the size argument
10752   // to strncat and may lead to buffer overflows.
10753   unsigned PatternType = 0;
10754   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10755     // - sizeof(dst)
10756     if (referToTheSameDecl(SizeOfArg, DstArg))
10757       PatternType = 1;
10758     // - sizeof(src)
10759     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10760       PatternType = 2;
10761   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10762     if (BE->getOpcode() == BO_Sub) {
10763       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10764       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10765       // - sizeof(dst) - strlen(dst)
10766       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10767           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10768         PatternType = 1;
10769       // - sizeof(src) - (anything)
10770       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10771         PatternType = 2;
10772     }
10773   }
10774 
10775   if (PatternType == 0)
10776     return;
10777 
10778   // Generate the diagnostic.
10779   SourceLocation SL = LenArg->getBeginLoc();
10780   SourceRange SR = LenArg->getSourceRange();
10781   SourceManager &SM = getSourceManager();
10782 
10783   // If the function is defined as a builtin macro, do not show macro expansion.
10784   if (SM.isMacroArgExpansion(SL)) {
10785     SL = SM.getSpellingLoc(SL);
10786     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10787                      SM.getSpellingLoc(SR.getEnd()));
10788   }
10789 
10790   // Check if the destination is an array (rather than a pointer to an array).
10791   QualType DstTy = DstArg->getType();
10792   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10793                                                                     Context);
10794   if (!isKnownSizeArray) {
10795     if (PatternType == 1)
10796       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10797     else
10798       Diag(SL, diag::warn_strncat_src_size) << SR;
10799     return;
10800   }
10801 
10802   if (PatternType == 1)
10803     Diag(SL, diag::warn_strncat_large_size) << SR;
10804   else
10805     Diag(SL, diag::warn_strncat_src_size) << SR;
10806 
10807   SmallString<128> sizeString;
10808   llvm::raw_svector_ostream OS(sizeString);
10809   OS << "sizeof(";
10810   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10811   OS << ") - ";
10812   OS << "strlen(";
10813   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10814   OS << ") - 1";
10815 
10816   Diag(SL, diag::note_strncat_wrong_size)
10817     << FixItHint::CreateReplacement(SR, OS.str());
10818 }
10819 
10820 namespace {
10821 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10822                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10823   if (isa<FieldDecl, FunctionDecl, VarDecl>(D)) {
10824     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10825         << CalleeName << 0 /*object: */ << cast<NamedDecl>(D);
10826     return;
10827   }
10828 }
10829 
10830 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10831                                  const UnaryOperator *UnaryExpr) {
10832   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr())) {
10833     const Decl *D = Lvalue->getDecl();
10834     if (isa<DeclaratorDecl>(D))
10835       if (!dyn_cast<DeclaratorDecl>(D)->getType()->isReferenceType())
10836         return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, D);
10837   }
10838 
10839   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10840     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10841                                       Lvalue->getMemberDecl());
10842 }
10843 
10844 void CheckFreeArgumentsPlus(Sema &S, const std::string &CalleeName,
10845                             const UnaryOperator *UnaryExpr) {
10846   const auto *Lambda = dyn_cast<LambdaExpr>(
10847       UnaryExpr->getSubExpr()->IgnoreImplicitAsWritten()->IgnoreParens());
10848   if (!Lambda)
10849     return;
10850 
10851   S.Diag(Lambda->getBeginLoc(), diag::warn_free_nonheap_object)
10852       << CalleeName << 2 /*object: lambda expression*/;
10853 }
10854 
10855 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10856                                   const DeclRefExpr *Lvalue) {
10857   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10858   if (Var == nullptr)
10859     return;
10860 
10861   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10862       << CalleeName << 0 /*object: */ << Var;
10863 }
10864 
10865 void CheckFreeArgumentsCast(Sema &S, const std::string &CalleeName,
10866                             const CastExpr *Cast) {
10867   SmallString<128> SizeString;
10868   llvm::raw_svector_ostream OS(SizeString);
10869 
10870   clang::CastKind Kind = Cast->getCastKind();
10871   if (Kind == clang::CK_BitCast &&
10872       !Cast->getSubExpr()->getType()->isFunctionPointerType())
10873     return;
10874   if (Kind == clang::CK_IntegralToPointer &&
10875       !isa<IntegerLiteral>(
10876           Cast->getSubExpr()->IgnoreParenImpCasts()->IgnoreParens()))
10877     return;
10878 
10879   switch (Cast->getCastKind()) {
10880   case clang::CK_BitCast:
10881   case clang::CK_IntegralToPointer:
10882   case clang::CK_FunctionToPointerDecay:
10883     OS << '\'';
10884     Cast->printPretty(OS, nullptr, S.getPrintingPolicy());
10885     OS << '\'';
10886     break;
10887   default:
10888     return;
10889   }
10890 
10891   S.Diag(Cast->getBeginLoc(), diag::warn_free_nonheap_object)
10892       << CalleeName << 0 /*object: */ << OS.str();
10893 }
10894 } // namespace
10895 
10896 /// Alerts the user that they are attempting to free a non-malloc'd object.
10897 void Sema::CheckFreeArguments(const CallExpr *E) {
10898   const std::string CalleeName =
10899       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10900 
10901   { // Prefer something that doesn't involve a cast to make things simpler.
10902     const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10903     if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10904       switch (UnaryExpr->getOpcode()) {
10905       case UnaryOperator::Opcode::UO_AddrOf:
10906         return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10907       case UnaryOperator::Opcode::UO_Plus:
10908         return CheckFreeArgumentsPlus(*this, CalleeName, UnaryExpr);
10909       default:
10910         break;
10911       }
10912 
10913     if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10914       if (Lvalue->getType()->isArrayType())
10915         return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10916 
10917     if (const auto *Label = dyn_cast<AddrLabelExpr>(Arg)) {
10918       Diag(Label->getBeginLoc(), diag::warn_free_nonheap_object)
10919           << CalleeName << 0 /*object: */ << Label->getLabel()->getIdentifier();
10920       return;
10921     }
10922 
10923     if (isa<BlockExpr>(Arg)) {
10924       Diag(Arg->getBeginLoc(), diag::warn_free_nonheap_object)
10925           << CalleeName << 1 /*object: block*/;
10926       return;
10927     }
10928   }
10929   // Maybe the cast was important, check after the other cases.
10930   if (const auto *Cast = dyn_cast<CastExpr>(E->getArg(0)))
10931     return CheckFreeArgumentsCast(*this, CalleeName, Cast);
10932 }
10933 
10934 void
10935 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10936                          SourceLocation ReturnLoc,
10937                          bool isObjCMethod,
10938                          const AttrVec *Attrs,
10939                          const FunctionDecl *FD) {
10940   // Check if the return value is null but should not be.
10941   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10942        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10943       CheckNonNullExpr(*this, RetValExp))
10944     Diag(ReturnLoc, diag::warn_null_ret)
10945       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10946 
10947   // C++11 [basic.stc.dynamic.allocation]p4:
10948   //   If an allocation function declared with a non-throwing
10949   //   exception-specification fails to allocate storage, it shall return
10950   //   a null pointer. Any other allocation function that fails to allocate
10951   //   storage shall indicate failure only by throwing an exception [...]
10952   if (FD) {
10953     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10954     if (Op == OO_New || Op == OO_Array_New) {
10955       const FunctionProtoType *Proto
10956         = FD->getType()->castAs<FunctionProtoType>();
10957       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10958           CheckNonNullExpr(*this, RetValExp))
10959         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10960           << FD << getLangOpts().CPlusPlus11;
10961     }
10962   }
10963 
10964   // PPC MMA non-pointer types are not allowed as return type. Checking the type
10965   // here prevent the user from using a PPC MMA type as trailing return type.
10966   if (Context.getTargetInfo().getTriple().isPPC64())
10967     CheckPPCMMAType(RetValExp->getType(), ReturnLoc);
10968 }
10969 
10970 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10971 
10972 /// Check for comparisons of floating point operands using != and ==.
10973 /// Issue a warning if these are no self-comparisons, as they are not likely
10974 /// to do what the programmer intended.
10975 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10976   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10977   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10978 
10979   // Special case: check for x == x (which is OK).
10980   // Do not emit warnings for such cases.
10981   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10982     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10983       if (DRL->getDecl() == DRR->getDecl())
10984         return;
10985 
10986   // Special case: check for comparisons against literals that can be exactly
10987   //  represented by APFloat.  In such cases, do not emit a warning.  This
10988   //  is a heuristic: often comparison against such literals are used to
10989   //  detect if a value in a variable has not changed.  This clearly can
10990   //  lead to false negatives.
10991   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10992     if (FLL->isExact())
10993       return;
10994   } else
10995     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10996       if (FLR->isExact())
10997         return;
10998 
10999   // Check for comparisons with builtin types.
11000   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
11001     if (CL->getBuiltinCallee())
11002       return;
11003 
11004   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
11005     if (CR->getBuiltinCallee())
11006       return;
11007 
11008   // Emit the diagnostic.
11009   Diag(Loc, diag::warn_floatingpoint_eq)
11010     << LHS->getSourceRange() << RHS->getSourceRange();
11011 }
11012 
11013 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
11014 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
11015 
11016 namespace {
11017 
11018 /// Structure recording the 'active' range of an integer-valued
11019 /// expression.
11020 struct IntRange {
11021   /// The number of bits active in the int. Note that this includes exactly one
11022   /// sign bit if !NonNegative.
11023   unsigned Width;
11024 
11025   /// True if the int is known not to have negative values. If so, all leading
11026   /// bits before Width are known zero, otherwise they are known to be the
11027   /// same as the MSB within Width.
11028   bool NonNegative;
11029 
11030   IntRange(unsigned Width, bool NonNegative)
11031       : Width(Width), NonNegative(NonNegative) {}
11032 
11033   /// Number of bits excluding the sign bit.
11034   unsigned valueBits() const {
11035     return NonNegative ? Width : Width - 1;
11036   }
11037 
11038   /// Returns the range of the bool type.
11039   static IntRange forBoolType() {
11040     return IntRange(1, true);
11041   }
11042 
11043   /// Returns the range of an opaque value of the given integral type.
11044   static IntRange forValueOfType(ASTContext &C, QualType T) {
11045     return forValueOfCanonicalType(C,
11046                           T->getCanonicalTypeInternal().getTypePtr());
11047   }
11048 
11049   /// Returns the range of an opaque value of a canonical integral type.
11050   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
11051     assert(T->isCanonicalUnqualified());
11052 
11053     if (const VectorType *VT = dyn_cast<VectorType>(T))
11054       T = VT->getElementType().getTypePtr();
11055     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11056       T = CT->getElementType().getTypePtr();
11057     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11058       T = AT->getValueType().getTypePtr();
11059 
11060     if (!C.getLangOpts().CPlusPlus) {
11061       // For enum types in C code, use the underlying datatype.
11062       if (const EnumType *ET = dyn_cast<EnumType>(T))
11063         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
11064     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
11065       // For enum types in C++, use the known bit width of the enumerators.
11066       EnumDecl *Enum = ET->getDecl();
11067       // In C++11, enums can have a fixed underlying type. Use this type to
11068       // compute the range.
11069       if (Enum->isFixed()) {
11070         return IntRange(C.getIntWidth(QualType(T, 0)),
11071                         !ET->isSignedIntegerOrEnumerationType());
11072       }
11073 
11074       unsigned NumPositive = Enum->getNumPositiveBits();
11075       unsigned NumNegative = Enum->getNumNegativeBits();
11076 
11077       if (NumNegative == 0)
11078         return IntRange(NumPositive, true/*NonNegative*/);
11079       else
11080         return IntRange(std::max(NumPositive + 1, NumNegative),
11081                         false/*NonNegative*/);
11082     }
11083 
11084     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11085       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11086 
11087     const BuiltinType *BT = cast<BuiltinType>(T);
11088     assert(BT->isInteger());
11089 
11090     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11091   }
11092 
11093   /// Returns the "target" range of a canonical integral type, i.e.
11094   /// the range of values expressible in the type.
11095   ///
11096   /// This matches forValueOfCanonicalType except that enums have the
11097   /// full range of their type, not the range of their enumerators.
11098   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
11099     assert(T->isCanonicalUnqualified());
11100 
11101     if (const VectorType *VT = dyn_cast<VectorType>(T))
11102       T = VT->getElementType().getTypePtr();
11103     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
11104       T = CT->getElementType().getTypePtr();
11105     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
11106       T = AT->getValueType().getTypePtr();
11107     if (const EnumType *ET = dyn_cast<EnumType>(T))
11108       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
11109 
11110     if (const auto *EIT = dyn_cast<ExtIntType>(T))
11111       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
11112 
11113     const BuiltinType *BT = cast<BuiltinType>(T);
11114     assert(BT->isInteger());
11115 
11116     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
11117   }
11118 
11119   /// Returns the supremum of two ranges: i.e. their conservative merge.
11120   static IntRange join(IntRange L, IntRange R) {
11121     bool Unsigned = L.NonNegative && R.NonNegative;
11122     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
11123                     L.NonNegative && R.NonNegative);
11124   }
11125 
11126   /// Return the range of a bitwise-AND of the two ranges.
11127   static IntRange bit_and(IntRange L, IntRange R) {
11128     unsigned Bits = std::max(L.Width, R.Width);
11129     bool NonNegative = false;
11130     if (L.NonNegative) {
11131       Bits = std::min(Bits, L.Width);
11132       NonNegative = true;
11133     }
11134     if (R.NonNegative) {
11135       Bits = std::min(Bits, R.Width);
11136       NonNegative = true;
11137     }
11138     return IntRange(Bits, NonNegative);
11139   }
11140 
11141   /// Return the range of a sum of the two ranges.
11142   static IntRange sum(IntRange L, IntRange R) {
11143     bool Unsigned = L.NonNegative && R.NonNegative;
11144     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
11145                     Unsigned);
11146   }
11147 
11148   /// Return the range of a difference of the two ranges.
11149   static IntRange difference(IntRange L, IntRange R) {
11150     // We need a 1-bit-wider range if:
11151     //   1) LHS can be negative: least value can be reduced.
11152     //   2) RHS can be negative: greatest value can be increased.
11153     bool CanWiden = !L.NonNegative || !R.NonNegative;
11154     bool Unsigned = L.NonNegative && R.Width == 0;
11155     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
11156                         !Unsigned,
11157                     Unsigned);
11158   }
11159 
11160   /// Return the range of a product of the two ranges.
11161   static IntRange product(IntRange L, IntRange R) {
11162     // If both LHS and RHS can be negative, we can form
11163     //   -2^L * -2^R = 2^(L + R)
11164     // which requires L + R + 1 value bits to represent.
11165     bool CanWiden = !L.NonNegative && !R.NonNegative;
11166     bool Unsigned = L.NonNegative && R.NonNegative;
11167     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
11168                     Unsigned);
11169   }
11170 
11171   /// Return the range of a remainder operation between the two ranges.
11172   static IntRange rem(IntRange L, IntRange R) {
11173     // The result of a remainder can't be larger than the result of
11174     // either side. The sign of the result is the sign of the LHS.
11175     bool Unsigned = L.NonNegative;
11176     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
11177                     Unsigned);
11178   }
11179 };
11180 
11181 } // namespace
11182 
11183 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
11184                               unsigned MaxWidth) {
11185   if (value.isSigned() && value.isNegative())
11186     return IntRange(value.getMinSignedBits(), false);
11187 
11188   if (value.getBitWidth() > MaxWidth)
11189     value = value.trunc(MaxWidth);
11190 
11191   // isNonNegative() just checks the sign bit without considering
11192   // signedness.
11193   return IntRange(value.getActiveBits(), true);
11194 }
11195 
11196 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
11197                               unsigned MaxWidth) {
11198   if (result.isInt())
11199     return GetValueRange(C, result.getInt(), MaxWidth);
11200 
11201   if (result.isVector()) {
11202     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
11203     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
11204       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
11205       R = IntRange::join(R, El);
11206     }
11207     return R;
11208   }
11209 
11210   if (result.isComplexInt()) {
11211     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
11212     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
11213     return IntRange::join(R, I);
11214   }
11215 
11216   // This can happen with lossless casts to intptr_t of "based" lvalues.
11217   // Assume it might use arbitrary bits.
11218   // FIXME: The only reason we need to pass the type in here is to get
11219   // the sign right on this one case.  It would be nice if APValue
11220   // preserved this.
11221   assert(result.isLValue() || result.isAddrLabelDiff());
11222   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
11223 }
11224 
11225 static QualType GetExprType(const Expr *E) {
11226   QualType Ty = E->getType();
11227   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
11228     Ty = AtomicRHS->getValueType();
11229   return Ty;
11230 }
11231 
11232 /// Pseudo-evaluate the given integer expression, estimating the
11233 /// range of values it might take.
11234 ///
11235 /// \param MaxWidth The width to which the value will be truncated.
11236 /// \param Approximate If \c true, return a likely range for the result: in
11237 ///        particular, assume that arithmetic on narrower types doesn't leave
11238 ///        those types. If \c false, return a range including all possible
11239 ///        result values.
11240 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
11241                              bool InConstantContext, bool Approximate) {
11242   E = E->IgnoreParens();
11243 
11244   // Try a full evaluation first.
11245   Expr::EvalResult result;
11246   if (E->EvaluateAsRValue(result, C, InConstantContext))
11247     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
11248 
11249   // I think we only want to look through implicit casts here; if the
11250   // user has an explicit widening cast, we should treat the value as
11251   // being of the new, wider type.
11252   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
11253     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
11254       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
11255                           Approximate);
11256 
11257     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
11258 
11259     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
11260                          CE->getCastKind() == CK_BooleanToSignedIntegral;
11261 
11262     // Assume that non-integer casts can span the full range of the type.
11263     if (!isIntegerCast)
11264       return OutputTypeRange;
11265 
11266     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
11267                                      std::min(MaxWidth, OutputTypeRange.Width),
11268                                      InConstantContext, Approximate);
11269 
11270     // Bail out if the subexpr's range is as wide as the cast type.
11271     if (SubRange.Width >= OutputTypeRange.Width)
11272       return OutputTypeRange;
11273 
11274     // Otherwise, we take the smaller width, and we're non-negative if
11275     // either the output type or the subexpr is.
11276     return IntRange(SubRange.Width,
11277                     SubRange.NonNegative || OutputTypeRange.NonNegative);
11278   }
11279 
11280   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11281     // If we can fold the condition, just take that operand.
11282     bool CondResult;
11283     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
11284       return GetExprRange(C,
11285                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
11286                           MaxWidth, InConstantContext, Approximate);
11287 
11288     // Otherwise, conservatively merge.
11289     // GetExprRange requires an integer expression, but a throw expression
11290     // results in a void type.
11291     Expr *E = CO->getTrueExpr();
11292     IntRange L = E->getType()->isVoidType()
11293                      ? IntRange{0, true}
11294                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11295     E = CO->getFalseExpr();
11296     IntRange R = E->getType()->isVoidType()
11297                      ? IntRange{0, true}
11298                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
11299     return IntRange::join(L, R);
11300   }
11301 
11302   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11303     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
11304 
11305     switch (BO->getOpcode()) {
11306     case BO_Cmp:
11307       llvm_unreachable("builtin <=> should have class type");
11308 
11309     // Boolean-valued operations are single-bit and positive.
11310     case BO_LAnd:
11311     case BO_LOr:
11312     case BO_LT:
11313     case BO_GT:
11314     case BO_LE:
11315     case BO_GE:
11316     case BO_EQ:
11317     case BO_NE:
11318       return IntRange::forBoolType();
11319 
11320     // The type of the assignments is the type of the LHS, so the RHS
11321     // is not necessarily the same type.
11322     case BO_MulAssign:
11323     case BO_DivAssign:
11324     case BO_RemAssign:
11325     case BO_AddAssign:
11326     case BO_SubAssign:
11327     case BO_XorAssign:
11328     case BO_OrAssign:
11329       // TODO: bitfields?
11330       return IntRange::forValueOfType(C, GetExprType(E));
11331 
11332     // Simple assignments just pass through the RHS, which will have
11333     // been coerced to the LHS type.
11334     case BO_Assign:
11335       // TODO: bitfields?
11336       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11337                           Approximate);
11338 
11339     // Operations with opaque sources are black-listed.
11340     case BO_PtrMemD:
11341     case BO_PtrMemI:
11342       return IntRange::forValueOfType(C, GetExprType(E));
11343 
11344     // Bitwise-and uses the *infinum* of the two source ranges.
11345     case BO_And:
11346     case BO_AndAssign:
11347       Combine = IntRange::bit_and;
11348       break;
11349 
11350     // Left shift gets black-listed based on a judgement call.
11351     case BO_Shl:
11352       // ...except that we want to treat '1 << (blah)' as logically
11353       // positive.  It's an important idiom.
11354       if (IntegerLiteral *I
11355             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
11356         if (I->getValue() == 1) {
11357           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
11358           return IntRange(R.Width, /*NonNegative*/ true);
11359         }
11360       }
11361       LLVM_FALLTHROUGH;
11362 
11363     case BO_ShlAssign:
11364       return IntRange::forValueOfType(C, GetExprType(E));
11365 
11366     // Right shift by a constant can narrow its left argument.
11367     case BO_Shr:
11368     case BO_ShrAssign: {
11369       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
11370                                 Approximate);
11371 
11372       // If the shift amount is a positive constant, drop the width by
11373       // that much.
11374       if (Optional<llvm::APSInt> shift =
11375               BO->getRHS()->getIntegerConstantExpr(C)) {
11376         if (shift->isNonNegative()) {
11377           unsigned zext = shift->getZExtValue();
11378           if (zext >= L.Width)
11379             L.Width = (L.NonNegative ? 0 : 1);
11380           else
11381             L.Width -= zext;
11382         }
11383       }
11384 
11385       return L;
11386     }
11387 
11388     // Comma acts as its right operand.
11389     case BO_Comma:
11390       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
11391                           Approximate);
11392 
11393     case BO_Add:
11394       if (!Approximate)
11395         Combine = IntRange::sum;
11396       break;
11397 
11398     case BO_Sub:
11399       if (BO->getLHS()->getType()->isPointerType())
11400         return IntRange::forValueOfType(C, GetExprType(E));
11401       if (!Approximate)
11402         Combine = IntRange::difference;
11403       break;
11404 
11405     case BO_Mul:
11406       if (!Approximate)
11407         Combine = IntRange::product;
11408       break;
11409 
11410     // The width of a division result is mostly determined by the size
11411     // of the LHS.
11412     case BO_Div: {
11413       // Don't 'pre-truncate' the operands.
11414       unsigned opWidth = C.getIntWidth(GetExprType(E));
11415       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
11416                                 Approximate);
11417 
11418       // If the divisor is constant, use that.
11419       if (Optional<llvm::APSInt> divisor =
11420               BO->getRHS()->getIntegerConstantExpr(C)) {
11421         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
11422         if (log2 >= L.Width)
11423           L.Width = (L.NonNegative ? 0 : 1);
11424         else
11425           L.Width = std::min(L.Width - log2, MaxWidth);
11426         return L;
11427       }
11428 
11429       // Otherwise, just use the LHS's width.
11430       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
11431       // could be -1.
11432       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
11433                                 Approximate);
11434       return IntRange(L.Width, L.NonNegative && R.NonNegative);
11435     }
11436 
11437     case BO_Rem:
11438       Combine = IntRange::rem;
11439       break;
11440 
11441     // The default behavior is okay for these.
11442     case BO_Xor:
11443     case BO_Or:
11444       break;
11445     }
11446 
11447     // Combine the two ranges, but limit the result to the type in which we
11448     // performed the computation.
11449     QualType T = GetExprType(E);
11450     unsigned opWidth = C.getIntWidth(T);
11451     IntRange L =
11452         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
11453     IntRange R =
11454         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
11455     IntRange C = Combine(L, R);
11456     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
11457     C.Width = std::min(C.Width, MaxWidth);
11458     return C;
11459   }
11460 
11461   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
11462     switch (UO->getOpcode()) {
11463     // Boolean-valued operations are white-listed.
11464     case UO_LNot:
11465       return IntRange::forBoolType();
11466 
11467     // Operations with opaque sources are black-listed.
11468     case UO_Deref:
11469     case UO_AddrOf: // should be impossible
11470       return IntRange::forValueOfType(C, GetExprType(E));
11471 
11472     default:
11473       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
11474                           Approximate);
11475     }
11476   }
11477 
11478   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
11479     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
11480                         Approximate);
11481 
11482   if (const auto *BitField = E->getSourceBitField())
11483     return IntRange(BitField->getBitWidthValue(C),
11484                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
11485 
11486   return IntRange::forValueOfType(C, GetExprType(E));
11487 }
11488 
11489 static IntRange GetExprRange(ASTContext &C, const Expr *E,
11490                              bool InConstantContext, bool Approximate) {
11491   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
11492                       Approximate);
11493 }
11494 
11495 /// Checks whether the given value, which currently has the given
11496 /// source semantics, has the same value when coerced through the
11497 /// target semantics.
11498 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
11499                                  const llvm::fltSemantics &Src,
11500                                  const llvm::fltSemantics &Tgt) {
11501   llvm::APFloat truncated = value;
11502 
11503   bool ignored;
11504   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
11505   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
11506 
11507   return truncated.bitwiseIsEqual(value);
11508 }
11509 
11510 /// Checks whether the given value, which currently has the given
11511 /// source semantics, has the same value when coerced through the
11512 /// target semantics.
11513 ///
11514 /// The value might be a vector of floats (or a complex number).
11515 static bool IsSameFloatAfterCast(const APValue &value,
11516                                  const llvm::fltSemantics &Src,
11517                                  const llvm::fltSemantics &Tgt) {
11518   if (value.isFloat())
11519     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
11520 
11521   if (value.isVector()) {
11522     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
11523       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
11524         return false;
11525     return true;
11526   }
11527 
11528   assert(value.isComplexFloat());
11529   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
11530           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
11531 }
11532 
11533 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
11534                                        bool IsListInit = false);
11535 
11536 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
11537   // Suppress cases where we are comparing against an enum constant.
11538   if (const DeclRefExpr *DR =
11539       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
11540     if (isa<EnumConstantDecl>(DR->getDecl()))
11541       return true;
11542 
11543   // Suppress cases where the value is expanded from a macro, unless that macro
11544   // is how a language represents a boolean literal. This is the case in both C
11545   // and Objective-C.
11546   SourceLocation BeginLoc = E->getBeginLoc();
11547   if (BeginLoc.isMacroID()) {
11548     StringRef MacroName = Lexer::getImmediateMacroName(
11549         BeginLoc, S.getSourceManager(), S.getLangOpts());
11550     return MacroName != "YES" && MacroName != "NO" &&
11551            MacroName != "true" && MacroName != "false";
11552   }
11553 
11554   return false;
11555 }
11556 
11557 static bool isKnownToHaveUnsignedValue(Expr *E) {
11558   return E->getType()->isIntegerType() &&
11559          (!E->getType()->isSignedIntegerType() ||
11560           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
11561 }
11562 
11563 namespace {
11564 /// The promoted range of values of a type. In general this has the
11565 /// following structure:
11566 ///
11567 ///     |-----------| . . . |-----------|
11568 ///     ^           ^       ^           ^
11569 ///    Min       HoleMin  HoleMax      Max
11570 ///
11571 /// ... where there is only a hole if a signed type is promoted to unsigned
11572 /// (in which case Min and Max are the smallest and largest representable
11573 /// values).
11574 struct PromotedRange {
11575   // Min, or HoleMax if there is a hole.
11576   llvm::APSInt PromotedMin;
11577   // Max, or HoleMin if there is a hole.
11578   llvm::APSInt PromotedMax;
11579 
11580   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
11581     if (R.Width == 0)
11582       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
11583     else if (R.Width >= BitWidth && !Unsigned) {
11584       // Promotion made the type *narrower*. This happens when promoting
11585       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
11586       // Treat all values of 'signed int' as being in range for now.
11587       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
11588       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
11589     } else {
11590       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
11591                         .extOrTrunc(BitWidth);
11592       PromotedMin.setIsUnsigned(Unsigned);
11593 
11594       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
11595                         .extOrTrunc(BitWidth);
11596       PromotedMax.setIsUnsigned(Unsigned);
11597     }
11598   }
11599 
11600   // Determine whether this range is contiguous (has no hole).
11601   bool isContiguous() const { return PromotedMin <= PromotedMax; }
11602 
11603   // Where a constant value is within the range.
11604   enum ComparisonResult {
11605     LT = 0x1,
11606     LE = 0x2,
11607     GT = 0x4,
11608     GE = 0x8,
11609     EQ = 0x10,
11610     NE = 0x20,
11611     InRangeFlag = 0x40,
11612 
11613     Less = LE | LT | NE,
11614     Min = LE | InRangeFlag,
11615     InRange = InRangeFlag,
11616     Max = GE | InRangeFlag,
11617     Greater = GE | GT | NE,
11618 
11619     OnlyValue = LE | GE | EQ | InRangeFlag,
11620     InHole = NE
11621   };
11622 
11623   ComparisonResult compare(const llvm::APSInt &Value) const {
11624     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
11625            Value.isUnsigned() == PromotedMin.isUnsigned());
11626     if (!isContiguous()) {
11627       assert(Value.isUnsigned() && "discontiguous range for signed compare");
11628       if (Value.isMinValue()) return Min;
11629       if (Value.isMaxValue()) return Max;
11630       if (Value >= PromotedMin) return InRange;
11631       if (Value <= PromotedMax) return InRange;
11632       return InHole;
11633     }
11634 
11635     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
11636     case -1: return Less;
11637     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
11638     case 1:
11639       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
11640       case -1: return InRange;
11641       case 0: return Max;
11642       case 1: return Greater;
11643       }
11644     }
11645 
11646     llvm_unreachable("impossible compare result");
11647   }
11648 
11649   static llvm::Optional<StringRef>
11650   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11651     if (Op == BO_Cmp) {
11652       ComparisonResult LTFlag = LT, GTFlag = GT;
11653       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11654 
11655       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11656       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11657       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11658       return llvm::None;
11659     }
11660 
11661     ComparisonResult TrueFlag, FalseFlag;
11662     if (Op == BO_EQ) {
11663       TrueFlag = EQ;
11664       FalseFlag = NE;
11665     } else if (Op == BO_NE) {
11666       TrueFlag = NE;
11667       FalseFlag = EQ;
11668     } else {
11669       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11670         TrueFlag = LT;
11671         FalseFlag = GE;
11672       } else {
11673         TrueFlag = GT;
11674         FalseFlag = LE;
11675       }
11676       if (Op == BO_GE || Op == BO_LE)
11677         std::swap(TrueFlag, FalseFlag);
11678     }
11679     if (R & TrueFlag)
11680       return StringRef("true");
11681     if (R & FalseFlag)
11682       return StringRef("false");
11683     return llvm::None;
11684   }
11685 };
11686 }
11687 
11688 static bool HasEnumType(Expr *E) {
11689   // Strip off implicit integral promotions.
11690   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11691     if (ICE->getCastKind() != CK_IntegralCast &&
11692         ICE->getCastKind() != CK_NoOp)
11693       break;
11694     E = ICE->getSubExpr();
11695   }
11696 
11697   return E->getType()->isEnumeralType();
11698 }
11699 
11700 static int classifyConstantValue(Expr *Constant) {
11701   // The values of this enumeration are used in the diagnostics
11702   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11703   enum ConstantValueKind {
11704     Miscellaneous = 0,
11705     LiteralTrue,
11706     LiteralFalse
11707   };
11708   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11709     return BL->getValue() ? ConstantValueKind::LiteralTrue
11710                           : ConstantValueKind::LiteralFalse;
11711   return ConstantValueKind::Miscellaneous;
11712 }
11713 
11714 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11715                                         Expr *Constant, Expr *Other,
11716                                         const llvm::APSInt &Value,
11717                                         bool RhsConstant) {
11718   if (S.inTemplateInstantiation())
11719     return false;
11720 
11721   Expr *OriginalOther = Other;
11722 
11723   Constant = Constant->IgnoreParenImpCasts();
11724   Other = Other->IgnoreParenImpCasts();
11725 
11726   // Suppress warnings on tautological comparisons between values of the same
11727   // enumeration type. There are only two ways we could warn on this:
11728   //  - If the constant is outside the range of representable values of
11729   //    the enumeration. In such a case, we should warn about the cast
11730   //    to enumeration type, not about the comparison.
11731   //  - If the constant is the maximum / minimum in-range value. For an
11732   //    enumeratin type, such comparisons can be meaningful and useful.
11733   if (Constant->getType()->isEnumeralType() &&
11734       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11735     return false;
11736 
11737   IntRange OtherValueRange = GetExprRange(
11738       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11739 
11740   QualType OtherT = Other->getType();
11741   if (const auto *AT = OtherT->getAs<AtomicType>())
11742     OtherT = AT->getValueType();
11743   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11744 
11745   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11746   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11747   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11748                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11749                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11750 
11751   // Whether we're treating Other as being a bool because of the form of
11752   // expression despite it having another type (typically 'int' in C).
11753   bool OtherIsBooleanDespiteType =
11754       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11755   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11756     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11757 
11758   // Check if all values in the range of possible values of this expression
11759   // lead to the same comparison outcome.
11760   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11761                                         Value.isUnsigned());
11762   auto Cmp = OtherPromotedValueRange.compare(Value);
11763   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11764   if (!Result)
11765     return false;
11766 
11767   // Also consider the range determined by the type alone. This allows us to
11768   // classify the warning under the proper diagnostic group.
11769   bool TautologicalTypeCompare = false;
11770   {
11771     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11772                                          Value.isUnsigned());
11773     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11774     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11775                                                        RhsConstant)) {
11776       TautologicalTypeCompare = true;
11777       Cmp = TypeCmp;
11778       Result = TypeResult;
11779     }
11780   }
11781 
11782   // Don't warn if the non-constant operand actually always evaluates to the
11783   // same value.
11784   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11785     return false;
11786 
11787   // Suppress the diagnostic for an in-range comparison if the constant comes
11788   // from a macro or enumerator. We don't want to diagnose
11789   //
11790   //   some_long_value <= INT_MAX
11791   //
11792   // when sizeof(int) == sizeof(long).
11793   bool InRange = Cmp & PromotedRange::InRangeFlag;
11794   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11795     return false;
11796 
11797   // A comparison of an unsigned bit-field against 0 is really a type problem,
11798   // even though at the type level the bit-field might promote to 'signed int'.
11799   if (Other->refersToBitField() && InRange && Value == 0 &&
11800       Other->getType()->isUnsignedIntegerOrEnumerationType())
11801     TautologicalTypeCompare = true;
11802 
11803   // If this is a comparison to an enum constant, include that
11804   // constant in the diagnostic.
11805   const EnumConstantDecl *ED = nullptr;
11806   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11807     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11808 
11809   // Should be enough for uint128 (39 decimal digits)
11810   SmallString<64> PrettySourceValue;
11811   llvm::raw_svector_ostream OS(PrettySourceValue);
11812   if (ED) {
11813     OS << '\'' << *ED << "' (" << Value << ")";
11814   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11815                Constant->IgnoreParenImpCasts())) {
11816     OS << (BL->getValue() ? "YES" : "NO");
11817   } else {
11818     OS << Value;
11819   }
11820 
11821   if (!TautologicalTypeCompare) {
11822     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11823         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11824         << E->getOpcodeStr() << OS.str() << *Result
11825         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11826     return true;
11827   }
11828 
11829   if (IsObjCSignedCharBool) {
11830     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11831                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11832                               << OS.str() << *Result);
11833     return true;
11834   }
11835 
11836   // FIXME: We use a somewhat different formatting for the in-range cases and
11837   // cases involving boolean values for historical reasons. We should pick a
11838   // consistent way of presenting these diagnostics.
11839   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11840 
11841     S.DiagRuntimeBehavior(
11842         E->getOperatorLoc(), E,
11843         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11844                          : diag::warn_tautological_bool_compare)
11845             << OS.str() << classifyConstantValue(Constant) << OtherT
11846             << OtherIsBooleanDespiteType << *Result
11847             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11848   } else {
11849     bool IsCharTy = OtherT.withoutLocalFastQualifiers() == S.Context.CharTy;
11850     unsigned Diag =
11851         (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11852             ? (HasEnumType(OriginalOther)
11853                    ? diag::warn_unsigned_enum_always_true_comparison
11854                    : IsCharTy ? diag::warn_unsigned_char_always_true_comparison
11855                               : diag::warn_unsigned_always_true_comparison)
11856             : diag::warn_tautological_constant_compare;
11857 
11858     S.Diag(E->getOperatorLoc(), Diag)
11859         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11860         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11861   }
11862 
11863   return true;
11864 }
11865 
11866 /// Analyze the operands of the given comparison.  Implements the
11867 /// fallback case from AnalyzeComparison.
11868 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11869   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11870   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11871 }
11872 
11873 /// Implements -Wsign-compare.
11874 ///
11875 /// \param E the binary operator to check for warnings
11876 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11877   // The type the comparison is being performed in.
11878   QualType T = E->getLHS()->getType();
11879 
11880   // Only analyze comparison operators where both sides have been converted to
11881   // the same type.
11882   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11883     return AnalyzeImpConvsInComparison(S, E);
11884 
11885   // Don't analyze value-dependent comparisons directly.
11886   if (E->isValueDependent())
11887     return AnalyzeImpConvsInComparison(S, E);
11888 
11889   Expr *LHS = E->getLHS();
11890   Expr *RHS = E->getRHS();
11891 
11892   if (T->isIntegralType(S.Context)) {
11893     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11894     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11895 
11896     // We don't care about expressions whose result is a constant.
11897     if (RHSValue && LHSValue)
11898       return AnalyzeImpConvsInComparison(S, E);
11899 
11900     // We only care about expressions where just one side is literal
11901     if ((bool)RHSValue ^ (bool)LHSValue) {
11902       // Is the constant on the RHS or LHS?
11903       const bool RhsConstant = (bool)RHSValue;
11904       Expr *Const = RhsConstant ? RHS : LHS;
11905       Expr *Other = RhsConstant ? LHS : RHS;
11906       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11907 
11908       // Check whether an integer constant comparison results in a value
11909       // of 'true' or 'false'.
11910       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11911         return AnalyzeImpConvsInComparison(S, E);
11912     }
11913   }
11914 
11915   if (!T->hasUnsignedIntegerRepresentation()) {
11916     // We don't do anything special if this isn't an unsigned integral
11917     // comparison:  we're only interested in integral comparisons, and
11918     // signed comparisons only happen in cases we don't care to warn about.
11919     return AnalyzeImpConvsInComparison(S, E);
11920   }
11921 
11922   LHS = LHS->IgnoreParenImpCasts();
11923   RHS = RHS->IgnoreParenImpCasts();
11924 
11925   if (!S.getLangOpts().CPlusPlus) {
11926     // Avoid warning about comparison of integers with different signs when
11927     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11928     // the type of `E`.
11929     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11930       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11931     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11932       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11933   }
11934 
11935   // Check to see if one of the (unmodified) operands is of different
11936   // signedness.
11937   Expr *signedOperand, *unsignedOperand;
11938   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11939     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11940            "unsigned comparison between two signed integer expressions?");
11941     signedOperand = LHS;
11942     unsignedOperand = RHS;
11943   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11944     signedOperand = RHS;
11945     unsignedOperand = LHS;
11946   } else {
11947     return AnalyzeImpConvsInComparison(S, E);
11948   }
11949 
11950   // Otherwise, calculate the effective range of the signed operand.
11951   IntRange signedRange = GetExprRange(
11952       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11953 
11954   // Go ahead and analyze implicit conversions in the operands.  Note
11955   // that we skip the implicit conversions on both sides.
11956   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11957   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11958 
11959   // If the signed range is non-negative, -Wsign-compare won't fire.
11960   if (signedRange.NonNegative)
11961     return;
11962 
11963   // For (in)equality comparisons, if the unsigned operand is a
11964   // constant which cannot collide with a overflowed signed operand,
11965   // then reinterpreting the signed operand as unsigned will not
11966   // change the result of the comparison.
11967   if (E->isEqualityOp()) {
11968     unsigned comparisonWidth = S.Context.getIntWidth(T);
11969     IntRange unsignedRange =
11970         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11971                      /*Approximate*/ true);
11972 
11973     // We should never be unable to prove that the unsigned operand is
11974     // non-negative.
11975     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11976 
11977     if (unsignedRange.Width < comparisonWidth)
11978       return;
11979   }
11980 
11981   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11982                         S.PDiag(diag::warn_mixed_sign_comparison)
11983                             << LHS->getType() << RHS->getType()
11984                             << LHS->getSourceRange() << RHS->getSourceRange());
11985 }
11986 
11987 /// Analyzes an attempt to assign the given value to a bitfield.
11988 ///
11989 /// Returns true if there was something fishy about the attempt.
11990 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11991                                       SourceLocation InitLoc) {
11992   assert(Bitfield->isBitField());
11993   if (Bitfield->isInvalidDecl())
11994     return false;
11995 
11996   // White-list bool bitfields.
11997   QualType BitfieldType = Bitfield->getType();
11998   if (BitfieldType->isBooleanType())
11999      return false;
12000 
12001   if (BitfieldType->isEnumeralType()) {
12002     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
12003     // If the underlying enum type was not explicitly specified as an unsigned
12004     // type and the enum contain only positive values, MSVC++ will cause an
12005     // inconsistency by storing this as a signed type.
12006     if (S.getLangOpts().CPlusPlus11 &&
12007         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
12008         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
12009         BitfieldEnumDecl->getNumNegativeBits() == 0) {
12010       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
12011           << BitfieldEnumDecl;
12012     }
12013   }
12014 
12015   if (Bitfield->getType()->isBooleanType())
12016     return false;
12017 
12018   // Ignore value- or type-dependent expressions.
12019   if (Bitfield->getBitWidth()->isValueDependent() ||
12020       Bitfield->getBitWidth()->isTypeDependent() ||
12021       Init->isValueDependent() ||
12022       Init->isTypeDependent())
12023     return false;
12024 
12025   Expr *OriginalInit = Init->IgnoreParenImpCasts();
12026   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
12027 
12028   Expr::EvalResult Result;
12029   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
12030                                    Expr::SE_AllowSideEffects)) {
12031     // The RHS is not constant.  If the RHS has an enum type, make sure the
12032     // bitfield is wide enough to hold all the values of the enum without
12033     // truncation.
12034     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
12035       EnumDecl *ED = EnumTy->getDecl();
12036       bool SignedBitfield = BitfieldType->isSignedIntegerType();
12037 
12038       // Enum types are implicitly signed on Windows, so check if there are any
12039       // negative enumerators to see if the enum was intended to be signed or
12040       // not.
12041       bool SignedEnum = ED->getNumNegativeBits() > 0;
12042 
12043       // Check for surprising sign changes when assigning enum values to a
12044       // bitfield of different signedness.  If the bitfield is signed and we
12045       // have exactly the right number of bits to store this unsigned enum,
12046       // suggest changing the enum to an unsigned type. This typically happens
12047       // on Windows where unfixed enums always use an underlying type of 'int'.
12048       unsigned DiagID = 0;
12049       if (SignedEnum && !SignedBitfield) {
12050         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
12051       } else if (SignedBitfield && !SignedEnum &&
12052                  ED->getNumPositiveBits() == FieldWidth) {
12053         DiagID = diag::warn_signed_bitfield_enum_conversion;
12054       }
12055 
12056       if (DiagID) {
12057         S.Diag(InitLoc, DiagID) << Bitfield << ED;
12058         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
12059         SourceRange TypeRange =
12060             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
12061         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
12062             << SignedEnum << TypeRange;
12063       }
12064 
12065       // Compute the required bitwidth. If the enum has negative values, we need
12066       // one more bit than the normal number of positive bits to represent the
12067       // sign bit.
12068       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
12069                                                   ED->getNumNegativeBits())
12070                                        : ED->getNumPositiveBits();
12071 
12072       // Check the bitwidth.
12073       if (BitsNeeded > FieldWidth) {
12074         Expr *WidthExpr = Bitfield->getBitWidth();
12075         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
12076             << Bitfield << ED;
12077         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
12078             << BitsNeeded << ED << WidthExpr->getSourceRange();
12079       }
12080     }
12081 
12082     return false;
12083   }
12084 
12085   llvm::APSInt Value = Result.Val.getInt();
12086 
12087   unsigned OriginalWidth = Value.getBitWidth();
12088 
12089   if (!Value.isSigned() || Value.isNegative())
12090     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
12091       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
12092         OriginalWidth = Value.getMinSignedBits();
12093 
12094   if (OriginalWidth <= FieldWidth)
12095     return false;
12096 
12097   // Compute the value which the bitfield will contain.
12098   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
12099   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
12100 
12101   // Check whether the stored value is equal to the original value.
12102   TruncatedValue = TruncatedValue.extend(OriginalWidth);
12103   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
12104     return false;
12105 
12106   // Special-case bitfields of width 1: booleans are naturally 0/1, and
12107   // therefore don't strictly fit into a signed bitfield of width 1.
12108   if (FieldWidth == 1 && Value == 1)
12109     return false;
12110 
12111   std::string PrettyValue = toString(Value, 10);
12112   std::string PrettyTrunc = toString(TruncatedValue, 10);
12113 
12114   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
12115     << PrettyValue << PrettyTrunc << OriginalInit->getType()
12116     << Init->getSourceRange();
12117 
12118   return true;
12119 }
12120 
12121 /// Analyze the given simple or compound assignment for warning-worthy
12122 /// operations.
12123 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
12124   // Just recurse on the LHS.
12125   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12126 
12127   // We want to recurse on the RHS as normal unless we're assigning to
12128   // a bitfield.
12129   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
12130     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
12131                                   E->getOperatorLoc())) {
12132       // Recurse, ignoring any implicit conversions on the RHS.
12133       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
12134                                         E->getOperatorLoc());
12135     }
12136   }
12137 
12138   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12139 
12140   // Diagnose implicitly sequentially-consistent atomic assignment.
12141   if (E->getLHS()->getType()->isAtomicType())
12142     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12143 }
12144 
12145 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12146 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
12147                             SourceLocation CContext, unsigned diag,
12148                             bool pruneControlFlow = false) {
12149   if (pruneControlFlow) {
12150     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12151                           S.PDiag(diag)
12152                               << SourceType << T << E->getSourceRange()
12153                               << SourceRange(CContext));
12154     return;
12155   }
12156   S.Diag(E->getExprLoc(), diag)
12157     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
12158 }
12159 
12160 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
12161 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
12162                             SourceLocation CContext,
12163                             unsigned diag, bool pruneControlFlow = false) {
12164   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
12165 }
12166 
12167 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
12168   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
12169       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
12170 }
12171 
12172 static void adornObjCBoolConversionDiagWithTernaryFixit(
12173     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
12174   Expr *Ignored = SourceExpr->IgnoreImplicit();
12175   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
12176     Ignored = OVE->getSourceExpr();
12177   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
12178                      isa<BinaryOperator>(Ignored) ||
12179                      isa<CXXOperatorCallExpr>(Ignored);
12180   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
12181   if (NeedsParens)
12182     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
12183             << FixItHint::CreateInsertion(EndLoc, ")");
12184   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
12185 }
12186 
12187 /// Diagnose an implicit cast from a floating point value to an integer value.
12188 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
12189                                     SourceLocation CContext) {
12190   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
12191   const bool PruneWarnings = S.inTemplateInstantiation();
12192 
12193   Expr *InnerE = E->IgnoreParenImpCasts();
12194   // We also want to warn on, e.g., "int i = -1.234"
12195   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
12196     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
12197       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
12198 
12199   const bool IsLiteral =
12200       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
12201 
12202   llvm::APFloat Value(0.0);
12203   bool IsConstant =
12204     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
12205   if (!IsConstant) {
12206     if (isObjCSignedCharBool(S, T)) {
12207       return adornObjCBoolConversionDiagWithTernaryFixit(
12208           S, E,
12209           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
12210               << E->getType());
12211     }
12212 
12213     return DiagnoseImpCast(S, E, T, CContext,
12214                            diag::warn_impcast_float_integer, PruneWarnings);
12215   }
12216 
12217   bool isExact = false;
12218 
12219   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
12220                             T->hasUnsignedIntegerRepresentation());
12221   llvm::APFloat::opStatus Result = Value.convertToInteger(
12222       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
12223 
12224   // FIXME: Force the precision of the source value down so we don't print
12225   // digits which are usually useless (we don't really care here if we
12226   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
12227   // would automatically print the shortest representation, but it's a bit
12228   // tricky to implement.
12229   SmallString<16> PrettySourceValue;
12230   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
12231   precision = (precision * 59 + 195) / 196;
12232   Value.toString(PrettySourceValue, precision);
12233 
12234   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
12235     return adornObjCBoolConversionDiagWithTernaryFixit(
12236         S, E,
12237         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
12238             << PrettySourceValue);
12239   }
12240 
12241   if (Result == llvm::APFloat::opOK && isExact) {
12242     if (IsLiteral) return;
12243     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
12244                            PruneWarnings);
12245   }
12246 
12247   // Conversion of a floating-point value to a non-bool integer where the
12248   // integral part cannot be represented by the integer type is undefined.
12249   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
12250     return DiagnoseImpCast(
12251         S, E, T, CContext,
12252         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
12253                   : diag::warn_impcast_float_to_integer_out_of_range,
12254         PruneWarnings);
12255 
12256   unsigned DiagID = 0;
12257   if (IsLiteral) {
12258     // Warn on floating point literal to integer.
12259     DiagID = diag::warn_impcast_literal_float_to_integer;
12260   } else if (IntegerValue == 0) {
12261     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
12262       return DiagnoseImpCast(S, E, T, CContext,
12263                              diag::warn_impcast_float_integer, PruneWarnings);
12264     }
12265     // Warn on non-zero to zero conversion.
12266     DiagID = diag::warn_impcast_float_to_integer_zero;
12267   } else {
12268     if (IntegerValue.isUnsigned()) {
12269       if (!IntegerValue.isMaxValue()) {
12270         return DiagnoseImpCast(S, E, T, CContext,
12271                                diag::warn_impcast_float_integer, PruneWarnings);
12272       }
12273     } else {  // IntegerValue.isSigned()
12274       if (!IntegerValue.isMaxSignedValue() &&
12275           !IntegerValue.isMinSignedValue()) {
12276         return DiagnoseImpCast(S, E, T, CContext,
12277                                diag::warn_impcast_float_integer, PruneWarnings);
12278       }
12279     }
12280     // Warn on evaluatable floating point expression to integer conversion.
12281     DiagID = diag::warn_impcast_float_to_integer;
12282   }
12283 
12284   SmallString<16> PrettyTargetValue;
12285   if (IsBool)
12286     PrettyTargetValue = Value.isZero() ? "false" : "true";
12287   else
12288     IntegerValue.toString(PrettyTargetValue);
12289 
12290   if (PruneWarnings) {
12291     S.DiagRuntimeBehavior(E->getExprLoc(), E,
12292                           S.PDiag(DiagID)
12293                               << E->getType() << T.getUnqualifiedType()
12294                               << PrettySourceValue << PrettyTargetValue
12295                               << E->getSourceRange() << SourceRange(CContext));
12296   } else {
12297     S.Diag(E->getExprLoc(), DiagID)
12298         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
12299         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
12300   }
12301 }
12302 
12303 /// Analyze the given compound assignment for the possible losing of
12304 /// floating-point precision.
12305 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
12306   assert(isa<CompoundAssignOperator>(E) &&
12307          "Must be compound assignment operation");
12308   // Recurse on the LHS and RHS in here
12309   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
12310   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
12311 
12312   if (E->getLHS()->getType()->isAtomicType())
12313     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
12314 
12315   // Now check the outermost expression
12316   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
12317   const auto *RBT = cast<CompoundAssignOperator>(E)
12318                         ->getComputationResultType()
12319                         ->getAs<BuiltinType>();
12320 
12321   // The below checks assume source is floating point.
12322   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
12323 
12324   // If source is floating point but target is an integer.
12325   if (ResultBT->isInteger())
12326     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
12327                            E->getExprLoc(), diag::warn_impcast_float_integer);
12328 
12329   if (!ResultBT->isFloatingPoint())
12330     return;
12331 
12332   // If both source and target are floating points, warn about losing precision.
12333   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12334       QualType(ResultBT, 0), QualType(RBT, 0));
12335   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
12336     // warn about dropping FP rank.
12337     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
12338                     diag::warn_impcast_float_result_precision);
12339 }
12340 
12341 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
12342                                       IntRange Range) {
12343   if (!Range.Width) return "0";
12344 
12345   llvm::APSInt ValueInRange = Value;
12346   ValueInRange.setIsSigned(!Range.NonNegative);
12347   ValueInRange = ValueInRange.trunc(Range.Width);
12348   return toString(ValueInRange, 10);
12349 }
12350 
12351 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
12352   if (!isa<ImplicitCastExpr>(Ex))
12353     return false;
12354 
12355   Expr *InnerE = Ex->IgnoreParenImpCasts();
12356   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
12357   const Type *Source =
12358     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
12359   if (Target->isDependentType())
12360     return false;
12361 
12362   const BuiltinType *FloatCandidateBT =
12363     dyn_cast<BuiltinType>(ToBool ? Source : Target);
12364   const Type *BoolCandidateType = ToBool ? Target : Source;
12365 
12366   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
12367           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
12368 }
12369 
12370 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
12371                                              SourceLocation CC) {
12372   unsigned NumArgs = TheCall->getNumArgs();
12373   for (unsigned i = 0; i < NumArgs; ++i) {
12374     Expr *CurrA = TheCall->getArg(i);
12375     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
12376       continue;
12377 
12378     bool IsSwapped = ((i > 0) &&
12379         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
12380     IsSwapped |= ((i < (NumArgs - 1)) &&
12381         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
12382     if (IsSwapped) {
12383       // Warn on this floating-point to bool conversion.
12384       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
12385                       CurrA->getType(), CC,
12386                       diag::warn_impcast_floating_point_to_bool);
12387     }
12388   }
12389 }
12390 
12391 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
12392                                    SourceLocation CC) {
12393   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
12394                         E->getExprLoc()))
12395     return;
12396 
12397   // Don't warn on functions which have return type nullptr_t.
12398   if (isa<CallExpr>(E))
12399     return;
12400 
12401   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
12402   const Expr::NullPointerConstantKind NullKind =
12403       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
12404   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
12405     return;
12406 
12407   // Return if target type is a safe conversion.
12408   if (T->isAnyPointerType() || T->isBlockPointerType() ||
12409       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
12410     return;
12411 
12412   SourceLocation Loc = E->getSourceRange().getBegin();
12413 
12414   // Venture through the macro stacks to get to the source of macro arguments.
12415   // The new location is a better location than the complete location that was
12416   // passed in.
12417   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
12418   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
12419 
12420   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
12421   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
12422     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
12423         Loc, S.SourceMgr, S.getLangOpts());
12424     if (MacroName == "NULL")
12425       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
12426   }
12427 
12428   // Only warn if the null and context location are in the same macro expansion.
12429   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
12430     return;
12431 
12432   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
12433       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
12434       << FixItHint::CreateReplacement(Loc,
12435                                       S.getFixItZeroLiteralForType(T, Loc));
12436 }
12437 
12438 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12439                                   ObjCArrayLiteral *ArrayLiteral);
12440 
12441 static void
12442 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12443                            ObjCDictionaryLiteral *DictionaryLiteral);
12444 
12445 /// Check a single element within a collection literal against the
12446 /// target element type.
12447 static void checkObjCCollectionLiteralElement(Sema &S,
12448                                               QualType TargetElementType,
12449                                               Expr *Element,
12450                                               unsigned ElementKind) {
12451   // Skip a bitcast to 'id' or qualified 'id'.
12452   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
12453     if (ICE->getCastKind() == CK_BitCast &&
12454         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
12455       Element = ICE->getSubExpr();
12456   }
12457 
12458   QualType ElementType = Element->getType();
12459   ExprResult ElementResult(Element);
12460   if (ElementType->getAs<ObjCObjectPointerType>() &&
12461       S.CheckSingleAssignmentConstraints(TargetElementType,
12462                                          ElementResult,
12463                                          false, false)
12464         != Sema::Compatible) {
12465     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
12466         << ElementType << ElementKind << TargetElementType
12467         << Element->getSourceRange();
12468   }
12469 
12470   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
12471     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
12472   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
12473     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
12474 }
12475 
12476 /// Check an Objective-C array literal being converted to the given
12477 /// target type.
12478 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
12479                                   ObjCArrayLiteral *ArrayLiteral) {
12480   if (!S.NSArrayDecl)
12481     return;
12482 
12483   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12484   if (!TargetObjCPtr)
12485     return;
12486 
12487   if (TargetObjCPtr->isUnspecialized() ||
12488       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12489         != S.NSArrayDecl->getCanonicalDecl())
12490     return;
12491 
12492   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12493   if (TypeArgs.size() != 1)
12494     return;
12495 
12496   QualType TargetElementType = TypeArgs[0];
12497   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
12498     checkObjCCollectionLiteralElement(S, TargetElementType,
12499                                       ArrayLiteral->getElement(I),
12500                                       0);
12501   }
12502 }
12503 
12504 /// Check an Objective-C dictionary literal being converted to the given
12505 /// target type.
12506 static void
12507 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
12508                            ObjCDictionaryLiteral *DictionaryLiteral) {
12509   if (!S.NSDictionaryDecl)
12510     return;
12511 
12512   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
12513   if (!TargetObjCPtr)
12514     return;
12515 
12516   if (TargetObjCPtr->isUnspecialized() ||
12517       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
12518         != S.NSDictionaryDecl->getCanonicalDecl())
12519     return;
12520 
12521   auto TypeArgs = TargetObjCPtr->getTypeArgs();
12522   if (TypeArgs.size() != 2)
12523     return;
12524 
12525   QualType TargetKeyType = TypeArgs[0];
12526   QualType TargetObjectType = TypeArgs[1];
12527   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
12528     auto Element = DictionaryLiteral->getKeyValueElement(I);
12529     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
12530     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
12531   }
12532 }
12533 
12534 // Helper function to filter out cases for constant width constant conversion.
12535 // Don't warn on char array initialization or for non-decimal values.
12536 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
12537                                           SourceLocation CC) {
12538   // If initializing from a constant, and the constant starts with '0',
12539   // then it is a binary, octal, or hexadecimal.  Allow these constants
12540   // to fill all the bits, even if there is a sign change.
12541   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
12542     const char FirstLiteralCharacter =
12543         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
12544     if (FirstLiteralCharacter == '0')
12545       return false;
12546   }
12547 
12548   // If the CC location points to a '{', and the type is char, then assume
12549   // assume it is an array initialization.
12550   if (CC.isValid() && T->isCharType()) {
12551     const char FirstContextCharacter =
12552         S.getSourceManager().getCharacterData(CC)[0];
12553     if (FirstContextCharacter == '{')
12554       return false;
12555   }
12556 
12557   return true;
12558 }
12559 
12560 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
12561   const auto *IL = dyn_cast<IntegerLiteral>(E);
12562   if (!IL) {
12563     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
12564       if (UO->getOpcode() == UO_Minus)
12565         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
12566     }
12567   }
12568 
12569   return IL;
12570 }
12571 
12572 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
12573   E = E->IgnoreParenImpCasts();
12574   SourceLocation ExprLoc = E->getExprLoc();
12575 
12576   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
12577     BinaryOperator::Opcode Opc = BO->getOpcode();
12578     Expr::EvalResult Result;
12579     // Do not diagnose unsigned shifts.
12580     if (Opc == BO_Shl) {
12581       const auto *LHS = getIntegerLiteral(BO->getLHS());
12582       const auto *RHS = getIntegerLiteral(BO->getRHS());
12583       if (LHS && LHS->getValue() == 0)
12584         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
12585       else if (!E->isValueDependent() && LHS && RHS &&
12586                RHS->getValue().isNonNegative() &&
12587                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
12588         S.Diag(ExprLoc, diag::warn_left_shift_always)
12589             << (Result.Val.getInt() != 0);
12590       else if (E->getType()->isSignedIntegerType())
12591         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
12592     }
12593   }
12594 
12595   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
12596     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
12597     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
12598     if (!LHS || !RHS)
12599       return;
12600     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
12601         (RHS->getValue() == 0 || RHS->getValue() == 1))
12602       // Do not diagnose common idioms.
12603       return;
12604     if (LHS->getValue() != 0 && RHS->getValue() != 0)
12605       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
12606   }
12607 }
12608 
12609 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
12610                                     SourceLocation CC,
12611                                     bool *ICContext = nullptr,
12612                                     bool IsListInit = false) {
12613   if (E->isTypeDependent() || E->isValueDependent()) return;
12614 
12615   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
12616   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
12617   if (Source == Target) return;
12618   if (Target->isDependentType()) return;
12619 
12620   // If the conversion context location is invalid don't complain. We also
12621   // don't want to emit a warning if the issue occurs from the expansion of
12622   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
12623   // delay this check as long as possible. Once we detect we are in that
12624   // scenario, we just return.
12625   if (CC.isInvalid())
12626     return;
12627 
12628   if (Source->isAtomicType())
12629     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
12630 
12631   // Diagnose implicit casts to bool.
12632   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
12633     if (isa<StringLiteral>(E))
12634       // Warn on string literal to bool.  Checks for string literals in logical
12635       // and expressions, for instance, assert(0 && "error here"), are
12636       // prevented by a check in AnalyzeImplicitConversions().
12637       return DiagnoseImpCast(S, E, T, CC,
12638                              diag::warn_impcast_string_literal_to_bool);
12639     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
12640         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
12641       // This covers the literal expressions that evaluate to Objective-C
12642       // objects.
12643       return DiagnoseImpCast(S, E, T, CC,
12644                              diag::warn_impcast_objective_c_literal_to_bool);
12645     }
12646     if (Source->isPointerType() || Source->canDecayToPointerType()) {
12647       // Warn on pointer to bool conversion that is always true.
12648       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
12649                                      SourceRange(CC));
12650     }
12651   }
12652 
12653   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12654   // is a typedef for signed char (macOS), then that constant value has to be 1
12655   // or 0.
12656   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12657     Expr::EvalResult Result;
12658     if (E->EvaluateAsInt(Result, S.getASTContext(),
12659                          Expr::SE_AllowSideEffects)) {
12660       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12661         adornObjCBoolConversionDiagWithTernaryFixit(
12662             S, E,
12663             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12664                 << toString(Result.Val.getInt(), 10));
12665       }
12666       return;
12667     }
12668   }
12669 
12670   // Check implicit casts from Objective-C collection literals to specialized
12671   // collection types, e.g., NSArray<NSString *> *.
12672   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12673     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12674   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12675     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12676 
12677   // Strip vector types.
12678   if (isa<VectorType>(Source)) {
12679     if (Target->isVLSTBuiltinType() &&
12680         (S.Context.areCompatibleSveTypes(QualType(Target, 0),
12681                                          QualType(Source, 0)) ||
12682          S.Context.areLaxCompatibleSveTypes(QualType(Target, 0),
12683                                             QualType(Source, 0))))
12684       return;
12685 
12686     if (!isa<VectorType>(Target)) {
12687       if (S.SourceMgr.isInSystemMacro(CC))
12688         return;
12689       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12690     }
12691 
12692     // If the vector cast is cast between two vectors of the same size, it is
12693     // a bitcast, not a conversion.
12694     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12695       return;
12696 
12697     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12698     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12699   }
12700   if (auto VecTy = dyn_cast<VectorType>(Target))
12701     Target = VecTy->getElementType().getTypePtr();
12702 
12703   // Strip complex types.
12704   if (isa<ComplexType>(Source)) {
12705     if (!isa<ComplexType>(Target)) {
12706       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12707         return;
12708 
12709       return DiagnoseImpCast(S, E, T, CC,
12710                              S.getLangOpts().CPlusPlus
12711                                  ? diag::err_impcast_complex_scalar
12712                                  : diag::warn_impcast_complex_scalar);
12713     }
12714 
12715     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12716     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12717   }
12718 
12719   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12720   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12721 
12722   // If the source is floating point...
12723   if (SourceBT && SourceBT->isFloatingPoint()) {
12724     // ...and the target is floating point...
12725     if (TargetBT && TargetBT->isFloatingPoint()) {
12726       // ...then warn if we're dropping FP rank.
12727 
12728       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12729           QualType(SourceBT, 0), QualType(TargetBT, 0));
12730       if (Order > 0) {
12731         // Don't warn about float constants that are precisely
12732         // representable in the target type.
12733         Expr::EvalResult result;
12734         if (E->EvaluateAsRValue(result, S.Context)) {
12735           // Value might be a float, a float vector, or a float complex.
12736           if (IsSameFloatAfterCast(result.Val,
12737                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12738                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12739             return;
12740         }
12741 
12742         if (S.SourceMgr.isInSystemMacro(CC))
12743           return;
12744 
12745         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12746       }
12747       // ... or possibly if we're increasing rank, too
12748       else if (Order < 0) {
12749         if (S.SourceMgr.isInSystemMacro(CC))
12750           return;
12751 
12752         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12753       }
12754       return;
12755     }
12756 
12757     // If the target is integral, always warn.
12758     if (TargetBT && TargetBT->isInteger()) {
12759       if (S.SourceMgr.isInSystemMacro(CC))
12760         return;
12761 
12762       DiagnoseFloatingImpCast(S, E, T, CC);
12763     }
12764 
12765     // Detect the case where a call result is converted from floating-point to
12766     // to bool, and the final argument to the call is converted from bool, to
12767     // discover this typo:
12768     //
12769     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12770     //
12771     // FIXME: This is an incredibly special case; is there some more general
12772     // way to detect this class of misplaced-parentheses bug?
12773     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12774       // Check last argument of function call to see if it is an
12775       // implicit cast from a type matching the type the result
12776       // is being cast to.
12777       CallExpr *CEx = cast<CallExpr>(E);
12778       if (unsigned NumArgs = CEx->getNumArgs()) {
12779         Expr *LastA = CEx->getArg(NumArgs - 1);
12780         Expr *InnerE = LastA->IgnoreParenImpCasts();
12781         if (isa<ImplicitCastExpr>(LastA) &&
12782             InnerE->getType()->isBooleanType()) {
12783           // Warn on this floating-point to bool conversion
12784           DiagnoseImpCast(S, E, T, CC,
12785                           diag::warn_impcast_floating_point_to_bool);
12786         }
12787       }
12788     }
12789     return;
12790   }
12791 
12792   // Valid casts involving fixed point types should be accounted for here.
12793   if (Source->isFixedPointType()) {
12794     if (Target->isUnsaturatedFixedPointType()) {
12795       Expr::EvalResult Result;
12796       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12797                                   S.isConstantEvaluated())) {
12798         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12799         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12800         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12801         if (Value > MaxVal || Value < MinVal) {
12802           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12803                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12804                                     << Value.toString() << T
12805                                     << E->getSourceRange()
12806                                     << clang::SourceRange(CC));
12807           return;
12808         }
12809       }
12810     } else if (Target->isIntegerType()) {
12811       Expr::EvalResult Result;
12812       if (!S.isConstantEvaluated() &&
12813           E->EvaluateAsFixedPoint(Result, S.Context,
12814                                   Expr::SE_AllowSideEffects)) {
12815         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12816 
12817         bool Overflowed;
12818         llvm::APSInt IntResult = FXResult.convertToInt(
12819             S.Context.getIntWidth(T),
12820             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12821 
12822         if (Overflowed) {
12823           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12824                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12825                                     << FXResult.toString() << T
12826                                     << E->getSourceRange()
12827                                     << clang::SourceRange(CC));
12828           return;
12829         }
12830       }
12831     }
12832   } else if (Target->isUnsaturatedFixedPointType()) {
12833     if (Source->isIntegerType()) {
12834       Expr::EvalResult Result;
12835       if (!S.isConstantEvaluated() &&
12836           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12837         llvm::APSInt Value = Result.Val.getInt();
12838 
12839         bool Overflowed;
12840         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12841             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12842 
12843         if (Overflowed) {
12844           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12845                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12846                                     << toString(Value, /*Radix=*/10) << T
12847                                     << E->getSourceRange()
12848                                     << clang::SourceRange(CC));
12849           return;
12850         }
12851       }
12852     }
12853   }
12854 
12855   // If we are casting an integer type to a floating point type without
12856   // initialization-list syntax, we might lose accuracy if the floating
12857   // point type has a narrower significand than the integer type.
12858   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12859       TargetBT->isFloatingType() && !IsListInit) {
12860     // Determine the number of precision bits in the source integer type.
12861     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12862                                         /*Approximate*/ true);
12863     unsigned int SourcePrecision = SourceRange.Width;
12864 
12865     // Determine the number of precision bits in the
12866     // target floating point type.
12867     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12868         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12869 
12870     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12871         SourcePrecision > TargetPrecision) {
12872 
12873       if (Optional<llvm::APSInt> SourceInt =
12874               E->getIntegerConstantExpr(S.Context)) {
12875         // If the source integer is a constant, convert it to the target
12876         // floating point type. Issue a warning if the value changes
12877         // during the whole conversion.
12878         llvm::APFloat TargetFloatValue(
12879             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12880         llvm::APFloat::opStatus ConversionStatus =
12881             TargetFloatValue.convertFromAPInt(
12882                 *SourceInt, SourceBT->isSignedInteger(),
12883                 llvm::APFloat::rmNearestTiesToEven);
12884 
12885         if (ConversionStatus != llvm::APFloat::opOK) {
12886           SmallString<32> PrettySourceValue;
12887           SourceInt->toString(PrettySourceValue, 10);
12888           SmallString<32> PrettyTargetValue;
12889           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12890 
12891           S.DiagRuntimeBehavior(
12892               E->getExprLoc(), E,
12893               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12894                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12895                   << E->getSourceRange() << clang::SourceRange(CC));
12896         }
12897       } else {
12898         // Otherwise, the implicit conversion may lose precision.
12899         DiagnoseImpCast(S, E, T, CC,
12900                         diag::warn_impcast_integer_float_precision);
12901       }
12902     }
12903   }
12904 
12905   DiagnoseNullConversion(S, E, T, CC);
12906 
12907   S.DiscardMisalignedMemberAddress(Target, E);
12908 
12909   if (Target->isBooleanType())
12910     DiagnoseIntInBoolContext(S, E);
12911 
12912   if (!Source->isIntegerType() || !Target->isIntegerType())
12913     return;
12914 
12915   // TODO: remove this early return once the false positives for constant->bool
12916   // in templates, macros, etc, are reduced or removed.
12917   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12918     return;
12919 
12920   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12921       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12922     return adornObjCBoolConversionDiagWithTernaryFixit(
12923         S, E,
12924         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12925             << E->getType());
12926   }
12927 
12928   IntRange SourceTypeRange =
12929       IntRange::forTargetOfCanonicalType(S.Context, Source);
12930   IntRange LikelySourceRange =
12931       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12932   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12933 
12934   if (LikelySourceRange.Width > TargetRange.Width) {
12935     // If the source is a constant, use a default-on diagnostic.
12936     // TODO: this should happen for bitfield stores, too.
12937     Expr::EvalResult Result;
12938     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12939                          S.isConstantEvaluated())) {
12940       llvm::APSInt Value(32);
12941       Value = Result.Val.getInt();
12942 
12943       if (S.SourceMgr.isInSystemMacro(CC))
12944         return;
12945 
12946       std::string PrettySourceValue = toString(Value, 10);
12947       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12948 
12949       S.DiagRuntimeBehavior(
12950           E->getExprLoc(), E,
12951           S.PDiag(diag::warn_impcast_integer_precision_constant)
12952               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12953               << E->getSourceRange() << SourceRange(CC));
12954       return;
12955     }
12956 
12957     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12958     if (S.SourceMgr.isInSystemMacro(CC))
12959       return;
12960 
12961     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12962       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12963                              /* pruneControlFlow */ true);
12964     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12965   }
12966 
12967   if (TargetRange.Width > SourceTypeRange.Width) {
12968     if (auto *UO = dyn_cast<UnaryOperator>(E))
12969       if (UO->getOpcode() == UO_Minus)
12970         if (Source->isUnsignedIntegerType()) {
12971           if (Target->isUnsignedIntegerType())
12972             return DiagnoseImpCast(S, E, T, CC,
12973                                    diag::warn_impcast_high_order_zero_bits);
12974           if (Target->isSignedIntegerType())
12975             return DiagnoseImpCast(S, E, T, CC,
12976                                    diag::warn_impcast_nonnegative_result);
12977         }
12978   }
12979 
12980   if (TargetRange.Width == LikelySourceRange.Width &&
12981       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12982       Source->isSignedIntegerType()) {
12983     // Warn when doing a signed to signed conversion, warn if the positive
12984     // source value is exactly the width of the target type, which will
12985     // cause a negative value to be stored.
12986 
12987     Expr::EvalResult Result;
12988     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12989         !S.SourceMgr.isInSystemMacro(CC)) {
12990       llvm::APSInt Value = Result.Val.getInt();
12991       if (isSameWidthConstantConversion(S, E, T, CC)) {
12992         std::string PrettySourceValue = toString(Value, 10);
12993         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12994 
12995         S.DiagRuntimeBehavior(
12996             E->getExprLoc(), E,
12997             S.PDiag(diag::warn_impcast_integer_precision_constant)
12998                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12999                 << E->getSourceRange() << SourceRange(CC));
13000         return;
13001       }
13002     }
13003 
13004     // Fall through for non-constants to give a sign conversion warning.
13005   }
13006 
13007   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
13008       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
13009        LikelySourceRange.Width == TargetRange.Width)) {
13010     if (S.SourceMgr.isInSystemMacro(CC))
13011       return;
13012 
13013     unsigned DiagID = diag::warn_impcast_integer_sign;
13014 
13015     // Traditionally, gcc has warned about this under -Wsign-compare.
13016     // We also want to warn about it in -Wconversion.
13017     // So if -Wconversion is off, use a completely identical diagnostic
13018     // in the sign-compare group.
13019     // The conditional-checking code will
13020     if (ICContext) {
13021       DiagID = diag::warn_impcast_integer_sign_conditional;
13022       *ICContext = true;
13023     }
13024 
13025     return DiagnoseImpCast(S, E, T, CC, DiagID);
13026   }
13027 
13028   // Diagnose conversions between different enumeration types.
13029   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
13030   // type, to give us better diagnostics.
13031   QualType SourceType = E->getType();
13032   if (!S.getLangOpts().CPlusPlus) {
13033     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13034       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
13035         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
13036         SourceType = S.Context.getTypeDeclType(Enum);
13037         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
13038       }
13039   }
13040 
13041   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
13042     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
13043       if (SourceEnum->getDecl()->hasNameForLinkage() &&
13044           TargetEnum->getDecl()->hasNameForLinkage() &&
13045           SourceEnum != TargetEnum) {
13046         if (S.SourceMgr.isInSystemMacro(CC))
13047           return;
13048 
13049         return DiagnoseImpCast(S, E, SourceType, T, CC,
13050                                diag::warn_impcast_different_enum_types);
13051       }
13052 }
13053 
13054 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13055                                      SourceLocation CC, QualType T);
13056 
13057 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
13058                                     SourceLocation CC, bool &ICContext) {
13059   E = E->IgnoreParenImpCasts();
13060 
13061   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
13062     return CheckConditionalOperator(S, CO, CC, T);
13063 
13064   AnalyzeImplicitConversions(S, E, CC);
13065   if (E->getType() != T)
13066     return CheckImplicitConversion(S, E, T, CC, &ICContext);
13067 }
13068 
13069 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
13070                                      SourceLocation CC, QualType T) {
13071   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
13072 
13073   Expr *TrueExpr = E->getTrueExpr();
13074   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
13075     TrueExpr = BCO->getCommon();
13076 
13077   bool Suspicious = false;
13078   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
13079   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
13080 
13081   if (T->isBooleanType())
13082     DiagnoseIntInBoolContext(S, E);
13083 
13084   // If -Wconversion would have warned about either of the candidates
13085   // for a signedness conversion to the context type...
13086   if (!Suspicious) return;
13087 
13088   // ...but it's currently ignored...
13089   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
13090     return;
13091 
13092   // ...then check whether it would have warned about either of the
13093   // candidates for a signedness conversion to the condition type.
13094   if (E->getType() == T) return;
13095 
13096   Suspicious = false;
13097   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
13098                           E->getType(), CC, &Suspicious);
13099   if (!Suspicious)
13100     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
13101                             E->getType(), CC, &Suspicious);
13102 }
13103 
13104 /// Check conversion of given expression to boolean.
13105 /// Input argument E is a logical expression.
13106 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
13107   if (S.getLangOpts().Bool)
13108     return;
13109   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
13110     return;
13111   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
13112 }
13113 
13114 namespace {
13115 struct AnalyzeImplicitConversionsWorkItem {
13116   Expr *E;
13117   SourceLocation CC;
13118   bool IsListInit;
13119 };
13120 }
13121 
13122 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
13123 /// that should be visited are added to WorkList.
13124 static void AnalyzeImplicitConversions(
13125     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
13126     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
13127   Expr *OrigE = Item.E;
13128   SourceLocation CC = Item.CC;
13129 
13130   QualType T = OrigE->getType();
13131   Expr *E = OrigE->IgnoreParenImpCasts();
13132 
13133   // Propagate whether we are in a C++ list initialization expression.
13134   // If so, we do not issue warnings for implicit int-float conversion
13135   // precision loss, because C++11 narrowing already handles it.
13136   bool IsListInit = Item.IsListInit ||
13137                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
13138 
13139   if (E->isTypeDependent() || E->isValueDependent())
13140     return;
13141 
13142   Expr *SourceExpr = E;
13143   // Examine, but don't traverse into the source expression of an
13144   // OpaqueValueExpr, since it may have multiple parents and we don't want to
13145   // emit duplicate diagnostics. Its fine to examine the form or attempt to
13146   // evaluate it in the context of checking the specific conversion to T though.
13147   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
13148     if (auto *Src = OVE->getSourceExpr())
13149       SourceExpr = Src;
13150 
13151   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
13152     if (UO->getOpcode() == UO_Not &&
13153         UO->getSubExpr()->isKnownToHaveBooleanValue())
13154       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
13155           << OrigE->getSourceRange() << T->isBooleanType()
13156           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
13157 
13158   if (const auto *BO = dyn_cast<BinaryOperator>(SourceExpr))
13159     if ((BO->getOpcode() == BO_And || BO->getOpcode() == BO_Or) &&
13160         BO->getLHS()->isKnownToHaveBooleanValue() &&
13161         BO->getRHS()->isKnownToHaveBooleanValue() &&
13162         BO->getLHS()->HasSideEffects(S.Context) &&
13163         BO->getRHS()->HasSideEffects(S.Context)) {
13164       S.Diag(BO->getBeginLoc(), diag::warn_bitwise_instead_of_logical)
13165           << (BO->getOpcode() == BO_And ? "&" : "|") << OrigE->getSourceRange()
13166           << FixItHint::CreateReplacement(
13167                  BO->getOperatorLoc(),
13168                  (BO->getOpcode() == BO_And ? "&&" : "||"));
13169       S.Diag(BO->getBeginLoc(), diag::note_cast_operand_to_int);
13170     }
13171 
13172   // For conditional operators, we analyze the arguments as if they
13173   // were being fed directly into the output.
13174   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
13175     CheckConditionalOperator(S, CO, CC, T);
13176     return;
13177   }
13178 
13179   // Check implicit argument conversions for function calls.
13180   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
13181     CheckImplicitArgumentConversions(S, Call, CC);
13182 
13183   // Go ahead and check any implicit conversions we might have skipped.
13184   // The non-canonical typecheck is just an optimization;
13185   // CheckImplicitConversion will filter out dead implicit conversions.
13186   if (SourceExpr->getType() != T)
13187     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
13188 
13189   // Now continue drilling into this expression.
13190 
13191   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
13192     // The bound subexpressions in a PseudoObjectExpr are not reachable
13193     // as transitive children.
13194     // FIXME: Use a more uniform representation for this.
13195     for (auto *SE : POE->semantics())
13196       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
13197         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
13198   }
13199 
13200   // Skip past explicit casts.
13201   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
13202     E = CE->getSubExpr()->IgnoreParenImpCasts();
13203     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
13204       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
13205     WorkList.push_back({E, CC, IsListInit});
13206     return;
13207   }
13208 
13209   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13210     // Do a somewhat different check with comparison operators.
13211     if (BO->isComparisonOp())
13212       return AnalyzeComparison(S, BO);
13213 
13214     // And with simple assignments.
13215     if (BO->getOpcode() == BO_Assign)
13216       return AnalyzeAssignment(S, BO);
13217     // And with compound assignments.
13218     if (BO->isAssignmentOp())
13219       return AnalyzeCompoundAssignment(S, BO);
13220   }
13221 
13222   // These break the otherwise-useful invariant below.  Fortunately,
13223   // we don't really need to recurse into them, because any internal
13224   // expressions should have been analyzed already when they were
13225   // built into statements.
13226   if (isa<StmtExpr>(E)) return;
13227 
13228   // Don't descend into unevaluated contexts.
13229   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
13230 
13231   // Now just recurse over the expression's children.
13232   CC = E->getExprLoc();
13233   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
13234   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
13235   for (Stmt *SubStmt : E->children()) {
13236     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
13237     if (!ChildExpr)
13238       continue;
13239 
13240     if (IsLogicalAndOperator &&
13241         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
13242       // Ignore checking string literals that are in logical and operators.
13243       // This is a common pattern for asserts.
13244       continue;
13245     WorkList.push_back({ChildExpr, CC, IsListInit});
13246   }
13247 
13248   if (BO && BO->isLogicalOp()) {
13249     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
13250     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13251       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13252 
13253     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
13254     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
13255       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
13256   }
13257 
13258   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
13259     if (U->getOpcode() == UO_LNot) {
13260       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
13261     } else if (U->getOpcode() != UO_AddrOf) {
13262       if (U->getSubExpr()->getType()->isAtomicType())
13263         S.Diag(U->getSubExpr()->getBeginLoc(),
13264                diag::warn_atomic_implicit_seq_cst);
13265     }
13266   }
13267 }
13268 
13269 /// AnalyzeImplicitConversions - Find and report any interesting
13270 /// implicit conversions in the given expression.  There are a couple
13271 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
13272 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
13273                                        bool IsListInit/*= false*/) {
13274   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
13275   WorkList.push_back({OrigE, CC, IsListInit});
13276   while (!WorkList.empty())
13277     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
13278 }
13279 
13280 /// Diagnose integer type and any valid implicit conversion to it.
13281 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
13282   // Taking into account implicit conversions,
13283   // allow any integer.
13284   if (!E->getType()->isIntegerType()) {
13285     S.Diag(E->getBeginLoc(),
13286            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
13287     return true;
13288   }
13289   // Potentially emit standard warnings for implicit conversions if enabled
13290   // using -Wconversion.
13291   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
13292   return false;
13293 }
13294 
13295 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
13296 // Returns true when emitting a warning about taking the address of a reference.
13297 static bool CheckForReference(Sema &SemaRef, const Expr *E,
13298                               const PartialDiagnostic &PD) {
13299   E = E->IgnoreParenImpCasts();
13300 
13301   const FunctionDecl *FD = nullptr;
13302 
13303   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
13304     if (!DRE->getDecl()->getType()->isReferenceType())
13305       return false;
13306   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13307     if (!M->getMemberDecl()->getType()->isReferenceType())
13308       return false;
13309   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
13310     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
13311       return false;
13312     FD = Call->getDirectCallee();
13313   } else {
13314     return false;
13315   }
13316 
13317   SemaRef.Diag(E->getExprLoc(), PD);
13318 
13319   // If possible, point to location of function.
13320   if (FD) {
13321     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
13322   }
13323 
13324   return true;
13325 }
13326 
13327 // Returns true if the SourceLocation is expanded from any macro body.
13328 // Returns false if the SourceLocation is invalid, is from not in a macro
13329 // expansion, or is from expanded from a top-level macro argument.
13330 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
13331   if (Loc.isInvalid())
13332     return false;
13333 
13334   while (Loc.isMacroID()) {
13335     if (SM.isMacroBodyExpansion(Loc))
13336       return true;
13337     Loc = SM.getImmediateMacroCallerLoc(Loc);
13338   }
13339 
13340   return false;
13341 }
13342 
13343 /// Diagnose pointers that are always non-null.
13344 /// \param E the expression containing the pointer
13345 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
13346 /// compared to a null pointer
13347 /// \param IsEqual True when the comparison is equal to a null pointer
13348 /// \param Range Extra SourceRange to highlight in the diagnostic
13349 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
13350                                         Expr::NullPointerConstantKind NullKind,
13351                                         bool IsEqual, SourceRange Range) {
13352   if (!E)
13353     return;
13354 
13355   // Don't warn inside macros.
13356   if (E->getExprLoc().isMacroID()) {
13357     const SourceManager &SM = getSourceManager();
13358     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
13359         IsInAnyMacroBody(SM, Range.getBegin()))
13360       return;
13361   }
13362   E = E->IgnoreImpCasts();
13363 
13364   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
13365 
13366   if (isa<CXXThisExpr>(E)) {
13367     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
13368                                 : diag::warn_this_bool_conversion;
13369     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
13370     return;
13371   }
13372 
13373   bool IsAddressOf = false;
13374 
13375   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13376     if (UO->getOpcode() != UO_AddrOf)
13377       return;
13378     IsAddressOf = true;
13379     E = UO->getSubExpr();
13380   }
13381 
13382   if (IsAddressOf) {
13383     unsigned DiagID = IsCompare
13384                           ? diag::warn_address_of_reference_null_compare
13385                           : diag::warn_address_of_reference_bool_conversion;
13386     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
13387                                          << IsEqual;
13388     if (CheckForReference(*this, E, PD)) {
13389       return;
13390     }
13391   }
13392 
13393   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
13394     bool IsParam = isa<NonNullAttr>(NonnullAttr);
13395     std::string Str;
13396     llvm::raw_string_ostream S(Str);
13397     E->printPretty(S, nullptr, getPrintingPolicy());
13398     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
13399                                 : diag::warn_cast_nonnull_to_bool;
13400     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
13401       << E->getSourceRange() << Range << IsEqual;
13402     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
13403   };
13404 
13405   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
13406   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
13407     if (auto *Callee = Call->getDirectCallee()) {
13408       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
13409         ComplainAboutNonnullParamOrCall(A);
13410         return;
13411       }
13412     }
13413   }
13414 
13415   // Expect to find a single Decl.  Skip anything more complicated.
13416   ValueDecl *D = nullptr;
13417   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
13418     D = R->getDecl();
13419   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
13420     D = M->getMemberDecl();
13421   }
13422 
13423   // Weak Decls can be null.
13424   if (!D || D->isWeak())
13425     return;
13426 
13427   // Check for parameter decl with nonnull attribute
13428   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
13429     if (getCurFunction() &&
13430         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
13431       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
13432         ComplainAboutNonnullParamOrCall(A);
13433         return;
13434       }
13435 
13436       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
13437         // Skip function template not specialized yet.
13438         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
13439           return;
13440         auto ParamIter = llvm::find(FD->parameters(), PV);
13441         assert(ParamIter != FD->param_end());
13442         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
13443 
13444         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
13445           if (!NonNull->args_size()) {
13446               ComplainAboutNonnullParamOrCall(NonNull);
13447               return;
13448           }
13449 
13450           for (const ParamIdx &ArgNo : NonNull->args()) {
13451             if (ArgNo.getASTIndex() == ParamNo) {
13452               ComplainAboutNonnullParamOrCall(NonNull);
13453               return;
13454             }
13455           }
13456         }
13457       }
13458     }
13459   }
13460 
13461   QualType T = D->getType();
13462   const bool IsArray = T->isArrayType();
13463   const bool IsFunction = T->isFunctionType();
13464 
13465   // Address of function is used to silence the function warning.
13466   if (IsAddressOf && IsFunction) {
13467     return;
13468   }
13469 
13470   // Found nothing.
13471   if (!IsAddressOf && !IsFunction && !IsArray)
13472     return;
13473 
13474   // Pretty print the expression for the diagnostic.
13475   std::string Str;
13476   llvm::raw_string_ostream S(Str);
13477   E->printPretty(S, nullptr, getPrintingPolicy());
13478 
13479   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
13480                               : diag::warn_impcast_pointer_to_bool;
13481   enum {
13482     AddressOf,
13483     FunctionPointer,
13484     ArrayPointer
13485   } DiagType;
13486   if (IsAddressOf)
13487     DiagType = AddressOf;
13488   else if (IsFunction)
13489     DiagType = FunctionPointer;
13490   else if (IsArray)
13491     DiagType = ArrayPointer;
13492   else
13493     llvm_unreachable("Could not determine diagnostic.");
13494   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
13495                                 << Range << IsEqual;
13496 
13497   if (!IsFunction)
13498     return;
13499 
13500   // Suggest '&' to silence the function warning.
13501   Diag(E->getExprLoc(), diag::note_function_warning_silence)
13502       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
13503 
13504   // Check to see if '()' fixit should be emitted.
13505   QualType ReturnType;
13506   UnresolvedSet<4> NonTemplateOverloads;
13507   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
13508   if (ReturnType.isNull())
13509     return;
13510 
13511   if (IsCompare) {
13512     // There are two cases here.  If there is null constant, the only suggest
13513     // for a pointer return type.  If the null is 0, then suggest if the return
13514     // type is a pointer or an integer type.
13515     if (!ReturnType->isPointerType()) {
13516       if (NullKind == Expr::NPCK_ZeroExpression ||
13517           NullKind == Expr::NPCK_ZeroLiteral) {
13518         if (!ReturnType->isIntegerType())
13519           return;
13520       } else {
13521         return;
13522       }
13523     }
13524   } else { // !IsCompare
13525     // For function to bool, only suggest if the function pointer has bool
13526     // return type.
13527     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
13528       return;
13529   }
13530   Diag(E->getExprLoc(), diag::note_function_to_function_call)
13531       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
13532 }
13533 
13534 /// Diagnoses "dangerous" implicit conversions within the given
13535 /// expression (which is a full expression).  Implements -Wconversion
13536 /// and -Wsign-compare.
13537 ///
13538 /// \param CC the "context" location of the implicit conversion, i.e.
13539 ///   the most location of the syntactic entity requiring the implicit
13540 ///   conversion
13541 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
13542   // Don't diagnose in unevaluated contexts.
13543   if (isUnevaluatedContext())
13544     return;
13545 
13546   // Don't diagnose for value- or type-dependent expressions.
13547   if (E->isTypeDependent() || E->isValueDependent())
13548     return;
13549 
13550   // Check for array bounds violations in cases where the check isn't triggered
13551   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
13552   // ArraySubscriptExpr is on the RHS of a variable initialization.
13553   CheckArrayAccess(E);
13554 
13555   // This is not the right CC for (e.g.) a variable initialization.
13556   AnalyzeImplicitConversions(*this, E, CC);
13557 }
13558 
13559 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
13560 /// Input argument E is a logical expression.
13561 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
13562   ::CheckBoolLikeConversion(*this, E, CC);
13563 }
13564 
13565 /// Diagnose when expression is an integer constant expression and its evaluation
13566 /// results in integer overflow
13567 void Sema::CheckForIntOverflow (Expr *E) {
13568   // Use a work list to deal with nested struct initializers.
13569   SmallVector<Expr *, 2> Exprs(1, E);
13570 
13571   do {
13572     Expr *OriginalE = Exprs.pop_back_val();
13573     Expr *E = OriginalE->IgnoreParenCasts();
13574 
13575     if (isa<BinaryOperator>(E)) {
13576       E->EvaluateForOverflow(Context);
13577       continue;
13578     }
13579 
13580     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
13581       Exprs.append(InitList->inits().begin(), InitList->inits().end());
13582     else if (isa<ObjCBoxedExpr>(OriginalE))
13583       E->EvaluateForOverflow(Context);
13584     else if (auto Call = dyn_cast<CallExpr>(E))
13585       Exprs.append(Call->arg_begin(), Call->arg_end());
13586     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
13587       Exprs.append(Message->arg_begin(), Message->arg_end());
13588   } while (!Exprs.empty());
13589 }
13590 
13591 namespace {
13592 
13593 /// Visitor for expressions which looks for unsequenced operations on the
13594 /// same object.
13595 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
13596   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
13597 
13598   /// A tree of sequenced regions within an expression. Two regions are
13599   /// unsequenced if one is an ancestor or a descendent of the other. When we
13600   /// finish processing an expression with sequencing, such as a comma
13601   /// expression, we fold its tree nodes into its parent, since they are
13602   /// unsequenced with respect to nodes we will visit later.
13603   class SequenceTree {
13604     struct Value {
13605       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
13606       unsigned Parent : 31;
13607       unsigned Merged : 1;
13608     };
13609     SmallVector<Value, 8> Values;
13610 
13611   public:
13612     /// A region within an expression which may be sequenced with respect
13613     /// to some other region.
13614     class Seq {
13615       friend class SequenceTree;
13616 
13617       unsigned Index;
13618 
13619       explicit Seq(unsigned N) : Index(N) {}
13620 
13621     public:
13622       Seq() : Index(0) {}
13623     };
13624 
13625     SequenceTree() { Values.push_back(Value(0)); }
13626     Seq root() const { return Seq(0); }
13627 
13628     /// Create a new sequence of operations, which is an unsequenced
13629     /// subset of \p Parent. This sequence of operations is sequenced with
13630     /// respect to other children of \p Parent.
13631     Seq allocate(Seq Parent) {
13632       Values.push_back(Value(Parent.Index));
13633       return Seq(Values.size() - 1);
13634     }
13635 
13636     /// Merge a sequence of operations into its parent.
13637     void merge(Seq S) {
13638       Values[S.Index].Merged = true;
13639     }
13640 
13641     /// Determine whether two operations are unsequenced. This operation
13642     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
13643     /// should have been merged into its parent as appropriate.
13644     bool isUnsequenced(Seq Cur, Seq Old) {
13645       unsigned C = representative(Cur.Index);
13646       unsigned Target = representative(Old.Index);
13647       while (C >= Target) {
13648         if (C == Target)
13649           return true;
13650         C = Values[C].Parent;
13651       }
13652       return false;
13653     }
13654 
13655   private:
13656     /// Pick a representative for a sequence.
13657     unsigned representative(unsigned K) {
13658       if (Values[K].Merged)
13659         // Perform path compression as we go.
13660         return Values[K].Parent = representative(Values[K].Parent);
13661       return K;
13662     }
13663   };
13664 
13665   /// An object for which we can track unsequenced uses.
13666   using Object = const NamedDecl *;
13667 
13668   /// Different flavors of object usage which we track. We only track the
13669   /// least-sequenced usage of each kind.
13670   enum UsageKind {
13671     /// A read of an object. Multiple unsequenced reads are OK.
13672     UK_Use,
13673 
13674     /// A modification of an object which is sequenced before the value
13675     /// computation of the expression, such as ++n in C++.
13676     UK_ModAsValue,
13677 
13678     /// A modification of an object which is not sequenced before the value
13679     /// computation of the expression, such as n++.
13680     UK_ModAsSideEffect,
13681 
13682     UK_Count = UK_ModAsSideEffect + 1
13683   };
13684 
13685   /// Bundle together a sequencing region and the expression corresponding
13686   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13687   struct Usage {
13688     const Expr *UsageExpr;
13689     SequenceTree::Seq Seq;
13690 
13691     Usage() : UsageExpr(nullptr), Seq() {}
13692   };
13693 
13694   struct UsageInfo {
13695     Usage Uses[UK_Count];
13696 
13697     /// Have we issued a diagnostic for this object already?
13698     bool Diagnosed;
13699 
13700     UsageInfo() : Uses(), Diagnosed(false) {}
13701   };
13702   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13703 
13704   Sema &SemaRef;
13705 
13706   /// Sequenced regions within the expression.
13707   SequenceTree Tree;
13708 
13709   /// Declaration modifications and references which we have seen.
13710   UsageInfoMap UsageMap;
13711 
13712   /// The region we are currently within.
13713   SequenceTree::Seq Region;
13714 
13715   /// Filled in with declarations which were modified as a side-effect
13716   /// (that is, post-increment operations).
13717   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13718 
13719   /// Expressions to check later. We defer checking these to reduce
13720   /// stack usage.
13721   SmallVectorImpl<const Expr *> &WorkList;
13722 
13723   /// RAII object wrapping the visitation of a sequenced subexpression of an
13724   /// expression. At the end of this process, the side-effects of the evaluation
13725   /// become sequenced with respect to the value computation of the result, so
13726   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13727   /// UK_ModAsValue.
13728   struct SequencedSubexpression {
13729     SequencedSubexpression(SequenceChecker &Self)
13730       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13731       Self.ModAsSideEffect = &ModAsSideEffect;
13732     }
13733 
13734     ~SequencedSubexpression() {
13735       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13736         // Add a new usage with usage kind UK_ModAsValue, and then restore
13737         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13738         // the previous one was empty).
13739         UsageInfo &UI = Self.UsageMap[M.first];
13740         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13741         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13742         SideEffectUsage = M.second;
13743       }
13744       Self.ModAsSideEffect = OldModAsSideEffect;
13745     }
13746 
13747     SequenceChecker &Self;
13748     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13749     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13750   };
13751 
13752   /// RAII object wrapping the visitation of a subexpression which we might
13753   /// choose to evaluate as a constant. If any subexpression is evaluated and
13754   /// found to be non-constant, this allows us to suppress the evaluation of
13755   /// the outer expression.
13756   class EvaluationTracker {
13757   public:
13758     EvaluationTracker(SequenceChecker &Self)
13759         : Self(Self), Prev(Self.EvalTracker) {
13760       Self.EvalTracker = this;
13761     }
13762 
13763     ~EvaluationTracker() {
13764       Self.EvalTracker = Prev;
13765       if (Prev)
13766         Prev->EvalOK &= EvalOK;
13767     }
13768 
13769     bool evaluate(const Expr *E, bool &Result) {
13770       if (!EvalOK || E->isValueDependent())
13771         return false;
13772       EvalOK = E->EvaluateAsBooleanCondition(
13773           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13774       return EvalOK;
13775     }
13776 
13777   private:
13778     SequenceChecker &Self;
13779     EvaluationTracker *Prev;
13780     bool EvalOK = true;
13781   } *EvalTracker = nullptr;
13782 
13783   /// Find the object which is produced by the specified expression,
13784   /// if any.
13785   Object getObject(const Expr *E, bool Mod) const {
13786     E = E->IgnoreParenCasts();
13787     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13788       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13789         return getObject(UO->getSubExpr(), Mod);
13790     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13791       if (BO->getOpcode() == BO_Comma)
13792         return getObject(BO->getRHS(), Mod);
13793       if (Mod && BO->isAssignmentOp())
13794         return getObject(BO->getLHS(), Mod);
13795     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13796       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13797       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13798         return ME->getMemberDecl();
13799     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13800       // FIXME: If this is a reference, map through to its value.
13801       return DRE->getDecl();
13802     return nullptr;
13803   }
13804 
13805   /// Note that an object \p O was modified or used by an expression
13806   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13807   /// the object \p O as obtained via the \p UsageMap.
13808   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13809     // Get the old usage for the given object and usage kind.
13810     Usage &U = UI.Uses[UK];
13811     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13812       // If we have a modification as side effect and are in a sequenced
13813       // subexpression, save the old Usage so that we can restore it later
13814       // in SequencedSubexpression::~SequencedSubexpression.
13815       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13816         ModAsSideEffect->push_back(std::make_pair(O, U));
13817       // Then record the new usage with the current sequencing region.
13818       U.UsageExpr = UsageExpr;
13819       U.Seq = Region;
13820     }
13821   }
13822 
13823   /// Check whether a modification or use of an object \p O in an expression
13824   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13825   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13826   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13827   /// usage and false we are checking for a mod-use unsequenced usage.
13828   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13829                   UsageKind OtherKind, bool IsModMod) {
13830     if (UI.Diagnosed)
13831       return;
13832 
13833     const Usage &U = UI.Uses[OtherKind];
13834     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13835       return;
13836 
13837     const Expr *Mod = U.UsageExpr;
13838     const Expr *ModOrUse = UsageExpr;
13839     if (OtherKind == UK_Use)
13840       std::swap(Mod, ModOrUse);
13841 
13842     SemaRef.DiagRuntimeBehavior(
13843         Mod->getExprLoc(), {Mod, ModOrUse},
13844         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13845                                : diag::warn_unsequenced_mod_use)
13846             << O << SourceRange(ModOrUse->getExprLoc()));
13847     UI.Diagnosed = true;
13848   }
13849 
13850   // A note on note{Pre, Post}{Use, Mod}:
13851   //
13852   // (It helps to follow the algorithm with an expression such as
13853   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13854   //  operations before C++17 and both are well-defined in C++17).
13855   //
13856   // When visiting a node which uses/modify an object we first call notePreUse
13857   // or notePreMod before visiting its sub-expression(s). At this point the
13858   // children of the current node have not yet been visited and so the eventual
13859   // uses/modifications resulting from the children of the current node have not
13860   // been recorded yet.
13861   //
13862   // We then visit the children of the current node. After that notePostUse or
13863   // notePostMod is called. These will 1) detect an unsequenced modification
13864   // as side effect (as in "k++ + k") and 2) add a new usage with the
13865   // appropriate usage kind.
13866   //
13867   // We also have to be careful that some operation sequences modification as
13868   // side effect as well (for example: || or ,). To account for this we wrap
13869   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13870   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13871   // which record usages which are modifications as side effect, and then
13872   // downgrade them (or more accurately restore the previous usage which was a
13873   // modification as side effect) when exiting the scope of the sequenced
13874   // subexpression.
13875 
13876   void notePreUse(Object O, const Expr *UseExpr) {
13877     UsageInfo &UI = UsageMap[O];
13878     // Uses conflict with other modifications.
13879     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13880   }
13881 
13882   void notePostUse(Object O, const Expr *UseExpr) {
13883     UsageInfo &UI = UsageMap[O];
13884     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13885                /*IsModMod=*/false);
13886     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13887   }
13888 
13889   void notePreMod(Object O, const Expr *ModExpr) {
13890     UsageInfo &UI = UsageMap[O];
13891     // Modifications conflict with other modifications and with uses.
13892     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13893     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13894   }
13895 
13896   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13897     UsageInfo &UI = UsageMap[O];
13898     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13899                /*IsModMod=*/true);
13900     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13901   }
13902 
13903 public:
13904   SequenceChecker(Sema &S, const Expr *E,
13905                   SmallVectorImpl<const Expr *> &WorkList)
13906       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13907     Visit(E);
13908     // Silence a -Wunused-private-field since WorkList is now unused.
13909     // TODO: Evaluate if it can be used, and if not remove it.
13910     (void)this->WorkList;
13911   }
13912 
13913   void VisitStmt(const Stmt *S) {
13914     // Skip all statements which aren't expressions for now.
13915   }
13916 
13917   void VisitExpr(const Expr *E) {
13918     // By default, just recurse to evaluated subexpressions.
13919     Base::VisitStmt(E);
13920   }
13921 
13922   void VisitCastExpr(const CastExpr *E) {
13923     Object O = Object();
13924     if (E->getCastKind() == CK_LValueToRValue)
13925       O = getObject(E->getSubExpr(), false);
13926 
13927     if (O)
13928       notePreUse(O, E);
13929     VisitExpr(E);
13930     if (O)
13931       notePostUse(O, E);
13932   }
13933 
13934   void VisitSequencedExpressions(const Expr *SequencedBefore,
13935                                  const Expr *SequencedAfter) {
13936     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13937     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13938     SequenceTree::Seq OldRegion = Region;
13939 
13940     {
13941       SequencedSubexpression SeqBefore(*this);
13942       Region = BeforeRegion;
13943       Visit(SequencedBefore);
13944     }
13945 
13946     Region = AfterRegion;
13947     Visit(SequencedAfter);
13948 
13949     Region = OldRegion;
13950 
13951     Tree.merge(BeforeRegion);
13952     Tree.merge(AfterRegion);
13953   }
13954 
13955   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13956     // C++17 [expr.sub]p1:
13957     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13958     //   expression E1 is sequenced before the expression E2.
13959     if (SemaRef.getLangOpts().CPlusPlus17)
13960       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13961     else {
13962       Visit(ASE->getLHS());
13963       Visit(ASE->getRHS());
13964     }
13965   }
13966 
13967   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13968   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13969   void VisitBinPtrMem(const BinaryOperator *BO) {
13970     // C++17 [expr.mptr.oper]p4:
13971     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13972     //  the expression E1 is sequenced before the expression E2.
13973     if (SemaRef.getLangOpts().CPlusPlus17)
13974       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13975     else {
13976       Visit(BO->getLHS());
13977       Visit(BO->getRHS());
13978     }
13979   }
13980 
13981   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13982   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13983   void VisitBinShlShr(const BinaryOperator *BO) {
13984     // C++17 [expr.shift]p4:
13985     //  The expression E1 is sequenced before the expression E2.
13986     if (SemaRef.getLangOpts().CPlusPlus17)
13987       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13988     else {
13989       Visit(BO->getLHS());
13990       Visit(BO->getRHS());
13991     }
13992   }
13993 
13994   void VisitBinComma(const BinaryOperator *BO) {
13995     // C++11 [expr.comma]p1:
13996     //   Every value computation and side effect associated with the left
13997     //   expression is sequenced before every value computation and side
13998     //   effect associated with the right expression.
13999     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
14000   }
14001 
14002   void VisitBinAssign(const BinaryOperator *BO) {
14003     SequenceTree::Seq RHSRegion;
14004     SequenceTree::Seq LHSRegion;
14005     if (SemaRef.getLangOpts().CPlusPlus17) {
14006       RHSRegion = Tree.allocate(Region);
14007       LHSRegion = Tree.allocate(Region);
14008     } else {
14009       RHSRegion = Region;
14010       LHSRegion = Region;
14011     }
14012     SequenceTree::Seq OldRegion = Region;
14013 
14014     // C++11 [expr.ass]p1:
14015     //  [...] the assignment is sequenced after the value computation
14016     //  of the right and left operands, [...]
14017     //
14018     // so check it before inspecting the operands and update the
14019     // map afterwards.
14020     Object O = getObject(BO->getLHS(), /*Mod=*/true);
14021     if (O)
14022       notePreMod(O, BO);
14023 
14024     if (SemaRef.getLangOpts().CPlusPlus17) {
14025       // C++17 [expr.ass]p1:
14026       //  [...] The right operand is sequenced before the left operand. [...]
14027       {
14028         SequencedSubexpression SeqBefore(*this);
14029         Region = RHSRegion;
14030         Visit(BO->getRHS());
14031       }
14032 
14033       Region = LHSRegion;
14034       Visit(BO->getLHS());
14035 
14036       if (O && isa<CompoundAssignOperator>(BO))
14037         notePostUse(O, BO);
14038 
14039     } else {
14040       // C++11 does not specify any sequencing between the LHS and RHS.
14041       Region = LHSRegion;
14042       Visit(BO->getLHS());
14043 
14044       if (O && isa<CompoundAssignOperator>(BO))
14045         notePostUse(O, BO);
14046 
14047       Region = RHSRegion;
14048       Visit(BO->getRHS());
14049     }
14050 
14051     // C++11 [expr.ass]p1:
14052     //  the assignment is sequenced [...] before the value computation of the
14053     //  assignment expression.
14054     // C11 6.5.16/3 has no such rule.
14055     Region = OldRegion;
14056     if (O)
14057       notePostMod(O, BO,
14058                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14059                                                   : UK_ModAsSideEffect);
14060     if (SemaRef.getLangOpts().CPlusPlus17) {
14061       Tree.merge(RHSRegion);
14062       Tree.merge(LHSRegion);
14063     }
14064   }
14065 
14066   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
14067     VisitBinAssign(CAO);
14068   }
14069 
14070   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14071   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
14072   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
14073     Object O = getObject(UO->getSubExpr(), true);
14074     if (!O)
14075       return VisitExpr(UO);
14076 
14077     notePreMod(O, UO);
14078     Visit(UO->getSubExpr());
14079     // C++11 [expr.pre.incr]p1:
14080     //   the expression ++x is equivalent to x+=1
14081     notePostMod(O, UO,
14082                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
14083                                                 : UK_ModAsSideEffect);
14084   }
14085 
14086   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14087   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
14088   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
14089     Object O = getObject(UO->getSubExpr(), true);
14090     if (!O)
14091       return VisitExpr(UO);
14092 
14093     notePreMod(O, UO);
14094     Visit(UO->getSubExpr());
14095     notePostMod(O, UO, UK_ModAsSideEffect);
14096   }
14097 
14098   void VisitBinLOr(const BinaryOperator *BO) {
14099     // C++11 [expr.log.or]p2:
14100     //  If the second expression is evaluated, every value computation and
14101     //  side effect associated with the first expression is sequenced before
14102     //  every value computation and side effect associated with the
14103     //  second expression.
14104     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14105     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14106     SequenceTree::Seq OldRegion = Region;
14107 
14108     EvaluationTracker Eval(*this);
14109     {
14110       SequencedSubexpression Sequenced(*this);
14111       Region = LHSRegion;
14112       Visit(BO->getLHS());
14113     }
14114 
14115     // C++11 [expr.log.or]p1:
14116     //  [...] the second operand is not evaluated if the first operand
14117     //  evaluates to true.
14118     bool EvalResult = false;
14119     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14120     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
14121     if (ShouldVisitRHS) {
14122       Region = RHSRegion;
14123       Visit(BO->getRHS());
14124     }
14125 
14126     Region = OldRegion;
14127     Tree.merge(LHSRegion);
14128     Tree.merge(RHSRegion);
14129   }
14130 
14131   void VisitBinLAnd(const BinaryOperator *BO) {
14132     // C++11 [expr.log.and]p2:
14133     //  If the second expression is evaluated, every value computation and
14134     //  side effect associated with the first expression is sequenced before
14135     //  every value computation and side effect associated with the
14136     //  second expression.
14137     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
14138     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
14139     SequenceTree::Seq OldRegion = Region;
14140 
14141     EvaluationTracker Eval(*this);
14142     {
14143       SequencedSubexpression Sequenced(*this);
14144       Region = LHSRegion;
14145       Visit(BO->getLHS());
14146     }
14147 
14148     // C++11 [expr.log.and]p1:
14149     //  [...] the second operand is not evaluated if the first operand is false.
14150     bool EvalResult = false;
14151     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
14152     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
14153     if (ShouldVisitRHS) {
14154       Region = RHSRegion;
14155       Visit(BO->getRHS());
14156     }
14157 
14158     Region = OldRegion;
14159     Tree.merge(LHSRegion);
14160     Tree.merge(RHSRegion);
14161   }
14162 
14163   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
14164     // C++11 [expr.cond]p1:
14165     //  [...] Every value computation and side effect associated with the first
14166     //  expression is sequenced before every value computation and side effect
14167     //  associated with the second or third expression.
14168     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
14169 
14170     // No sequencing is specified between the true and false expression.
14171     // However since exactly one of both is going to be evaluated we can
14172     // consider them to be sequenced. This is needed to avoid warning on
14173     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
14174     // both the true and false expressions because we can't evaluate x.
14175     // This will still allow us to detect an expression like (pre C++17)
14176     // "(x ? y += 1 : y += 2) = y".
14177     //
14178     // We don't wrap the visitation of the true and false expression with
14179     // SequencedSubexpression because we don't want to downgrade modifications
14180     // as side effect in the true and false expressions after the visition
14181     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
14182     // not warn between the two "y++", but we should warn between the "y++"
14183     // and the "y".
14184     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
14185     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
14186     SequenceTree::Seq OldRegion = Region;
14187 
14188     EvaluationTracker Eval(*this);
14189     {
14190       SequencedSubexpression Sequenced(*this);
14191       Region = ConditionRegion;
14192       Visit(CO->getCond());
14193     }
14194 
14195     // C++11 [expr.cond]p1:
14196     // [...] The first expression is contextually converted to bool (Clause 4).
14197     // It is evaluated and if it is true, the result of the conditional
14198     // expression is the value of the second expression, otherwise that of the
14199     // third expression. Only one of the second and third expressions is
14200     // evaluated. [...]
14201     bool EvalResult = false;
14202     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
14203     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
14204     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
14205     if (ShouldVisitTrueExpr) {
14206       Region = TrueRegion;
14207       Visit(CO->getTrueExpr());
14208     }
14209     if (ShouldVisitFalseExpr) {
14210       Region = FalseRegion;
14211       Visit(CO->getFalseExpr());
14212     }
14213 
14214     Region = OldRegion;
14215     Tree.merge(ConditionRegion);
14216     Tree.merge(TrueRegion);
14217     Tree.merge(FalseRegion);
14218   }
14219 
14220   void VisitCallExpr(const CallExpr *CE) {
14221     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
14222 
14223     if (CE->isUnevaluatedBuiltinCall(Context))
14224       return;
14225 
14226     // C++11 [intro.execution]p15:
14227     //   When calling a function [...], every value computation and side effect
14228     //   associated with any argument expression, or with the postfix expression
14229     //   designating the called function, is sequenced before execution of every
14230     //   expression or statement in the body of the function [and thus before
14231     //   the value computation of its result].
14232     SequencedSubexpression Sequenced(*this);
14233     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
14234       // C++17 [expr.call]p5
14235       //   The postfix-expression is sequenced before each expression in the
14236       //   expression-list and any default argument. [...]
14237       SequenceTree::Seq CalleeRegion;
14238       SequenceTree::Seq OtherRegion;
14239       if (SemaRef.getLangOpts().CPlusPlus17) {
14240         CalleeRegion = Tree.allocate(Region);
14241         OtherRegion = Tree.allocate(Region);
14242       } else {
14243         CalleeRegion = Region;
14244         OtherRegion = Region;
14245       }
14246       SequenceTree::Seq OldRegion = Region;
14247 
14248       // Visit the callee expression first.
14249       Region = CalleeRegion;
14250       if (SemaRef.getLangOpts().CPlusPlus17) {
14251         SequencedSubexpression Sequenced(*this);
14252         Visit(CE->getCallee());
14253       } else {
14254         Visit(CE->getCallee());
14255       }
14256 
14257       // Then visit the argument expressions.
14258       Region = OtherRegion;
14259       for (const Expr *Argument : CE->arguments())
14260         Visit(Argument);
14261 
14262       Region = OldRegion;
14263       if (SemaRef.getLangOpts().CPlusPlus17) {
14264         Tree.merge(CalleeRegion);
14265         Tree.merge(OtherRegion);
14266       }
14267     });
14268   }
14269 
14270   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
14271     // C++17 [over.match.oper]p2:
14272     //   [...] the operator notation is first transformed to the equivalent
14273     //   function-call notation as summarized in Table 12 (where @ denotes one
14274     //   of the operators covered in the specified subclause). However, the
14275     //   operands are sequenced in the order prescribed for the built-in
14276     //   operator (Clause 8).
14277     //
14278     // From the above only overloaded binary operators and overloaded call
14279     // operators have sequencing rules in C++17 that we need to handle
14280     // separately.
14281     if (!SemaRef.getLangOpts().CPlusPlus17 ||
14282         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
14283       return VisitCallExpr(CXXOCE);
14284 
14285     enum {
14286       NoSequencing,
14287       LHSBeforeRHS,
14288       RHSBeforeLHS,
14289       LHSBeforeRest
14290     } SequencingKind;
14291     switch (CXXOCE->getOperator()) {
14292     case OO_Equal:
14293     case OO_PlusEqual:
14294     case OO_MinusEqual:
14295     case OO_StarEqual:
14296     case OO_SlashEqual:
14297     case OO_PercentEqual:
14298     case OO_CaretEqual:
14299     case OO_AmpEqual:
14300     case OO_PipeEqual:
14301     case OO_LessLessEqual:
14302     case OO_GreaterGreaterEqual:
14303       SequencingKind = RHSBeforeLHS;
14304       break;
14305 
14306     case OO_LessLess:
14307     case OO_GreaterGreater:
14308     case OO_AmpAmp:
14309     case OO_PipePipe:
14310     case OO_Comma:
14311     case OO_ArrowStar:
14312     case OO_Subscript:
14313       SequencingKind = LHSBeforeRHS;
14314       break;
14315 
14316     case OO_Call:
14317       SequencingKind = LHSBeforeRest;
14318       break;
14319 
14320     default:
14321       SequencingKind = NoSequencing;
14322       break;
14323     }
14324 
14325     if (SequencingKind == NoSequencing)
14326       return VisitCallExpr(CXXOCE);
14327 
14328     // This is a call, so all subexpressions are sequenced before the result.
14329     SequencedSubexpression Sequenced(*this);
14330 
14331     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
14332       assert(SemaRef.getLangOpts().CPlusPlus17 &&
14333              "Should only get there with C++17 and above!");
14334       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
14335              "Should only get there with an overloaded binary operator"
14336              " or an overloaded call operator!");
14337 
14338       if (SequencingKind == LHSBeforeRest) {
14339         assert(CXXOCE->getOperator() == OO_Call &&
14340                "We should only have an overloaded call operator here!");
14341 
14342         // This is very similar to VisitCallExpr, except that we only have the
14343         // C++17 case. The postfix-expression is the first argument of the
14344         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
14345         // are in the following arguments.
14346         //
14347         // Note that we intentionally do not visit the callee expression since
14348         // it is just a decayed reference to a function.
14349         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
14350         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
14351         SequenceTree::Seq OldRegion = Region;
14352 
14353         assert(CXXOCE->getNumArgs() >= 1 &&
14354                "An overloaded call operator must have at least one argument"
14355                " for the postfix-expression!");
14356         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
14357         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
14358                                           CXXOCE->getNumArgs() - 1);
14359 
14360         // Visit the postfix-expression first.
14361         {
14362           Region = PostfixExprRegion;
14363           SequencedSubexpression Sequenced(*this);
14364           Visit(PostfixExpr);
14365         }
14366 
14367         // Then visit the argument expressions.
14368         Region = ArgsRegion;
14369         for (const Expr *Arg : Args)
14370           Visit(Arg);
14371 
14372         Region = OldRegion;
14373         Tree.merge(PostfixExprRegion);
14374         Tree.merge(ArgsRegion);
14375       } else {
14376         assert(CXXOCE->getNumArgs() == 2 &&
14377                "Should only have two arguments here!");
14378         assert((SequencingKind == LHSBeforeRHS ||
14379                 SequencingKind == RHSBeforeLHS) &&
14380                "Unexpected sequencing kind!");
14381 
14382         // We do not visit the callee expression since it is just a decayed
14383         // reference to a function.
14384         const Expr *E1 = CXXOCE->getArg(0);
14385         const Expr *E2 = CXXOCE->getArg(1);
14386         if (SequencingKind == RHSBeforeLHS)
14387           std::swap(E1, E2);
14388 
14389         return VisitSequencedExpressions(E1, E2);
14390       }
14391     });
14392   }
14393 
14394   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
14395     // This is a call, so all subexpressions are sequenced before the result.
14396     SequencedSubexpression Sequenced(*this);
14397 
14398     if (!CCE->isListInitialization())
14399       return VisitExpr(CCE);
14400 
14401     // In C++11, list initializations are sequenced.
14402     SmallVector<SequenceTree::Seq, 32> Elts;
14403     SequenceTree::Seq Parent = Region;
14404     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
14405                                               E = CCE->arg_end();
14406          I != E; ++I) {
14407       Region = Tree.allocate(Parent);
14408       Elts.push_back(Region);
14409       Visit(*I);
14410     }
14411 
14412     // Forget that the initializers are sequenced.
14413     Region = Parent;
14414     for (unsigned I = 0; I < Elts.size(); ++I)
14415       Tree.merge(Elts[I]);
14416   }
14417 
14418   void VisitInitListExpr(const InitListExpr *ILE) {
14419     if (!SemaRef.getLangOpts().CPlusPlus11)
14420       return VisitExpr(ILE);
14421 
14422     // In C++11, list initializations are sequenced.
14423     SmallVector<SequenceTree::Seq, 32> Elts;
14424     SequenceTree::Seq Parent = Region;
14425     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
14426       const Expr *E = ILE->getInit(I);
14427       if (!E)
14428         continue;
14429       Region = Tree.allocate(Parent);
14430       Elts.push_back(Region);
14431       Visit(E);
14432     }
14433 
14434     // Forget that the initializers are sequenced.
14435     Region = Parent;
14436     for (unsigned I = 0; I < Elts.size(); ++I)
14437       Tree.merge(Elts[I]);
14438   }
14439 };
14440 
14441 } // namespace
14442 
14443 void Sema::CheckUnsequencedOperations(const Expr *E) {
14444   SmallVector<const Expr *, 8> WorkList;
14445   WorkList.push_back(E);
14446   while (!WorkList.empty()) {
14447     const Expr *Item = WorkList.pop_back_val();
14448     SequenceChecker(*this, Item, WorkList);
14449   }
14450 }
14451 
14452 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
14453                               bool IsConstexpr) {
14454   llvm::SaveAndRestore<bool> ConstantContext(
14455       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
14456   CheckImplicitConversions(E, CheckLoc);
14457   if (!E->isInstantiationDependent())
14458     CheckUnsequencedOperations(E);
14459   if (!IsConstexpr && !E->isValueDependent())
14460     CheckForIntOverflow(E);
14461   DiagnoseMisalignedMembers();
14462 }
14463 
14464 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
14465                                        FieldDecl *BitField,
14466                                        Expr *Init) {
14467   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
14468 }
14469 
14470 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
14471                                          SourceLocation Loc) {
14472   if (!PType->isVariablyModifiedType())
14473     return;
14474   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
14475     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
14476     return;
14477   }
14478   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
14479     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
14480     return;
14481   }
14482   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
14483     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
14484     return;
14485   }
14486 
14487   const ArrayType *AT = S.Context.getAsArrayType(PType);
14488   if (!AT)
14489     return;
14490 
14491   if (AT->getSizeModifier() != ArrayType::Star) {
14492     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
14493     return;
14494   }
14495 
14496   S.Diag(Loc, diag::err_array_star_in_function_definition);
14497 }
14498 
14499 /// CheckParmsForFunctionDef - Check that the parameters of the given
14500 /// function are appropriate for the definition of a function. This
14501 /// takes care of any checks that cannot be performed on the
14502 /// declaration itself, e.g., that the types of each of the function
14503 /// parameters are complete.
14504 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
14505                                     bool CheckParameterNames) {
14506   bool HasInvalidParm = false;
14507   for (ParmVarDecl *Param : Parameters) {
14508     // C99 6.7.5.3p4: the parameters in a parameter type list in a
14509     // function declarator that is part of a function definition of
14510     // that function shall not have incomplete type.
14511     //
14512     // This is also C++ [dcl.fct]p6.
14513     if (!Param->isInvalidDecl() &&
14514         RequireCompleteType(Param->getLocation(), Param->getType(),
14515                             diag::err_typecheck_decl_incomplete_type)) {
14516       Param->setInvalidDecl();
14517       HasInvalidParm = true;
14518     }
14519 
14520     // C99 6.9.1p5: If the declarator includes a parameter type list, the
14521     // declaration of each parameter shall include an identifier.
14522     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
14523         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
14524       // Diagnose this as an extension in C17 and earlier.
14525       if (!getLangOpts().C2x)
14526         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
14527     }
14528 
14529     // C99 6.7.5.3p12:
14530     //   If the function declarator is not part of a definition of that
14531     //   function, parameters may have incomplete type and may use the [*]
14532     //   notation in their sequences of declarator specifiers to specify
14533     //   variable length array types.
14534     QualType PType = Param->getOriginalType();
14535     // FIXME: This diagnostic should point the '[*]' if source-location
14536     // information is added for it.
14537     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
14538 
14539     // If the parameter is a c++ class type and it has to be destructed in the
14540     // callee function, declare the destructor so that it can be called by the
14541     // callee function. Do not perform any direct access check on the dtor here.
14542     if (!Param->isInvalidDecl()) {
14543       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
14544         if (!ClassDecl->isInvalidDecl() &&
14545             !ClassDecl->hasIrrelevantDestructor() &&
14546             !ClassDecl->isDependentContext() &&
14547             ClassDecl->isParamDestroyedInCallee()) {
14548           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
14549           MarkFunctionReferenced(Param->getLocation(), Destructor);
14550           DiagnoseUseOfDecl(Destructor, Param->getLocation());
14551         }
14552       }
14553     }
14554 
14555     // Parameters with the pass_object_size attribute only need to be marked
14556     // constant at function definitions. Because we lack information about
14557     // whether we're on a declaration or definition when we're instantiating the
14558     // attribute, we need to check for constness here.
14559     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
14560       if (!Param->getType().isConstQualified())
14561         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
14562             << Attr->getSpelling() << 1;
14563 
14564     // Check for parameter names shadowing fields from the class.
14565     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
14566       // The owning context for the parameter should be the function, but we
14567       // want to see if this function's declaration context is a record.
14568       DeclContext *DC = Param->getDeclContext();
14569       if (DC && DC->isFunctionOrMethod()) {
14570         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
14571           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
14572                                      RD, /*DeclIsField*/ false);
14573       }
14574     }
14575   }
14576 
14577   return HasInvalidParm;
14578 }
14579 
14580 Optional<std::pair<CharUnits, CharUnits>>
14581 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
14582 
14583 /// Compute the alignment and offset of the base class object given the
14584 /// derived-to-base cast expression and the alignment and offset of the derived
14585 /// class object.
14586 static std::pair<CharUnits, CharUnits>
14587 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
14588                                    CharUnits BaseAlignment, CharUnits Offset,
14589                                    ASTContext &Ctx) {
14590   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
14591        ++PathI) {
14592     const CXXBaseSpecifier *Base = *PathI;
14593     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
14594     if (Base->isVirtual()) {
14595       // The complete object may have a lower alignment than the non-virtual
14596       // alignment of the base, in which case the base may be misaligned. Choose
14597       // the smaller of the non-virtual alignment and BaseAlignment, which is a
14598       // conservative lower bound of the complete object alignment.
14599       CharUnits NonVirtualAlignment =
14600           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
14601       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
14602       Offset = CharUnits::Zero();
14603     } else {
14604       const ASTRecordLayout &RL =
14605           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
14606       Offset += RL.getBaseClassOffset(BaseDecl);
14607     }
14608     DerivedType = Base->getType();
14609   }
14610 
14611   return std::make_pair(BaseAlignment, Offset);
14612 }
14613 
14614 /// Compute the alignment and offset of a binary additive operator.
14615 static Optional<std::pair<CharUnits, CharUnits>>
14616 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
14617                                      bool IsSub, ASTContext &Ctx) {
14618   QualType PointeeType = PtrE->getType()->getPointeeType();
14619 
14620   if (!PointeeType->isConstantSizeType())
14621     return llvm::None;
14622 
14623   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
14624 
14625   if (!P)
14626     return llvm::None;
14627 
14628   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
14629   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
14630     CharUnits Offset = EltSize * IdxRes->getExtValue();
14631     if (IsSub)
14632       Offset = -Offset;
14633     return std::make_pair(P->first, P->second + Offset);
14634   }
14635 
14636   // If the integer expression isn't a constant expression, compute the lower
14637   // bound of the alignment using the alignment and offset of the pointer
14638   // expression and the element size.
14639   return std::make_pair(
14640       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
14641       CharUnits::Zero());
14642 }
14643 
14644 /// This helper function takes an lvalue expression and returns the alignment of
14645 /// a VarDecl and a constant offset from the VarDecl.
14646 Optional<std::pair<CharUnits, CharUnits>>
14647 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
14648   E = E->IgnoreParens();
14649   switch (E->getStmtClass()) {
14650   default:
14651     break;
14652   case Stmt::CStyleCastExprClass:
14653   case Stmt::CXXStaticCastExprClass:
14654   case Stmt::ImplicitCastExprClass: {
14655     auto *CE = cast<CastExpr>(E);
14656     const Expr *From = CE->getSubExpr();
14657     switch (CE->getCastKind()) {
14658     default:
14659       break;
14660     case CK_NoOp:
14661       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14662     case CK_UncheckedDerivedToBase:
14663     case CK_DerivedToBase: {
14664       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14665       if (!P)
14666         break;
14667       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
14668                                                 P->second, Ctx);
14669     }
14670     }
14671     break;
14672   }
14673   case Stmt::ArraySubscriptExprClass: {
14674     auto *ASE = cast<ArraySubscriptExpr>(E);
14675     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14676                                                 false, Ctx);
14677   }
14678   case Stmt::DeclRefExprClass: {
14679     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14680       // FIXME: If VD is captured by copy or is an escaping __block variable,
14681       // use the alignment of VD's type.
14682       if (!VD->getType()->isReferenceType())
14683         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14684       if (VD->hasInit())
14685         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14686     }
14687     break;
14688   }
14689   case Stmt::MemberExprClass: {
14690     auto *ME = cast<MemberExpr>(E);
14691     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14692     if (!FD || FD->getType()->isReferenceType() ||
14693         FD->getParent()->isInvalidDecl())
14694       break;
14695     Optional<std::pair<CharUnits, CharUnits>> P;
14696     if (ME->isArrow())
14697       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14698     else
14699       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14700     if (!P)
14701       break;
14702     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14703     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14704     return std::make_pair(P->first,
14705                           P->second + CharUnits::fromQuantity(Offset));
14706   }
14707   case Stmt::UnaryOperatorClass: {
14708     auto *UO = cast<UnaryOperator>(E);
14709     switch (UO->getOpcode()) {
14710     default:
14711       break;
14712     case UO_Deref:
14713       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14714     }
14715     break;
14716   }
14717   case Stmt::BinaryOperatorClass: {
14718     auto *BO = cast<BinaryOperator>(E);
14719     auto Opcode = BO->getOpcode();
14720     switch (Opcode) {
14721     default:
14722       break;
14723     case BO_Comma:
14724       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14725     }
14726     break;
14727   }
14728   }
14729   return llvm::None;
14730 }
14731 
14732 /// This helper function takes a pointer expression and returns the alignment of
14733 /// a VarDecl and a constant offset from the VarDecl.
14734 Optional<std::pair<CharUnits, CharUnits>>
14735 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14736   E = E->IgnoreParens();
14737   switch (E->getStmtClass()) {
14738   default:
14739     break;
14740   case Stmt::CStyleCastExprClass:
14741   case Stmt::CXXStaticCastExprClass:
14742   case Stmt::ImplicitCastExprClass: {
14743     auto *CE = cast<CastExpr>(E);
14744     const Expr *From = CE->getSubExpr();
14745     switch (CE->getCastKind()) {
14746     default:
14747       break;
14748     case CK_NoOp:
14749       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14750     case CK_ArrayToPointerDecay:
14751       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14752     case CK_UncheckedDerivedToBase:
14753     case CK_DerivedToBase: {
14754       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14755       if (!P)
14756         break;
14757       return getDerivedToBaseAlignmentAndOffset(
14758           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14759     }
14760     }
14761     break;
14762   }
14763   case Stmt::CXXThisExprClass: {
14764     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14765     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14766     return std::make_pair(Alignment, CharUnits::Zero());
14767   }
14768   case Stmt::UnaryOperatorClass: {
14769     auto *UO = cast<UnaryOperator>(E);
14770     if (UO->getOpcode() == UO_AddrOf)
14771       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14772     break;
14773   }
14774   case Stmt::BinaryOperatorClass: {
14775     auto *BO = cast<BinaryOperator>(E);
14776     auto Opcode = BO->getOpcode();
14777     switch (Opcode) {
14778     default:
14779       break;
14780     case BO_Add:
14781     case BO_Sub: {
14782       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14783       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14784         std::swap(LHS, RHS);
14785       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14786                                                   Ctx);
14787     }
14788     case BO_Comma:
14789       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14790     }
14791     break;
14792   }
14793   }
14794   return llvm::None;
14795 }
14796 
14797 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14798   // See if we can compute the alignment of a VarDecl and an offset from it.
14799   Optional<std::pair<CharUnits, CharUnits>> P =
14800       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14801 
14802   if (P)
14803     return P->first.alignmentAtOffset(P->second);
14804 
14805   // If that failed, return the type's alignment.
14806   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14807 }
14808 
14809 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14810 /// pointer cast increases the alignment requirements.
14811 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14812   // This is actually a lot of work to potentially be doing on every
14813   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14814   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14815     return;
14816 
14817   // Ignore dependent types.
14818   if (T->isDependentType() || Op->getType()->isDependentType())
14819     return;
14820 
14821   // Require that the destination be a pointer type.
14822   const PointerType *DestPtr = T->getAs<PointerType>();
14823   if (!DestPtr) return;
14824 
14825   // If the destination has alignment 1, we're done.
14826   QualType DestPointee = DestPtr->getPointeeType();
14827   if (DestPointee->isIncompleteType()) return;
14828   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14829   if (DestAlign.isOne()) return;
14830 
14831   // Require that the source be a pointer type.
14832   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14833   if (!SrcPtr) return;
14834   QualType SrcPointee = SrcPtr->getPointeeType();
14835 
14836   // Explicitly allow casts from cv void*.  We already implicitly
14837   // allowed casts to cv void*, since they have alignment 1.
14838   // Also allow casts involving incomplete types, which implicitly
14839   // includes 'void'.
14840   if (SrcPointee->isIncompleteType()) return;
14841 
14842   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14843 
14844   if (SrcAlign >= DestAlign) return;
14845 
14846   Diag(TRange.getBegin(), diag::warn_cast_align)
14847     << Op->getType() << T
14848     << static_cast<unsigned>(SrcAlign.getQuantity())
14849     << static_cast<unsigned>(DestAlign.getQuantity())
14850     << TRange << Op->getSourceRange();
14851 }
14852 
14853 /// Check whether this array fits the idiom of a size-one tail padded
14854 /// array member of a struct.
14855 ///
14856 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14857 /// commonly used to emulate flexible arrays in C89 code.
14858 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14859                                     const NamedDecl *ND) {
14860   if (Size != 1 || !ND) return false;
14861 
14862   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14863   if (!FD) return false;
14864 
14865   // Don't consider sizes resulting from macro expansions or template argument
14866   // substitution to form C89 tail-padded arrays.
14867 
14868   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14869   while (TInfo) {
14870     TypeLoc TL = TInfo->getTypeLoc();
14871     // Look through typedefs.
14872     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14873       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14874       TInfo = TDL->getTypeSourceInfo();
14875       continue;
14876     }
14877     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14878       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14879       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14880         return false;
14881     }
14882     break;
14883   }
14884 
14885   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14886   if (!RD) return false;
14887   if (RD->isUnion()) return false;
14888   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14889     if (!CRD->isStandardLayout()) return false;
14890   }
14891 
14892   // See if this is the last field decl in the record.
14893   const Decl *D = FD;
14894   while ((D = D->getNextDeclInContext()))
14895     if (isa<FieldDecl>(D))
14896       return false;
14897   return true;
14898 }
14899 
14900 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14901                             const ArraySubscriptExpr *ASE,
14902                             bool AllowOnePastEnd, bool IndexNegated) {
14903   // Already diagnosed by the constant evaluator.
14904   if (isConstantEvaluated())
14905     return;
14906 
14907   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14908   if (IndexExpr->isValueDependent())
14909     return;
14910 
14911   const Type *EffectiveType =
14912       BaseExpr->getType()->getPointeeOrArrayElementType();
14913   BaseExpr = BaseExpr->IgnoreParenCasts();
14914   const ConstantArrayType *ArrayTy =
14915       Context.getAsConstantArrayType(BaseExpr->getType());
14916 
14917   const Type *BaseType =
14918       ArrayTy == nullptr ? nullptr : ArrayTy->getElementType().getTypePtr();
14919   bool IsUnboundedArray = (BaseType == nullptr);
14920   if (EffectiveType->isDependentType() ||
14921       (!IsUnboundedArray && BaseType->isDependentType()))
14922     return;
14923 
14924   Expr::EvalResult Result;
14925   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14926     return;
14927 
14928   llvm::APSInt index = Result.Val.getInt();
14929   if (IndexNegated) {
14930     index.setIsUnsigned(false);
14931     index = -index;
14932   }
14933 
14934   const NamedDecl *ND = nullptr;
14935   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14936     ND = DRE->getDecl();
14937   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14938     ND = ME->getMemberDecl();
14939 
14940   if (IsUnboundedArray) {
14941     if (index.isUnsigned() || !index.isNegative()) {
14942       const auto &ASTC = getASTContext();
14943       unsigned AddrBits =
14944           ASTC.getTargetInfo().getPointerWidth(ASTC.getTargetAddressSpace(
14945               EffectiveType->getCanonicalTypeInternal()));
14946       if (index.getBitWidth() < AddrBits)
14947         index = index.zext(AddrBits);
14948       Optional<CharUnits> ElemCharUnits =
14949           ASTC.getTypeSizeInCharsIfKnown(EffectiveType);
14950       // PR50741 - If EffectiveType has unknown size (e.g., if it's a void
14951       // pointer) bounds-checking isn't meaningful.
14952       if (!ElemCharUnits)
14953         return;
14954       llvm::APInt ElemBytes(index.getBitWidth(), ElemCharUnits->getQuantity());
14955       // If index has more active bits than address space, we already know
14956       // we have a bounds violation to warn about.  Otherwise, compute
14957       // address of (index + 1)th element, and warn about bounds violation
14958       // only if that address exceeds address space.
14959       if (index.getActiveBits() <= AddrBits) {
14960         bool Overflow;
14961         llvm::APInt Product(index);
14962         Product += 1;
14963         Product = Product.umul_ov(ElemBytes, Overflow);
14964         if (!Overflow && Product.getActiveBits() <= AddrBits)
14965           return;
14966       }
14967 
14968       // Need to compute max possible elements in address space, since that
14969       // is included in diag message.
14970       llvm::APInt MaxElems = llvm::APInt::getMaxValue(AddrBits);
14971       MaxElems = MaxElems.zext(std::max(AddrBits + 1, ElemBytes.getBitWidth()));
14972       MaxElems += 1;
14973       ElemBytes = ElemBytes.zextOrTrunc(MaxElems.getBitWidth());
14974       MaxElems = MaxElems.udiv(ElemBytes);
14975 
14976       unsigned DiagID =
14977           ASE ? diag::warn_array_index_exceeds_max_addressable_bounds
14978               : diag::warn_ptr_arith_exceeds_max_addressable_bounds;
14979 
14980       // Diag message shows element size in bits and in "bytes" (platform-
14981       // dependent CharUnits)
14982       DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14983                           PDiag(DiagID)
14984                               << toString(index, 10, true) << AddrBits
14985                               << (unsigned)ASTC.toBits(*ElemCharUnits)
14986                               << toString(ElemBytes, 10, false)
14987                               << toString(MaxElems, 10, false)
14988                               << (unsigned)MaxElems.getLimitedValue(~0U)
14989                               << IndexExpr->getSourceRange());
14990 
14991       if (!ND) {
14992         // Try harder to find a NamedDecl to point at in the note.
14993         while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
14994           BaseExpr = ASE->getBase()->IgnoreParenCasts();
14995         if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14996           ND = DRE->getDecl();
14997         if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
14998           ND = ME->getMemberDecl();
14999       }
15000 
15001       if (ND)
15002         DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15003                             PDiag(diag::note_array_declared_here) << ND);
15004     }
15005     return;
15006   }
15007 
15008   if (index.isUnsigned() || !index.isNegative()) {
15009     // It is possible that the type of the base expression after
15010     // IgnoreParenCasts is incomplete, even though the type of the base
15011     // expression before IgnoreParenCasts is complete (see PR39746 for an
15012     // example). In this case we have no information about whether the array
15013     // access exceeds the array bounds. However we can still diagnose an array
15014     // access which precedes the array bounds.
15015     if (BaseType->isIncompleteType())
15016       return;
15017 
15018     llvm::APInt size = ArrayTy->getSize();
15019     if (!size.isStrictlyPositive())
15020       return;
15021 
15022     if (BaseType != EffectiveType) {
15023       // Make sure we're comparing apples to apples when comparing index to size
15024       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
15025       uint64_t array_typesize = Context.getTypeSize(BaseType);
15026       // Handle ptrarith_typesize being zero, such as when casting to void*
15027       if (!ptrarith_typesize) ptrarith_typesize = 1;
15028       if (ptrarith_typesize != array_typesize) {
15029         // There's a cast to a different size type involved
15030         uint64_t ratio = array_typesize / ptrarith_typesize;
15031         // TODO: Be smarter about handling cases where array_typesize is not a
15032         // multiple of ptrarith_typesize
15033         if (ptrarith_typesize * ratio == array_typesize)
15034           size *= llvm::APInt(size.getBitWidth(), ratio);
15035       }
15036     }
15037 
15038     if (size.getBitWidth() > index.getBitWidth())
15039       index = index.zext(size.getBitWidth());
15040     else if (size.getBitWidth() < index.getBitWidth())
15041       size = size.zext(index.getBitWidth());
15042 
15043     // For array subscripting the index must be less than size, but for pointer
15044     // arithmetic also allow the index (offset) to be equal to size since
15045     // computing the next address after the end of the array is legal and
15046     // commonly done e.g. in C++ iterators and range-based for loops.
15047     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
15048       return;
15049 
15050     // Also don't warn for arrays of size 1 which are members of some
15051     // structure. These are often used to approximate flexible arrays in C89
15052     // code.
15053     if (IsTailPaddedMemberArray(*this, size, ND))
15054       return;
15055 
15056     // Suppress the warning if the subscript expression (as identified by the
15057     // ']' location) and the index expression are both from macro expansions
15058     // within a system header.
15059     if (ASE) {
15060       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
15061           ASE->getRBracketLoc());
15062       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
15063         SourceLocation IndexLoc =
15064             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
15065         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
15066           return;
15067       }
15068     }
15069 
15070     unsigned DiagID = ASE ? diag::warn_array_index_exceeds_bounds
15071                           : diag::warn_ptr_arith_exceeds_bounds;
15072 
15073     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15074                         PDiag(DiagID) << toString(index, 10, true)
15075                                       << toString(size, 10, true)
15076                                       << (unsigned)size.getLimitedValue(~0U)
15077                                       << IndexExpr->getSourceRange());
15078   } else {
15079     unsigned DiagID = diag::warn_array_index_precedes_bounds;
15080     if (!ASE) {
15081       DiagID = diag::warn_ptr_arith_precedes_bounds;
15082       if (index.isNegative()) index = -index;
15083     }
15084 
15085     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
15086                         PDiag(DiagID) << toString(index, 10, true)
15087                                       << IndexExpr->getSourceRange());
15088   }
15089 
15090   if (!ND) {
15091     // Try harder to find a NamedDecl to point at in the note.
15092     while (const auto *ASE = dyn_cast<ArraySubscriptExpr>(BaseExpr))
15093       BaseExpr = ASE->getBase()->IgnoreParenCasts();
15094     if (const auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
15095       ND = DRE->getDecl();
15096     if (const auto *ME = dyn_cast<MemberExpr>(BaseExpr))
15097       ND = ME->getMemberDecl();
15098   }
15099 
15100   if (ND)
15101     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
15102                         PDiag(diag::note_array_declared_here) << ND);
15103 }
15104 
15105 void Sema::CheckArrayAccess(const Expr *expr) {
15106   int AllowOnePastEnd = 0;
15107   while (expr) {
15108     expr = expr->IgnoreParenImpCasts();
15109     switch (expr->getStmtClass()) {
15110       case Stmt::ArraySubscriptExprClass: {
15111         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
15112         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
15113                          AllowOnePastEnd > 0);
15114         expr = ASE->getBase();
15115         break;
15116       }
15117       case Stmt::MemberExprClass: {
15118         expr = cast<MemberExpr>(expr)->getBase();
15119         break;
15120       }
15121       case Stmt::OMPArraySectionExprClass: {
15122         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
15123         if (ASE->getLowerBound())
15124           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
15125                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
15126         return;
15127       }
15128       case Stmt::UnaryOperatorClass: {
15129         // Only unwrap the * and & unary operators
15130         const UnaryOperator *UO = cast<UnaryOperator>(expr);
15131         expr = UO->getSubExpr();
15132         switch (UO->getOpcode()) {
15133           case UO_AddrOf:
15134             AllowOnePastEnd++;
15135             break;
15136           case UO_Deref:
15137             AllowOnePastEnd--;
15138             break;
15139           default:
15140             return;
15141         }
15142         break;
15143       }
15144       case Stmt::ConditionalOperatorClass: {
15145         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
15146         if (const Expr *lhs = cond->getLHS())
15147           CheckArrayAccess(lhs);
15148         if (const Expr *rhs = cond->getRHS())
15149           CheckArrayAccess(rhs);
15150         return;
15151       }
15152       case Stmt::CXXOperatorCallExprClass: {
15153         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
15154         for (const auto *Arg : OCE->arguments())
15155           CheckArrayAccess(Arg);
15156         return;
15157       }
15158       default:
15159         return;
15160     }
15161   }
15162 }
15163 
15164 //===--- CHECK: Objective-C retain cycles ----------------------------------//
15165 
15166 namespace {
15167 
15168 struct RetainCycleOwner {
15169   VarDecl *Variable = nullptr;
15170   SourceRange Range;
15171   SourceLocation Loc;
15172   bool Indirect = false;
15173 
15174   RetainCycleOwner() = default;
15175 
15176   void setLocsFrom(Expr *e) {
15177     Loc = e->getExprLoc();
15178     Range = e->getSourceRange();
15179   }
15180 };
15181 
15182 } // namespace
15183 
15184 /// Consider whether capturing the given variable can possibly lead to
15185 /// a retain cycle.
15186 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
15187   // In ARC, it's captured strongly iff the variable has __strong
15188   // lifetime.  In MRR, it's captured strongly if the variable is
15189   // __block and has an appropriate type.
15190   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15191     return false;
15192 
15193   owner.Variable = var;
15194   if (ref)
15195     owner.setLocsFrom(ref);
15196   return true;
15197 }
15198 
15199 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
15200   while (true) {
15201     e = e->IgnoreParens();
15202     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
15203       switch (cast->getCastKind()) {
15204       case CK_BitCast:
15205       case CK_LValueBitCast:
15206       case CK_LValueToRValue:
15207       case CK_ARCReclaimReturnedObject:
15208         e = cast->getSubExpr();
15209         continue;
15210 
15211       default:
15212         return false;
15213       }
15214     }
15215 
15216     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
15217       ObjCIvarDecl *ivar = ref->getDecl();
15218       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
15219         return false;
15220 
15221       // Try to find a retain cycle in the base.
15222       if (!findRetainCycleOwner(S, ref->getBase(), owner))
15223         return false;
15224 
15225       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
15226       owner.Indirect = true;
15227       return true;
15228     }
15229 
15230     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
15231       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
15232       if (!var) return false;
15233       return considerVariable(var, ref, owner);
15234     }
15235 
15236     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
15237       if (member->isArrow()) return false;
15238 
15239       // Don't count this as an indirect ownership.
15240       e = member->getBase();
15241       continue;
15242     }
15243 
15244     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
15245       // Only pay attention to pseudo-objects on property references.
15246       ObjCPropertyRefExpr *pre
15247         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
15248                                               ->IgnoreParens());
15249       if (!pre) return false;
15250       if (pre->isImplicitProperty()) return false;
15251       ObjCPropertyDecl *property = pre->getExplicitProperty();
15252       if (!property->isRetaining() &&
15253           !(property->getPropertyIvarDecl() &&
15254             property->getPropertyIvarDecl()->getType()
15255               .getObjCLifetime() == Qualifiers::OCL_Strong))
15256           return false;
15257 
15258       owner.Indirect = true;
15259       if (pre->isSuperReceiver()) {
15260         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
15261         if (!owner.Variable)
15262           return false;
15263         owner.Loc = pre->getLocation();
15264         owner.Range = pre->getSourceRange();
15265         return true;
15266       }
15267       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
15268                               ->getSourceExpr());
15269       continue;
15270     }
15271 
15272     // Array ivars?
15273 
15274     return false;
15275   }
15276 }
15277 
15278 namespace {
15279 
15280   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
15281     ASTContext &Context;
15282     VarDecl *Variable;
15283     Expr *Capturer = nullptr;
15284     bool VarWillBeReased = false;
15285 
15286     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
15287         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
15288           Context(Context), Variable(variable) {}
15289 
15290     void VisitDeclRefExpr(DeclRefExpr *ref) {
15291       if (ref->getDecl() == Variable && !Capturer)
15292         Capturer = ref;
15293     }
15294 
15295     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
15296       if (Capturer) return;
15297       Visit(ref->getBase());
15298       if (Capturer && ref->isFreeIvar())
15299         Capturer = ref;
15300     }
15301 
15302     void VisitBlockExpr(BlockExpr *block) {
15303       // Look inside nested blocks
15304       if (block->getBlockDecl()->capturesVariable(Variable))
15305         Visit(block->getBlockDecl()->getBody());
15306     }
15307 
15308     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
15309       if (Capturer) return;
15310       if (OVE->getSourceExpr())
15311         Visit(OVE->getSourceExpr());
15312     }
15313 
15314     void VisitBinaryOperator(BinaryOperator *BinOp) {
15315       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
15316         return;
15317       Expr *LHS = BinOp->getLHS();
15318       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
15319         if (DRE->getDecl() != Variable)
15320           return;
15321         if (Expr *RHS = BinOp->getRHS()) {
15322           RHS = RHS->IgnoreParenCasts();
15323           Optional<llvm::APSInt> Value;
15324           VarWillBeReased =
15325               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
15326                *Value == 0);
15327         }
15328       }
15329     }
15330   };
15331 
15332 } // namespace
15333 
15334 /// Check whether the given argument is a block which captures a
15335 /// variable.
15336 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
15337   assert(owner.Variable && owner.Loc.isValid());
15338 
15339   e = e->IgnoreParenCasts();
15340 
15341   // Look through [^{...} copy] and Block_copy(^{...}).
15342   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
15343     Selector Cmd = ME->getSelector();
15344     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
15345       e = ME->getInstanceReceiver();
15346       if (!e)
15347         return nullptr;
15348       e = e->IgnoreParenCasts();
15349     }
15350   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
15351     if (CE->getNumArgs() == 1) {
15352       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
15353       if (Fn) {
15354         const IdentifierInfo *FnI = Fn->getIdentifier();
15355         if (FnI && FnI->isStr("_Block_copy")) {
15356           e = CE->getArg(0)->IgnoreParenCasts();
15357         }
15358       }
15359     }
15360   }
15361 
15362   BlockExpr *block = dyn_cast<BlockExpr>(e);
15363   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
15364     return nullptr;
15365 
15366   FindCaptureVisitor visitor(S.Context, owner.Variable);
15367   visitor.Visit(block->getBlockDecl()->getBody());
15368   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
15369 }
15370 
15371 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
15372                                 RetainCycleOwner &owner) {
15373   assert(capturer);
15374   assert(owner.Variable && owner.Loc.isValid());
15375 
15376   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
15377     << owner.Variable << capturer->getSourceRange();
15378   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
15379     << owner.Indirect << owner.Range;
15380 }
15381 
15382 /// Check for a keyword selector that starts with the word 'add' or
15383 /// 'set'.
15384 static bool isSetterLikeSelector(Selector sel) {
15385   if (sel.isUnarySelector()) return false;
15386 
15387   StringRef str = sel.getNameForSlot(0);
15388   while (!str.empty() && str.front() == '_') str = str.substr(1);
15389   if (str.startswith("set"))
15390     str = str.substr(3);
15391   else if (str.startswith("add")) {
15392     // Specially allow 'addOperationWithBlock:'.
15393     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
15394       return false;
15395     str = str.substr(3);
15396   }
15397   else
15398     return false;
15399 
15400   if (str.empty()) return true;
15401   return !isLowercase(str.front());
15402 }
15403 
15404 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
15405                                                     ObjCMessageExpr *Message) {
15406   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
15407                                                 Message->getReceiverInterface(),
15408                                                 NSAPI::ClassId_NSMutableArray);
15409   if (!IsMutableArray) {
15410     return None;
15411   }
15412 
15413   Selector Sel = Message->getSelector();
15414 
15415   Optional<NSAPI::NSArrayMethodKind> MKOpt =
15416     S.NSAPIObj->getNSArrayMethodKind(Sel);
15417   if (!MKOpt) {
15418     return None;
15419   }
15420 
15421   NSAPI::NSArrayMethodKind MK = *MKOpt;
15422 
15423   switch (MK) {
15424     case NSAPI::NSMutableArr_addObject:
15425     case NSAPI::NSMutableArr_insertObjectAtIndex:
15426     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
15427       return 0;
15428     case NSAPI::NSMutableArr_replaceObjectAtIndex:
15429       return 1;
15430 
15431     default:
15432       return None;
15433   }
15434 
15435   return None;
15436 }
15437 
15438 static
15439 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
15440                                                   ObjCMessageExpr *Message) {
15441   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
15442                                             Message->getReceiverInterface(),
15443                                             NSAPI::ClassId_NSMutableDictionary);
15444   if (!IsMutableDictionary) {
15445     return None;
15446   }
15447 
15448   Selector Sel = Message->getSelector();
15449 
15450   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
15451     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
15452   if (!MKOpt) {
15453     return None;
15454   }
15455 
15456   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
15457 
15458   switch (MK) {
15459     case NSAPI::NSMutableDict_setObjectForKey:
15460     case NSAPI::NSMutableDict_setValueForKey:
15461     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
15462       return 0;
15463 
15464     default:
15465       return None;
15466   }
15467 
15468   return None;
15469 }
15470 
15471 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
15472   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
15473                                                 Message->getReceiverInterface(),
15474                                                 NSAPI::ClassId_NSMutableSet);
15475 
15476   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
15477                                             Message->getReceiverInterface(),
15478                                             NSAPI::ClassId_NSMutableOrderedSet);
15479   if (!IsMutableSet && !IsMutableOrderedSet) {
15480     return None;
15481   }
15482 
15483   Selector Sel = Message->getSelector();
15484 
15485   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
15486   if (!MKOpt) {
15487     return None;
15488   }
15489 
15490   NSAPI::NSSetMethodKind MK = *MKOpt;
15491 
15492   switch (MK) {
15493     case NSAPI::NSMutableSet_addObject:
15494     case NSAPI::NSOrderedSet_setObjectAtIndex:
15495     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
15496     case NSAPI::NSOrderedSet_insertObjectAtIndex:
15497       return 0;
15498     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
15499       return 1;
15500   }
15501 
15502   return None;
15503 }
15504 
15505 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
15506   if (!Message->isInstanceMessage()) {
15507     return;
15508   }
15509 
15510   Optional<int> ArgOpt;
15511 
15512   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
15513       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
15514       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
15515     return;
15516   }
15517 
15518   int ArgIndex = *ArgOpt;
15519 
15520   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
15521   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
15522     Arg = OE->getSourceExpr()->IgnoreImpCasts();
15523   }
15524 
15525   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
15526     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15527       if (ArgRE->isObjCSelfExpr()) {
15528         Diag(Message->getSourceRange().getBegin(),
15529              diag::warn_objc_circular_container)
15530           << ArgRE->getDecl() << StringRef("'super'");
15531       }
15532     }
15533   } else {
15534     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
15535 
15536     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
15537       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
15538     }
15539 
15540     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
15541       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
15542         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
15543           ValueDecl *Decl = ReceiverRE->getDecl();
15544           Diag(Message->getSourceRange().getBegin(),
15545                diag::warn_objc_circular_container)
15546             << Decl << Decl;
15547           if (!ArgRE->isObjCSelfExpr()) {
15548             Diag(Decl->getLocation(),
15549                  diag::note_objc_circular_container_declared_here)
15550               << Decl;
15551           }
15552         }
15553       }
15554     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
15555       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
15556         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
15557           ObjCIvarDecl *Decl = IvarRE->getDecl();
15558           Diag(Message->getSourceRange().getBegin(),
15559                diag::warn_objc_circular_container)
15560             << Decl << Decl;
15561           Diag(Decl->getLocation(),
15562                diag::note_objc_circular_container_declared_here)
15563             << Decl;
15564         }
15565       }
15566     }
15567   }
15568 }
15569 
15570 /// Check a message send to see if it's likely to cause a retain cycle.
15571 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
15572   // Only check instance methods whose selector looks like a setter.
15573   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
15574     return;
15575 
15576   // Try to find a variable that the receiver is strongly owned by.
15577   RetainCycleOwner owner;
15578   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
15579     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
15580       return;
15581   } else {
15582     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
15583     owner.Variable = getCurMethodDecl()->getSelfDecl();
15584     owner.Loc = msg->getSuperLoc();
15585     owner.Range = msg->getSuperLoc();
15586   }
15587 
15588   // Check whether the receiver is captured by any of the arguments.
15589   const ObjCMethodDecl *MD = msg->getMethodDecl();
15590   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
15591     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
15592       // noescape blocks should not be retained by the method.
15593       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
15594         continue;
15595       return diagnoseRetainCycle(*this, capturer, owner);
15596     }
15597   }
15598 }
15599 
15600 /// Check a property assign to see if it's likely to cause a retain cycle.
15601 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
15602   RetainCycleOwner owner;
15603   if (!findRetainCycleOwner(*this, receiver, owner))
15604     return;
15605 
15606   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
15607     diagnoseRetainCycle(*this, capturer, owner);
15608 }
15609 
15610 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
15611   RetainCycleOwner Owner;
15612   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
15613     return;
15614 
15615   // Because we don't have an expression for the variable, we have to set the
15616   // location explicitly here.
15617   Owner.Loc = Var->getLocation();
15618   Owner.Range = Var->getSourceRange();
15619 
15620   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
15621     diagnoseRetainCycle(*this, Capturer, Owner);
15622 }
15623 
15624 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
15625                                      Expr *RHS, bool isProperty) {
15626   // Check if RHS is an Objective-C object literal, which also can get
15627   // immediately zapped in a weak reference.  Note that we explicitly
15628   // allow ObjCStringLiterals, since those are designed to never really die.
15629   RHS = RHS->IgnoreParenImpCasts();
15630 
15631   // This enum needs to match with the 'select' in
15632   // warn_objc_arc_literal_assign (off-by-1).
15633   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
15634   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
15635     return false;
15636 
15637   S.Diag(Loc, diag::warn_arc_literal_assign)
15638     << (unsigned) Kind
15639     << (isProperty ? 0 : 1)
15640     << RHS->getSourceRange();
15641 
15642   return true;
15643 }
15644 
15645 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
15646                                     Qualifiers::ObjCLifetime LT,
15647                                     Expr *RHS, bool isProperty) {
15648   // Strip off any implicit cast added to get to the one ARC-specific.
15649   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15650     if (cast->getCastKind() == CK_ARCConsumeObject) {
15651       S.Diag(Loc, diag::warn_arc_retained_assign)
15652         << (LT == Qualifiers::OCL_ExplicitNone)
15653         << (isProperty ? 0 : 1)
15654         << RHS->getSourceRange();
15655       return true;
15656     }
15657     RHS = cast->getSubExpr();
15658   }
15659 
15660   if (LT == Qualifiers::OCL_Weak &&
15661       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
15662     return true;
15663 
15664   return false;
15665 }
15666 
15667 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
15668                               QualType LHS, Expr *RHS) {
15669   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
15670 
15671   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
15672     return false;
15673 
15674   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
15675     return true;
15676 
15677   return false;
15678 }
15679 
15680 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
15681                               Expr *LHS, Expr *RHS) {
15682   QualType LHSType;
15683   // PropertyRef on LHS type need be directly obtained from
15684   // its declaration as it has a PseudoType.
15685   ObjCPropertyRefExpr *PRE
15686     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
15687   if (PRE && !PRE->isImplicitProperty()) {
15688     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15689     if (PD)
15690       LHSType = PD->getType();
15691   }
15692 
15693   if (LHSType.isNull())
15694     LHSType = LHS->getType();
15695 
15696   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
15697 
15698   if (LT == Qualifiers::OCL_Weak) {
15699     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
15700       getCurFunction()->markSafeWeakUse(LHS);
15701   }
15702 
15703   if (checkUnsafeAssigns(Loc, LHSType, RHS))
15704     return;
15705 
15706   // FIXME. Check for other life times.
15707   if (LT != Qualifiers::OCL_None)
15708     return;
15709 
15710   if (PRE) {
15711     if (PRE->isImplicitProperty())
15712       return;
15713     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
15714     if (!PD)
15715       return;
15716 
15717     unsigned Attributes = PD->getPropertyAttributes();
15718     if (Attributes & ObjCPropertyAttribute::kind_assign) {
15719       // when 'assign' attribute was not explicitly specified
15720       // by user, ignore it and rely on property type itself
15721       // for lifetime info.
15722       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
15723       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
15724           LHSType->isObjCRetainableType())
15725         return;
15726 
15727       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
15728         if (cast->getCastKind() == CK_ARCConsumeObject) {
15729           Diag(Loc, diag::warn_arc_retained_property_assign)
15730           << RHS->getSourceRange();
15731           return;
15732         }
15733         RHS = cast->getSubExpr();
15734       }
15735     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
15736       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
15737         return;
15738     }
15739   }
15740 }
15741 
15742 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
15743 
15744 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15745                                         SourceLocation StmtLoc,
15746                                         const NullStmt *Body) {
15747   // Do not warn if the body is a macro that expands to nothing, e.g:
15748   //
15749   // #define CALL(x)
15750   // if (condition)
15751   //   CALL(0);
15752   if (Body->hasLeadingEmptyMacro())
15753     return false;
15754 
15755   // Get line numbers of statement and body.
15756   bool StmtLineInvalid;
15757   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15758                                                       &StmtLineInvalid);
15759   if (StmtLineInvalid)
15760     return false;
15761 
15762   bool BodyLineInvalid;
15763   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15764                                                       &BodyLineInvalid);
15765   if (BodyLineInvalid)
15766     return false;
15767 
15768   // Warn if null statement and body are on the same line.
15769   if (StmtLine != BodyLine)
15770     return false;
15771 
15772   return true;
15773 }
15774 
15775 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15776                                  const Stmt *Body,
15777                                  unsigned DiagID) {
15778   // Since this is a syntactic check, don't emit diagnostic for template
15779   // instantiations, this just adds noise.
15780   if (CurrentInstantiationScope)
15781     return;
15782 
15783   // The body should be a null statement.
15784   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15785   if (!NBody)
15786     return;
15787 
15788   // Do the usual checks.
15789   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15790     return;
15791 
15792   Diag(NBody->getSemiLoc(), DiagID);
15793   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15794 }
15795 
15796 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15797                                  const Stmt *PossibleBody) {
15798   assert(!CurrentInstantiationScope); // Ensured by caller
15799 
15800   SourceLocation StmtLoc;
15801   const Stmt *Body;
15802   unsigned DiagID;
15803   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15804     StmtLoc = FS->getRParenLoc();
15805     Body = FS->getBody();
15806     DiagID = diag::warn_empty_for_body;
15807   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15808     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15809     Body = WS->getBody();
15810     DiagID = diag::warn_empty_while_body;
15811   } else
15812     return; // Neither `for' nor `while'.
15813 
15814   // The body should be a null statement.
15815   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15816   if (!NBody)
15817     return;
15818 
15819   // Skip expensive checks if diagnostic is disabled.
15820   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15821     return;
15822 
15823   // Do the usual checks.
15824   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15825     return;
15826 
15827   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15828   // noise level low, emit diagnostics only if for/while is followed by a
15829   // CompoundStmt, e.g.:
15830   //    for (int i = 0; i < n; i++);
15831   //    {
15832   //      a(i);
15833   //    }
15834   // or if for/while is followed by a statement with more indentation
15835   // than for/while itself:
15836   //    for (int i = 0; i < n; i++);
15837   //      a(i);
15838   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15839   if (!ProbableTypo) {
15840     bool BodyColInvalid;
15841     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15842         PossibleBody->getBeginLoc(), &BodyColInvalid);
15843     if (BodyColInvalid)
15844       return;
15845 
15846     bool StmtColInvalid;
15847     unsigned StmtCol =
15848         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15849     if (StmtColInvalid)
15850       return;
15851 
15852     if (BodyCol > StmtCol)
15853       ProbableTypo = true;
15854   }
15855 
15856   if (ProbableTypo) {
15857     Diag(NBody->getSemiLoc(), DiagID);
15858     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15859   }
15860 }
15861 
15862 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15863 
15864 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15865 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15866                              SourceLocation OpLoc) {
15867   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15868     return;
15869 
15870   if (inTemplateInstantiation())
15871     return;
15872 
15873   // Strip parens and casts away.
15874   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15875   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15876 
15877   // Check for a call expression
15878   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15879   if (!CE || CE->getNumArgs() != 1)
15880     return;
15881 
15882   // Check for a call to std::move
15883   if (!CE->isCallToStdMove())
15884     return;
15885 
15886   // Get argument from std::move
15887   RHSExpr = CE->getArg(0);
15888 
15889   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15890   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15891 
15892   // Two DeclRefExpr's, check that the decls are the same.
15893   if (LHSDeclRef && RHSDeclRef) {
15894     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15895       return;
15896     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15897         RHSDeclRef->getDecl()->getCanonicalDecl())
15898       return;
15899 
15900     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15901                                         << LHSExpr->getSourceRange()
15902                                         << RHSExpr->getSourceRange();
15903     return;
15904   }
15905 
15906   // Member variables require a different approach to check for self moves.
15907   // MemberExpr's are the same if every nested MemberExpr refers to the same
15908   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15909   // the base Expr's are CXXThisExpr's.
15910   const Expr *LHSBase = LHSExpr;
15911   const Expr *RHSBase = RHSExpr;
15912   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15913   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15914   if (!LHSME || !RHSME)
15915     return;
15916 
15917   while (LHSME && RHSME) {
15918     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15919         RHSME->getMemberDecl()->getCanonicalDecl())
15920       return;
15921 
15922     LHSBase = LHSME->getBase();
15923     RHSBase = RHSME->getBase();
15924     LHSME = dyn_cast<MemberExpr>(LHSBase);
15925     RHSME = dyn_cast<MemberExpr>(RHSBase);
15926   }
15927 
15928   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15929   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15930   if (LHSDeclRef && RHSDeclRef) {
15931     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15932       return;
15933     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15934         RHSDeclRef->getDecl()->getCanonicalDecl())
15935       return;
15936 
15937     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15938                                         << LHSExpr->getSourceRange()
15939                                         << RHSExpr->getSourceRange();
15940     return;
15941   }
15942 
15943   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15944     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15945                                         << LHSExpr->getSourceRange()
15946                                         << RHSExpr->getSourceRange();
15947 }
15948 
15949 //===--- Layout compatibility ----------------------------------------------//
15950 
15951 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15952 
15953 /// Check if two enumeration types are layout-compatible.
15954 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15955   // C++11 [dcl.enum] p8:
15956   // Two enumeration types are layout-compatible if they have the same
15957   // underlying type.
15958   return ED1->isComplete() && ED2->isComplete() &&
15959          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15960 }
15961 
15962 /// Check if two fields are layout-compatible.
15963 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15964                                FieldDecl *Field2) {
15965   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15966     return false;
15967 
15968   if (Field1->isBitField() != Field2->isBitField())
15969     return false;
15970 
15971   if (Field1->isBitField()) {
15972     // Make sure that the bit-fields are the same length.
15973     unsigned Bits1 = Field1->getBitWidthValue(C);
15974     unsigned Bits2 = Field2->getBitWidthValue(C);
15975 
15976     if (Bits1 != Bits2)
15977       return false;
15978   }
15979 
15980   return true;
15981 }
15982 
15983 /// Check if two standard-layout structs are layout-compatible.
15984 /// (C++11 [class.mem] p17)
15985 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15986                                      RecordDecl *RD2) {
15987   // If both records are C++ classes, check that base classes match.
15988   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15989     // If one of records is a CXXRecordDecl we are in C++ mode,
15990     // thus the other one is a CXXRecordDecl, too.
15991     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15992     // Check number of base classes.
15993     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15994       return false;
15995 
15996     // Check the base classes.
15997     for (CXXRecordDecl::base_class_const_iterator
15998                Base1 = D1CXX->bases_begin(),
15999            BaseEnd1 = D1CXX->bases_end(),
16000               Base2 = D2CXX->bases_begin();
16001          Base1 != BaseEnd1;
16002          ++Base1, ++Base2) {
16003       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
16004         return false;
16005     }
16006   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
16007     // If only RD2 is a C++ class, it should have zero base classes.
16008     if (D2CXX->getNumBases() > 0)
16009       return false;
16010   }
16011 
16012   // Check the fields.
16013   RecordDecl::field_iterator Field2 = RD2->field_begin(),
16014                              Field2End = RD2->field_end(),
16015                              Field1 = RD1->field_begin(),
16016                              Field1End = RD1->field_end();
16017   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
16018     if (!isLayoutCompatible(C, *Field1, *Field2))
16019       return false;
16020   }
16021   if (Field1 != Field1End || Field2 != Field2End)
16022     return false;
16023 
16024   return true;
16025 }
16026 
16027 /// Check if two standard-layout unions are layout-compatible.
16028 /// (C++11 [class.mem] p18)
16029 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
16030                                     RecordDecl *RD2) {
16031   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
16032   for (auto *Field2 : RD2->fields())
16033     UnmatchedFields.insert(Field2);
16034 
16035   for (auto *Field1 : RD1->fields()) {
16036     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
16037         I = UnmatchedFields.begin(),
16038         E = UnmatchedFields.end();
16039 
16040     for ( ; I != E; ++I) {
16041       if (isLayoutCompatible(C, Field1, *I)) {
16042         bool Result = UnmatchedFields.erase(*I);
16043         (void) Result;
16044         assert(Result);
16045         break;
16046       }
16047     }
16048     if (I == E)
16049       return false;
16050   }
16051 
16052   return UnmatchedFields.empty();
16053 }
16054 
16055 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
16056                                RecordDecl *RD2) {
16057   if (RD1->isUnion() != RD2->isUnion())
16058     return false;
16059 
16060   if (RD1->isUnion())
16061     return isLayoutCompatibleUnion(C, RD1, RD2);
16062   else
16063     return isLayoutCompatibleStruct(C, RD1, RD2);
16064 }
16065 
16066 /// Check if two types are layout-compatible in C++11 sense.
16067 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
16068   if (T1.isNull() || T2.isNull())
16069     return false;
16070 
16071   // C++11 [basic.types] p11:
16072   // If two types T1 and T2 are the same type, then T1 and T2 are
16073   // layout-compatible types.
16074   if (C.hasSameType(T1, T2))
16075     return true;
16076 
16077   T1 = T1.getCanonicalType().getUnqualifiedType();
16078   T2 = T2.getCanonicalType().getUnqualifiedType();
16079 
16080   const Type::TypeClass TC1 = T1->getTypeClass();
16081   const Type::TypeClass TC2 = T2->getTypeClass();
16082 
16083   if (TC1 != TC2)
16084     return false;
16085 
16086   if (TC1 == Type::Enum) {
16087     return isLayoutCompatible(C,
16088                               cast<EnumType>(T1)->getDecl(),
16089                               cast<EnumType>(T2)->getDecl());
16090   } else if (TC1 == Type::Record) {
16091     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
16092       return false;
16093 
16094     return isLayoutCompatible(C,
16095                               cast<RecordType>(T1)->getDecl(),
16096                               cast<RecordType>(T2)->getDecl());
16097   }
16098 
16099   return false;
16100 }
16101 
16102 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
16103 
16104 /// Given a type tag expression find the type tag itself.
16105 ///
16106 /// \param TypeExpr Type tag expression, as it appears in user's code.
16107 ///
16108 /// \param VD Declaration of an identifier that appears in a type tag.
16109 ///
16110 /// \param MagicValue Type tag magic value.
16111 ///
16112 /// \param isConstantEvaluated whether the evalaution should be performed in
16113 
16114 /// constant context.
16115 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
16116                             const ValueDecl **VD, uint64_t *MagicValue,
16117                             bool isConstantEvaluated) {
16118   while(true) {
16119     if (!TypeExpr)
16120       return false;
16121 
16122     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
16123 
16124     switch (TypeExpr->getStmtClass()) {
16125     case Stmt::UnaryOperatorClass: {
16126       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
16127       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
16128         TypeExpr = UO->getSubExpr();
16129         continue;
16130       }
16131       return false;
16132     }
16133 
16134     case Stmt::DeclRefExprClass: {
16135       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
16136       *VD = DRE->getDecl();
16137       return true;
16138     }
16139 
16140     case Stmt::IntegerLiteralClass: {
16141       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
16142       llvm::APInt MagicValueAPInt = IL->getValue();
16143       if (MagicValueAPInt.getActiveBits() <= 64) {
16144         *MagicValue = MagicValueAPInt.getZExtValue();
16145         return true;
16146       } else
16147         return false;
16148     }
16149 
16150     case Stmt::BinaryConditionalOperatorClass:
16151     case Stmt::ConditionalOperatorClass: {
16152       const AbstractConditionalOperator *ACO =
16153           cast<AbstractConditionalOperator>(TypeExpr);
16154       bool Result;
16155       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
16156                                                      isConstantEvaluated)) {
16157         if (Result)
16158           TypeExpr = ACO->getTrueExpr();
16159         else
16160           TypeExpr = ACO->getFalseExpr();
16161         continue;
16162       }
16163       return false;
16164     }
16165 
16166     case Stmt::BinaryOperatorClass: {
16167       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
16168       if (BO->getOpcode() == BO_Comma) {
16169         TypeExpr = BO->getRHS();
16170         continue;
16171       }
16172       return false;
16173     }
16174 
16175     default:
16176       return false;
16177     }
16178   }
16179 }
16180 
16181 /// Retrieve the C type corresponding to type tag TypeExpr.
16182 ///
16183 /// \param TypeExpr Expression that specifies a type tag.
16184 ///
16185 /// \param MagicValues Registered magic values.
16186 ///
16187 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
16188 ///        kind.
16189 ///
16190 /// \param TypeInfo Information about the corresponding C type.
16191 ///
16192 /// \param isConstantEvaluated whether the evalaution should be performed in
16193 /// constant context.
16194 ///
16195 /// \returns true if the corresponding C type was found.
16196 static bool GetMatchingCType(
16197     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
16198     const ASTContext &Ctx,
16199     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
16200         *MagicValues,
16201     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
16202     bool isConstantEvaluated) {
16203   FoundWrongKind = false;
16204 
16205   // Variable declaration that has type_tag_for_datatype attribute.
16206   const ValueDecl *VD = nullptr;
16207 
16208   uint64_t MagicValue;
16209 
16210   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
16211     return false;
16212 
16213   if (VD) {
16214     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
16215       if (I->getArgumentKind() != ArgumentKind) {
16216         FoundWrongKind = true;
16217         return false;
16218       }
16219       TypeInfo.Type = I->getMatchingCType();
16220       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
16221       TypeInfo.MustBeNull = I->getMustBeNull();
16222       return true;
16223     }
16224     return false;
16225   }
16226 
16227   if (!MagicValues)
16228     return false;
16229 
16230   llvm::DenseMap<Sema::TypeTagMagicValue,
16231                  Sema::TypeTagData>::const_iterator I =
16232       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
16233   if (I == MagicValues->end())
16234     return false;
16235 
16236   TypeInfo = I->second;
16237   return true;
16238 }
16239 
16240 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
16241                                       uint64_t MagicValue, QualType Type,
16242                                       bool LayoutCompatible,
16243                                       bool MustBeNull) {
16244   if (!TypeTagForDatatypeMagicValues)
16245     TypeTagForDatatypeMagicValues.reset(
16246         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
16247 
16248   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
16249   (*TypeTagForDatatypeMagicValues)[Magic] =
16250       TypeTagData(Type, LayoutCompatible, MustBeNull);
16251 }
16252 
16253 static bool IsSameCharType(QualType T1, QualType T2) {
16254   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
16255   if (!BT1)
16256     return false;
16257 
16258   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
16259   if (!BT2)
16260     return false;
16261 
16262   BuiltinType::Kind T1Kind = BT1->getKind();
16263   BuiltinType::Kind T2Kind = BT2->getKind();
16264 
16265   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
16266          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
16267          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
16268          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
16269 }
16270 
16271 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
16272                                     const ArrayRef<const Expr *> ExprArgs,
16273                                     SourceLocation CallSiteLoc) {
16274   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
16275   bool IsPointerAttr = Attr->getIsPointer();
16276 
16277   // Retrieve the argument representing the 'type_tag'.
16278   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
16279   if (TypeTagIdxAST >= ExprArgs.size()) {
16280     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16281         << 0 << Attr->getTypeTagIdx().getSourceIndex();
16282     return;
16283   }
16284   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
16285   bool FoundWrongKind;
16286   TypeTagData TypeInfo;
16287   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
16288                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
16289                         TypeInfo, isConstantEvaluated())) {
16290     if (FoundWrongKind)
16291       Diag(TypeTagExpr->getExprLoc(),
16292            diag::warn_type_tag_for_datatype_wrong_kind)
16293         << TypeTagExpr->getSourceRange();
16294     return;
16295   }
16296 
16297   // Retrieve the argument representing the 'arg_idx'.
16298   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
16299   if (ArgumentIdxAST >= ExprArgs.size()) {
16300     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
16301         << 1 << Attr->getArgumentIdx().getSourceIndex();
16302     return;
16303   }
16304   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
16305   if (IsPointerAttr) {
16306     // Skip implicit cast of pointer to `void *' (as a function argument).
16307     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
16308       if (ICE->getType()->isVoidPointerType() &&
16309           ICE->getCastKind() == CK_BitCast)
16310         ArgumentExpr = ICE->getSubExpr();
16311   }
16312   QualType ArgumentType = ArgumentExpr->getType();
16313 
16314   // Passing a `void*' pointer shouldn't trigger a warning.
16315   if (IsPointerAttr && ArgumentType->isVoidPointerType())
16316     return;
16317 
16318   if (TypeInfo.MustBeNull) {
16319     // Type tag with matching void type requires a null pointer.
16320     if (!ArgumentExpr->isNullPointerConstant(Context,
16321                                              Expr::NPC_ValueDependentIsNotNull)) {
16322       Diag(ArgumentExpr->getExprLoc(),
16323            diag::warn_type_safety_null_pointer_required)
16324           << ArgumentKind->getName()
16325           << ArgumentExpr->getSourceRange()
16326           << TypeTagExpr->getSourceRange();
16327     }
16328     return;
16329   }
16330 
16331   QualType RequiredType = TypeInfo.Type;
16332   if (IsPointerAttr)
16333     RequiredType = Context.getPointerType(RequiredType);
16334 
16335   bool mismatch = false;
16336   if (!TypeInfo.LayoutCompatible) {
16337     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
16338 
16339     // C++11 [basic.fundamental] p1:
16340     // Plain char, signed char, and unsigned char are three distinct types.
16341     //
16342     // But we treat plain `char' as equivalent to `signed char' or `unsigned
16343     // char' depending on the current char signedness mode.
16344     if (mismatch)
16345       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
16346                                            RequiredType->getPointeeType())) ||
16347           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
16348         mismatch = false;
16349   } else
16350     if (IsPointerAttr)
16351       mismatch = !isLayoutCompatible(Context,
16352                                      ArgumentType->getPointeeType(),
16353                                      RequiredType->getPointeeType());
16354     else
16355       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
16356 
16357   if (mismatch)
16358     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
16359         << ArgumentType << ArgumentKind
16360         << TypeInfo.LayoutCompatible << RequiredType
16361         << ArgumentExpr->getSourceRange()
16362         << TypeTagExpr->getSourceRange();
16363 }
16364 
16365 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
16366                                          CharUnits Alignment) {
16367   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
16368 }
16369 
16370 void Sema::DiagnoseMisalignedMembers() {
16371   for (MisalignedMember &m : MisalignedMembers) {
16372     const NamedDecl *ND = m.RD;
16373     if (ND->getName().empty()) {
16374       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
16375         ND = TD;
16376     }
16377     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
16378         << m.MD << ND << m.E->getSourceRange();
16379   }
16380   MisalignedMembers.clear();
16381 }
16382 
16383 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
16384   E = E->IgnoreParens();
16385   if (!T->isPointerType() && !T->isIntegerType())
16386     return;
16387   if (isa<UnaryOperator>(E) &&
16388       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
16389     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
16390     if (isa<MemberExpr>(Op)) {
16391       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
16392       if (MA != MisalignedMembers.end() &&
16393           (T->isIntegerType() ||
16394            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
16395                                    Context.getTypeAlignInChars(
16396                                        T->getPointeeType()) <= MA->Alignment))))
16397         MisalignedMembers.erase(MA);
16398     }
16399   }
16400 }
16401 
16402 void Sema::RefersToMemberWithReducedAlignment(
16403     Expr *E,
16404     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
16405         Action) {
16406   const auto *ME = dyn_cast<MemberExpr>(E);
16407   if (!ME)
16408     return;
16409 
16410   // No need to check expressions with an __unaligned-qualified type.
16411   if (E->getType().getQualifiers().hasUnaligned())
16412     return;
16413 
16414   // For a chain of MemberExpr like "a.b.c.d" this list
16415   // will keep FieldDecl's like [d, c, b].
16416   SmallVector<FieldDecl *, 4> ReverseMemberChain;
16417   const MemberExpr *TopME = nullptr;
16418   bool AnyIsPacked = false;
16419   do {
16420     QualType BaseType = ME->getBase()->getType();
16421     if (BaseType->isDependentType())
16422       return;
16423     if (ME->isArrow())
16424       BaseType = BaseType->getPointeeType();
16425     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
16426     if (RD->isInvalidDecl())
16427       return;
16428 
16429     ValueDecl *MD = ME->getMemberDecl();
16430     auto *FD = dyn_cast<FieldDecl>(MD);
16431     // We do not care about non-data members.
16432     if (!FD || FD->isInvalidDecl())
16433       return;
16434 
16435     AnyIsPacked =
16436         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
16437     ReverseMemberChain.push_back(FD);
16438 
16439     TopME = ME;
16440     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
16441   } while (ME);
16442   assert(TopME && "We did not compute a topmost MemberExpr!");
16443 
16444   // Not the scope of this diagnostic.
16445   if (!AnyIsPacked)
16446     return;
16447 
16448   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
16449   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
16450   // TODO: The innermost base of the member expression may be too complicated.
16451   // For now, just disregard these cases. This is left for future
16452   // improvement.
16453   if (!DRE && !isa<CXXThisExpr>(TopBase))
16454       return;
16455 
16456   // Alignment expected by the whole expression.
16457   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
16458 
16459   // No need to do anything else with this case.
16460   if (ExpectedAlignment.isOne())
16461     return;
16462 
16463   // Synthesize offset of the whole access.
16464   CharUnits Offset;
16465   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
16466        I++) {
16467     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
16468   }
16469 
16470   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
16471   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
16472       ReverseMemberChain.back()->getParent()->getTypeForDecl());
16473 
16474   // The base expression of the innermost MemberExpr may give
16475   // stronger guarantees than the class containing the member.
16476   if (DRE && !TopME->isArrow()) {
16477     const ValueDecl *VD = DRE->getDecl();
16478     if (!VD->getType()->isReferenceType())
16479       CompleteObjectAlignment =
16480           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
16481   }
16482 
16483   // Check if the synthesized offset fulfills the alignment.
16484   if (Offset % ExpectedAlignment != 0 ||
16485       // It may fulfill the offset it but the effective alignment may still be
16486       // lower than the expected expression alignment.
16487       CompleteObjectAlignment < ExpectedAlignment) {
16488     // If this happens, we want to determine a sensible culprit of this.
16489     // Intuitively, watching the chain of member expressions from right to
16490     // left, we start with the required alignment (as required by the field
16491     // type) but some packed attribute in that chain has reduced the alignment.
16492     // It may happen that another packed structure increases it again. But if
16493     // we are here such increase has not been enough. So pointing the first
16494     // FieldDecl that either is packed or else its RecordDecl is,
16495     // seems reasonable.
16496     FieldDecl *FD = nullptr;
16497     CharUnits Alignment;
16498     for (FieldDecl *FDI : ReverseMemberChain) {
16499       if (FDI->hasAttr<PackedAttr>() ||
16500           FDI->getParent()->hasAttr<PackedAttr>()) {
16501         FD = FDI;
16502         Alignment = std::min(
16503             Context.getTypeAlignInChars(FD->getType()),
16504             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
16505         break;
16506       }
16507     }
16508     assert(FD && "We did not find a packed FieldDecl!");
16509     Action(E, FD->getParent(), FD, Alignment);
16510   }
16511 }
16512 
16513 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
16514   using namespace std::placeholders;
16515 
16516   RefersToMemberWithReducedAlignment(
16517       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
16518                      _2, _3, _4));
16519 }
16520 
16521 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
16522                                             ExprResult CallResult) {
16523   if (checkArgCount(*this, TheCall, 1))
16524     return ExprError();
16525 
16526   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
16527   if (MatrixArg.isInvalid())
16528     return MatrixArg;
16529   Expr *Matrix = MatrixArg.get();
16530 
16531   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
16532   if (!MType) {
16533     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
16534     return ExprError();
16535   }
16536 
16537   // Create returned matrix type by swapping rows and columns of the argument
16538   // matrix type.
16539   QualType ResultType = Context.getConstantMatrixType(
16540       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
16541 
16542   // Change the return type to the type of the returned matrix.
16543   TheCall->setType(ResultType);
16544 
16545   // Update call argument to use the possibly converted matrix argument.
16546   TheCall->setArg(0, Matrix);
16547   return CallResult;
16548 }
16549 
16550 // Get and verify the matrix dimensions.
16551 static llvm::Optional<unsigned>
16552 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
16553   SourceLocation ErrorPos;
16554   Optional<llvm::APSInt> Value =
16555       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
16556   if (!Value) {
16557     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
16558         << Name;
16559     return {};
16560   }
16561   uint64_t Dim = Value->getZExtValue();
16562   if (!ConstantMatrixType::isDimensionValid(Dim)) {
16563     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
16564         << Name << ConstantMatrixType::getMaxElementsPerDimension();
16565     return {};
16566   }
16567   return Dim;
16568 }
16569 
16570 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
16571                                                   ExprResult CallResult) {
16572   if (!getLangOpts().MatrixTypes) {
16573     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
16574     return ExprError();
16575   }
16576 
16577   if (checkArgCount(*this, TheCall, 4))
16578     return ExprError();
16579 
16580   unsigned PtrArgIdx = 0;
16581   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16582   Expr *RowsExpr = TheCall->getArg(1);
16583   Expr *ColumnsExpr = TheCall->getArg(2);
16584   Expr *StrideExpr = TheCall->getArg(3);
16585 
16586   bool ArgError = false;
16587 
16588   // Check pointer argument.
16589   {
16590     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16591     if (PtrConv.isInvalid())
16592       return PtrConv;
16593     PtrExpr = PtrConv.get();
16594     TheCall->setArg(0, PtrExpr);
16595     if (PtrExpr->isTypeDependent()) {
16596       TheCall->setType(Context.DependentTy);
16597       return TheCall;
16598     }
16599   }
16600 
16601   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16602   QualType ElementTy;
16603   if (!PtrTy) {
16604     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16605         << PtrArgIdx + 1;
16606     ArgError = true;
16607   } else {
16608     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
16609 
16610     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
16611       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16612           << PtrArgIdx + 1;
16613       ArgError = true;
16614     }
16615   }
16616 
16617   // Apply default Lvalue conversions and convert the expression to size_t.
16618   auto ApplyArgumentConversions = [this](Expr *E) {
16619     ExprResult Conv = DefaultLvalueConversion(E);
16620     if (Conv.isInvalid())
16621       return Conv;
16622 
16623     return tryConvertExprToType(Conv.get(), Context.getSizeType());
16624   };
16625 
16626   // Apply conversion to row and column expressions.
16627   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
16628   if (!RowsConv.isInvalid()) {
16629     RowsExpr = RowsConv.get();
16630     TheCall->setArg(1, RowsExpr);
16631   } else
16632     RowsExpr = nullptr;
16633 
16634   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
16635   if (!ColumnsConv.isInvalid()) {
16636     ColumnsExpr = ColumnsConv.get();
16637     TheCall->setArg(2, ColumnsExpr);
16638   } else
16639     ColumnsExpr = nullptr;
16640 
16641   // If any any part of the result matrix type is still pending, just use
16642   // Context.DependentTy, until all parts are resolved.
16643   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
16644       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
16645     TheCall->setType(Context.DependentTy);
16646     return CallResult;
16647   }
16648 
16649   // Check row and column dimensions.
16650   llvm::Optional<unsigned> MaybeRows;
16651   if (RowsExpr)
16652     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
16653 
16654   llvm::Optional<unsigned> MaybeColumns;
16655   if (ColumnsExpr)
16656     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
16657 
16658   // Check stride argument.
16659   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
16660   if (StrideConv.isInvalid())
16661     return ExprError();
16662   StrideExpr = StrideConv.get();
16663   TheCall->setArg(3, StrideExpr);
16664 
16665   if (MaybeRows) {
16666     if (Optional<llvm::APSInt> Value =
16667             StrideExpr->getIntegerConstantExpr(Context)) {
16668       uint64_t Stride = Value->getZExtValue();
16669       if (Stride < *MaybeRows) {
16670         Diag(StrideExpr->getBeginLoc(),
16671              diag::err_builtin_matrix_stride_too_small);
16672         ArgError = true;
16673       }
16674     }
16675   }
16676 
16677   if (ArgError || !MaybeRows || !MaybeColumns)
16678     return ExprError();
16679 
16680   TheCall->setType(
16681       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
16682   return CallResult;
16683 }
16684 
16685 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
16686                                                    ExprResult CallResult) {
16687   if (checkArgCount(*this, TheCall, 3))
16688     return ExprError();
16689 
16690   unsigned PtrArgIdx = 1;
16691   Expr *MatrixExpr = TheCall->getArg(0);
16692   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
16693   Expr *StrideExpr = TheCall->getArg(2);
16694 
16695   bool ArgError = false;
16696 
16697   {
16698     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
16699     if (MatrixConv.isInvalid())
16700       return MatrixConv;
16701     MatrixExpr = MatrixConv.get();
16702     TheCall->setArg(0, MatrixExpr);
16703   }
16704   if (MatrixExpr->isTypeDependent()) {
16705     TheCall->setType(Context.DependentTy);
16706     return TheCall;
16707   }
16708 
16709   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
16710   if (!MatrixTy) {
16711     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
16712     ArgError = true;
16713   }
16714 
16715   {
16716     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
16717     if (PtrConv.isInvalid())
16718       return PtrConv;
16719     PtrExpr = PtrConv.get();
16720     TheCall->setArg(1, PtrExpr);
16721     if (PtrExpr->isTypeDependent()) {
16722       TheCall->setType(Context.DependentTy);
16723       return TheCall;
16724     }
16725   }
16726 
16727   // Check pointer argument.
16728   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
16729   if (!PtrTy) {
16730     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
16731         << PtrArgIdx + 1;
16732     ArgError = true;
16733   } else {
16734     QualType ElementTy = PtrTy->getPointeeType();
16735     if (ElementTy.isConstQualified()) {
16736       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
16737       ArgError = true;
16738     }
16739     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
16740     if (MatrixTy &&
16741         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
16742       Diag(PtrExpr->getBeginLoc(),
16743            diag::err_builtin_matrix_pointer_arg_mismatch)
16744           << ElementTy << MatrixTy->getElementType();
16745       ArgError = true;
16746     }
16747   }
16748 
16749   // Apply default Lvalue conversions and convert the stride expression to
16750   // size_t.
16751   {
16752     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16753     if (StrideConv.isInvalid())
16754       return StrideConv;
16755 
16756     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16757     if (StrideConv.isInvalid())
16758       return StrideConv;
16759     StrideExpr = StrideConv.get();
16760     TheCall->setArg(2, StrideExpr);
16761   }
16762 
16763   // Check stride argument.
16764   if (MatrixTy) {
16765     if (Optional<llvm::APSInt> Value =
16766             StrideExpr->getIntegerConstantExpr(Context)) {
16767       uint64_t Stride = Value->getZExtValue();
16768       if (Stride < MatrixTy->getNumRows()) {
16769         Diag(StrideExpr->getBeginLoc(),
16770              diag::err_builtin_matrix_stride_too_small);
16771         ArgError = true;
16772       }
16773     }
16774   }
16775 
16776   if (ArgError)
16777     return ExprError();
16778 
16779   return CallResult;
16780 }
16781 
16782 /// \brief Enforce the bounds of a TCB
16783 /// CheckTCBEnforcement - Enforces that every function in a named TCB only
16784 /// directly calls other functions in the same TCB as marked by the enforce_tcb
16785 /// and enforce_tcb_leaf attributes.
16786 void Sema::CheckTCBEnforcement(const CallExpr *TheCall,
16787                                const FunctionDecl *Callee) {
16788   const FunctionDecl *Caller = getCurFunctionDecl();
16789 
16790   // Calls to builtins are not enforced.
16791   if (!Caller || !Caller->hasAttr<EnforceTCBAttr>() ||
16792       Callee->getBuiltinID() != 0)
16793     return;
16794 
16795   // Search through the enforce_tcb and enforce_tcb_leaf attributes to find
16796   // all TCBs the callee is a part of.
16797   llvm::StringSet<> CalleeTCBs;
16798   for_each(Callee->specific_attrs<EnforceTCBAttr>(),
16799            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16800   for_each(Callee->specific_attrs<EnforceTCBLeafAttr>(),
16801            [&](const auto *A) { CalleeTCBs.insert(A->getTCBName()); });
16802 
16803   // Go through the TCBs the caller is a part of and emit warnings if Caller
16804   // is in a TCB that the Callee is not.
16805   for_each(
16806       Caller->specific_attrs<EnforceTCBAttr>(),
16807       [&](const auto *A) {
16808         StringRef CallerTCB = A->getTCBName();
16809         if (CalleeTCBs.count(CallerTCB) == 0) {
16810           this->Diag(TheCall->getExprLoc(),
16811                      diag::warn_tcb_enforcement_violation) << Callee
16812                                                            << CallerTCB;
16813         }
16814       });
16815 }
16816