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/StringSwitch.h"
79 #include "llvm/ADT/Triple.h"
80 #include "llvm/Support/AtomicOrdering.h"
81 #include "llvm/Support/Casting.h"
82 #include "llvm/Support/Compiler.h"
83 #include "llvm/Support/ConvertUTF.h"
84 #include "llvm/Support/ErrorHandling.h"
85 #include "llvm/Support/Format.h"
86 #include "llvm/Support/Locale.h"
87 #include "llvm/Support/MathExtras.h"
88 #include "llvm/Support/SaveAndRestore.h"
89 #include "llvm/Support/raw_ostream.h"
90 #include <algorithm>
91 #include <bitset>
92 #include <cassert>
93 #include <cstddef>
94 #include <cstdint>
95 #include <functional>
96 #include <limits>
97 #include <string>
98 #include <tuple>
99 #include <utility>
100 
101 using namespace clang;
102 using namespace sema;
103 
104 SourceLocation Sema::getLocationOfStringLiteralByte(const StringLiteral *SL,
105                                                     unsigned ByteNo) const {
106   return SL->getLocationOfByte(ByteNo, getSourceManager(), LangOpts,
107                                Context.getTargetInfo());
108 }
109 
110 /// Checks that a call expression's argument count is the desired number.
111 /// This is useful when doing custom type-checking.  Returns true on error.
112 static bool checkArgCount(Sema &S, CallExpr *call, unsigned desiredArgCount) {
113   unsigned argCount = call->getNumArgs();
114   if (argCount == desiredArgCount) return false;
115 
116   if (argCount < desiredArgCount)
117     return S.Diag(call->getEndLoc(), diag::err_typecheck_call_too_few_args)
118            << 0 /*function call*/ << desiredArgCount << argCount
119            << call->getSourceRange();
120 
121   // Highlight all the excess arguments.
122   SourceRange range(call->getArg(desiredArgCount)->getBeginLoc(),
123                     call->getArg(argCount - 1)->getEndLoc());
124 
125   return S.Diag(range.getBegin(), diag::err_typecheck_call_too_many_args)
126     << 0 /*function call*/ << desiredArgCount << argCount
127     << call->getArg(1)->getSourceRange();
128 }
129 
130 /// Check that the first argument to __builtin_annotation is an integer
131 /// and the second argument is a non-wide string literal.
132 static bool SemaBuiltinAnnotation(Sema &S, CallExpr *TheCall) {
133   if (checkArgCount(S, TheCall, 2))
134     return true;
135 
136   // First argument should be an integer.
137   Expr *ValArg = TheCall->getArg(0);
138   QualType Ty = ValArg->getType();
139   if (!Ty->isIntegerType()) {
140     S.Diag(ValArg->getBeginLoc(), diag::err_builtin_annotation_first_arg)
141         << ValArg->getSourceRange();
142     return true;
143   }
144 
145   // Second argument should be a constant string.
146   Expr *StrArg = TheCall->getArg(1)->IgnoreParenCasts();
147   StringLiteral *Literal = dyn_cast<StringLiteral>(StrArg);
148   if (!Literal || !Literal->isAscii()) {
149     S.Diag(StrArg->getBeginLoc(), diag::err_builtin_annotation_second_arg)
150         << StrArg->getSourceRange();
151     return true;
152   }
153 
154   TheCall->setType(Ty);
155   return false;
156 }
157 
158 static bool SemaBuiltinMSVCAnnotation(Sema &S, CallExpr *TheCall) {
159   // We need at least one argument.
160   if (TheCall->getNumArgs() < 1) {
161     S.Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
162         << 0 << 1 << TheCall->getNumArgs()
163         << TheCall->getCallee()->getSourceRange();
164     return true;
165   }
166 
167   // All arguments should be wide string literals.
168   for (Expr *Arg : TheCall->arguments()) {
169     auto *Literal = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
170     if (!Literal || !Literal->isWide()) {
171       S.Diag(Arg->getBeginLoc(), diag::err_msvc_annotation_wide_str)
172           << Arg->getSourceRange();
173       return true;
174     }
175   }
176 
177   return false;
178 }
179 
180 /// Check that the argument to __builtin_addressof is a glvalue, and set the
181 /// result type to the corresponding pointer type.
182 static bool SemaBuiltinAddressof(Sema &S, CallExpr *TheCall) {
183   if (checkArgCount(S, TheCall, 1))
184     return true;
185 
186   ExprResult Arg(TheCall->getArg(0));
187   QualType ResultType = S.CheckAddressOfOperand(Arg, TheCall->getBeginLoc());
188   if (ResultType.isNull())
189     return true;
190 
191   TheCall->setArg(0, Arg.get());
192   TheCall->setType(ResultType);
193   return false;
194 }
195 
196 /// Check the number of arguments and set the result type to
197 /// the argument type.
198 static bool SemaBuiltinPreserveAI(Sema &S, CallExpr *TheCall) {
199   if (checkArgCount(S, TheCall, 1))
200     return true;
201 
202   TheCall->setType(TheCall->getArg(0)->getType());
203   return false;
204 }
205 
206 /// Check that the value argument for __builtin_is_aligned(value, alignment) and
207 /// __builtin_aligned_{up,down}(value, alignment) is an integer or a pointer
208 /// type (but not a function pointer) and that the alignment is a power-of-two.
209 static bool SemaBuiltinAlignment(Sema &S, CallExpr *TheCall, unsigned ID) {
210   if (checkArgCount(S, TheCall, 2))
211     return true;
212 
213   clang::Expr *Source = TheCall->getArg(0);
214   bool IsBooleanAlignBuiltin = ID == Builtin::BI__builtin_is_aligned;
215 
216   auto IsValidIntegerType = [](QualType Ty) {
217     return Ty->isIntegerType() && !Ty->isEnumeralType() && !Ty->isBooleanType();
218   };
219   QualType SrcTy = Source->getType();
220   // We should also be able to use it with arrays (but not functions!).
221   if (SrcTy->canDecayToPointerType() && SrcTy->isArrayType()) {
222     SrcTy = S.Context.getDecayedType(SrcTy);
223   }
224   if ((!SrcTy->isPointerType() && !IsValidIntegerType(SrcTy)) ||
225       SrcTy->isFunctionPointerType()) {
226     // FIXME: this is not quite the right error message since we don't allow
227     // floating point types, or member pointers.
228     S.Diag(Source->getExprLoc(), diag::err_typecheck_expect_scalar_operand)
229         << SrcTy;
230     return true;
231   }
232 
233   clang::Expr *AlignOp = TheCall->getArg(1);
234   if (!IsValidIntegerType(AlignOp->getType())) {
235     S.Diag(AlignOp->getExprLoc(), diag::err_typecheck_expect_int)
236         << AlignOp->getType();
237     return true;
238   }
239   Expr::EvalResult AlignResult;
240   unsigned MaxAlignmentBits = S.Context.getIntWidth(SrcTy) - 1;
241   // We can't check validity of alignment if it is value dependent.
242   if (!AlignOp->isValueDependent() &&
243       AlignOp->EvaluateAsInt(AlignResult, S.Context,
244                              Expr::SE_AllowSideEffects)) {
245     llvm::APSInt AlignValue = AlignResult.Val.getInt();
246     llvm::APSInt MaxValue(
247         llvm::APInt::getOneBitSet(MaxAlignmentBits + 1, MaxAlignmentBits));
248     if (AlignValue < 1) {
249       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_small) << 1;
250       return true;
251     }
252     if (llvm::APSInt::compareValues(AlignValue, MaxValue) > 0) {
253       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_too_big)
254           << MaxValue.toString(10);
255       return true;
256     }
257     if (!AlignValue.isPowerOf2()) {
258       S.Diag(AlignOp->getExprLoc(), diag::err_alignment_not_power_of_two);
259       return true;
260     }
261     if (AlignValue == 1) {
262       S.Diag(AlignOp->getExprLoc(), diag::warn_alignment_builtin_useless)
263           << IsBooleanAlignBuiltin;
264     }
265   }
266 
267   ExprResult SrcArg = S.PerformCopyInitialization(
268       InitializedEntity::InitializeParameter(S.Context, SrcTy, false),
269       SourceLocation(), Source);
270   if (SrcArg.isInvalid())
271     return true;
272   TheCall->setArg(0, SrcArg.get());
273   ExprResult AlignArg =
274       S.PerformCopyInitialization(InitializedEntity::InitializeParameter(
275                                       S.Context, AlignOp->getType(), false),
276                                   SourceLocation(), AlignOp);
277   if (AlignArg.isInvalid())
278     return true;
279   TheCall->setArg(1, AlignArg.get());
280   // For align_up/align_down, the return type is the same as the (potentially
281   // decayed) argument type including qualifiers. For is_aligned(), the result
282   // is always bool.
283   TheCall->setType(IsBooleanAlignBuiltin ? S.Context.BoolTy : SrcTy);
284   return false;
285 }
286 
287 static bool SemaBuiltinOverflow(Sema &S, CallExpr *TheCall,
288                                 unsigned BuiltinID) {
289   if (checkArgCount(S, TheCall, 3))
290     return true;
291 
292   // First two arguments should be integers.
293   for (unsigned I = 0; I < 2; ++I) {
294     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(I));
295     if (Arg.isInvalid()) return true;
296     TheCall->setArg(I, Arg.get());
297 
298     QualType Ty = Arg.get()->getType();
299     if (!Ty->isIntegerType()) {
300       S.Diag(Arg.get()->getBeginLoc(), diag::err_overflow_builtin_must_be_int)
301           << Ty << Arg.get()->getSourceRange();
302       return true;
303     }
304   }
305 
306   // Third argument should be a pointer to a non-const integer.
307   // IRGen correctly handles volatile, restrict, and address spaces, and
308   // the other qualifiers aren't possible.
309   {
310     ExprResult Arg = S.DefaultFunctionArrayLvalueConversion(TheCall->getArg(2));
311     if (Arg.isInvalid()) return true;
312     TheCall->setArg(2, Arg.get());
313 
314     QualType Ty = Arg.get()->getType();
315     const auto *PtrTy = Ty->getAs<PointerType>();
316     if (!PtrTy ||
317         !PtrTy->getPointeeType()->isIntegerType() ||
318         PtrTy->getPointeeType().isConstQualified()) {
319       S.Diag(Arg.get()->getBeginLoc(),
320              diag::err_overflow_builtin_must_be_ptr_int)
321         << Ty << Arg.get()->getSourceRange();
322       return true;
323     }
324   }
325 
326   // Disallow signed ExtIntType args larger than 128 bits to mul function until
327   // we improve backend support.
328   if (BuiltinID == Builtin::BI__builtin_mul_overflow) {
329     for (unsigned I = 0; I < 3; ++I) {
330       const auto Arg = TheCall->getArg(I);
331       // Third argument will be a pointer.
332       auto Ty = I < 2 ? Arg->getType() : Arg->getType()->getPointeeType();
333       if (Ty->isExtIntType() && Ty->isSignedIntegerType() &&
334           S.getASTContext().getIntWidth(Ty) > 128)
335         return S.Diag(Arg->getBeginLoc(),
336                       diag::err_overflow_builtin_ext_int_max_size)
337                << 128;
338     }
339   }
340 
341   return false;
342 }
343 
344 static bool SemaBuiltinCallWithStaticChain(Sema &S, CallExpr *BuiltinCall) {
345   if (checkArgCount(S, BuiltinCall, 2))
346     return true;
347 
348   SourceLocation BuiltinLoc = BuiltinCall->getBeginLoc();
349   Expr *Builtin = BuiltinCall->getCallee()->IgnoreImpCasts();
350   Expr *Call = BuiltinCall->getArg(0);
351   Expr *Chain = BuiltinCall->getArg(1);
352 
353   if (Call->getStmtClass() != Stmt::CallExprClass) {
354     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_not_call)
355         << Call->getSourceRange();
356     return true;
357   }
358 
359   auto CE = cast<CallExpr>(Call);
360   if (CE->getCallee()->getType()->isBlockPointerType()) {
361     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_block_call)
362         << Call->getSourceRange();
363     return true;
364   }
365 
366   const Decl *TargetDecl = CE->getCalleeDecl();
367   if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl))
368     if (FD->getBuiltinID()) {
369       S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_builtin_call)
370           << Call->getSourceRange();
371       return true;
372     }
373 
374   if (isa<CXXPseudoDestructorExpr>(CE->getCallee()->IgnoreParens())) {
375     S.Diag(BuiltinLoc, diag::err_first_argument_to_cwsc_pdtor_call)
376         << Call->getSourceRange();
377     return true;
378   }
379 
380   ExprResult ChainResult = S.UsualUnaryConversions(Chain);
381   if (ChainResult.isInvalid())
382     return true;
383   if (!ChainResult.get()->getType()->isPointerType()) {
384     S.Diag(BuiltinLoc, diag::err_second_argument_to_cwsc_not_pointer)
385         << Chain->getSourceRange();
386     return true;
387   }
388 
389   QualType ReturnTy = CE->getCallReturnType(S.Context);
390   QualType ArgTys[2] = { ReturnTy, ChainResult.get()->getType() };
391   QualType BuiltinTy = S.Context.getFunctionType(
392       ReturnTy, ArgTys, FunctionProtoType::ExtProtoInfo());
393   QualType BuiltinPtrTy = S.Context.getPointerType(BuiltinTy);
394 
395   Builtin =
396       S.ImpCastExprToType(Builtin, BuiltinPtrTy, CK_BuiltinFnToFnPtr).get();
397 
398   BuiltinCall->setType(CE->getType());
399   BuiltinCall->setValueKind(CE->getValueKind());
400   BuiltinCall->setObjectKind(CE->getObjectKind());
401   BuiltinCall->setCallee(Builtin);
402   BuiltinCall->setArg(1, ChainResult.get());
403 
404   return false;
405 }
406 
407 namespace {
408 
409 class EstimateSizeFormatHandler
410     : public analyze_format_string::FormatStringHandler {
411   size_t Size;
412 
413 public:
414   EstimateSizeFormatHandler(StringRef Format)
415       : Size(std::min(Format.find(0), Format.size()) +
416              1 /* null byte always written by sprintf */) {}
417 
418   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
419                              const char *, unsigned SpecifierLen) override {
420 
421     const size_t FieldWidth = computeFieldWidth(FS);
422     const size_t Precision = computePrecision(FS);
423 
424     // The actual format.
425     switch (FS.getConversionSpecifier().getKind()) {
426     // Just a char.
427     case analyze_format_string::ConversionSpecifier::cArg:
428     case analyze_format_string::ConversionSpecifier::CArg:
429       Size += std::max(FieldWidth, (size_t)1);
430       break;
431     // Just an integer.
432     case analyze_format_string::ConversionSpecifier::dArg:
433     case analyze_format_string::ConversionSpecifier::DArg:
434     case analyze_format_string::ConversionSpecifier::iArg:
435     case analyze_format_string::ConversionSpecifier::oArg:
436     case analyze_format_string::ConversionSpecifier::OArg:
437     case analyze_format_string::ConversionSpecifier::uArg:
438     case analyze_format_string::ConversionSpecifier::UArg:
439     case analyze_format_string::ConversionSpecifier::xArg:
440     case analyze_format_string::ConversionSpecifier::XArg:
441       Size += std::max(FieldWidth, Precision);
442       break;
443 
444     // %g style conversion switches between %f or %e style dynamically.
445     // %f always takes less space, so default to it.
446     case analyze_format_string::ConversionSpecifier::gArg:
447     case analyze_format_string::ConversionSpecifier::GArg:
448 
449     // Floating point number in the form '[+]ddd.ddd'.
450     case analyze_format_string::ConversionSpecifier::fArg:
451     case analyze_format_string::ConversionSpecifier::FArg:
452       Size += std::max(FieldWidth, 1 /* integer part */ +
453                                        (Precision ? 1 + Precision
454                                                   : 0) /* period + decimal */);
455       break;
456 
457     // Floating point number in the form '[-]d.ddde[+-]dd'.
458     case analyze_format_string::ConversionSpecifier::eArg:
459     case analyze_format_string::ConversionSpecifier::EArg:
460       Size +=
461           std::max(FieldWidth,
462                    1 /* integer part */ +
463                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
464                        1 /* e or E letter */ + 2 /* exponent */);
465       break;
466 
467     // Floating point number in the form '[-]0xh.hhhhp±dd'.
468     case analyze_format_string::ConversionSpecifier::aArg:
469     case analyze_format_string::ConversionSpecifier::AArg:
470       Size +=
471           std::max(FieldWidth,
472                    2 /* 0x */ + 1 /* integer part */ +
473                        (Precision ? 1 + Precision : 0) /* period + decimal */ +
474                        1 /* p or P letter */ + 1 /* + or - */ + 1 /* value */);
475       break;
476 
477     // Just a string.
478     case analyze_format_string::ConversionSpecifier::sArg:
479     case analyze_format_string::ConversionSpecifier::SArg:
480       Size += FieldWidth;
481       break;
482 
483     // Just a pointer in the form '0xddd'.
484     case analyze_format_string::ConversionSpecifier::pArg:
485       Size += std::max(FieldWidth, 2 /* leading 0x */ + Precision);
486       break;
487 
488     // A plain percent.
489     case analyze_format_string::ConversionSpecifier::PercentArg:
490       Size += 1;
491       break;
492 
493     default:
494       break;
495     }
496 
497     Size += FS.hasPlusPrefix() || FS.hasSpacePrefix();
498 
499     if (FS.hasAlternativeForm()) {
500       switch (FS.getConversionSpecifier().getKind()) {
501       default:
502         break;
503       // Force a leading '0'.
504       case analyze_format_string::ConversionSpecifier::oArg:
505         Size += 1;
506         break;
507       // Force a leading '0x'.
508       case analyze_format_string::ConversionSpecifier::xArg:
509       case analyze_format_string::ConversionSpecifier::XArg:
510         Size += 2;
511         break;
512       // Force a period '.' before decimal, even if precision is 0.
513       case analyze_format_string::ConversionSpecifier::aArg:
514       case analyze_format_string::ConversionSpecifier::AArg:
515       case analyze_format_string::ConversionSpecifier::eArg:
516       case analyze_format_string::ConversionSpecifier::EArg:
517       case analyze_format_string::ConversionSpecifier::fArg:
518       case analyze_format_string::ConversionSpecifier::FArg:
519       case analyze_format_string::ConversionSpecifier::gArg:
520       case analyze_format_string::ConversionSpecifier::GArg:
521         Size += (Precision ? 0 : 1);
522         break;
523       }
524     }
525     assert(SpecifierLen <= Size && "no underflow");
526     Size -= SpecifierLen;
527     return true;
528   }
529 
530   size_t getSizeLowerBound() const { return Size; }
531 
532 private:
533   static size_t computeFieldWidth(const analyze_printf::PrintfSpecifier &FS) {
534     const analyze_format_string::OptionalAmount &FW = FS.getFieldWidth();
535     size_t FieldWidth = 0;
536     if (FW.getHowSpecified() == analyze_format_string::OptionalAmount::Constant)
537       FieldWidth = FW.getConstantAmount();
538     return FieldWidth;
539   }
540 
541   static size_t computePrecision(const analyze_printf::PrintfSpecifier &FS) {
542     const analyze_format_string::OptionalAmount &FW = FS.getPrecision();
543     size_t Precision = 0;
544 
545     // See man 3 printf for default precision value based on the specifier.
546     switch (FW.getHowSpecified()) {
547     case analyze_format_string::OptionalAmount::NotSpecified:
548       switch (FS.getConversionSpecifier().getKind()) {
549       default:
550         break;
551       case analyze_format_string::ConversionSpecifier::dArg: // %d
552       case analyze_format_string::ConversionSpecifier::DArg: // %D
553       case analyze_format_string::ConversionSpecifier::iArg: // %i
554         Precision = 1;
555         break;
556       case analyze_format_string::ConversionSpecifier::oArg: // %d
557       case analyze_format_string::ConversionSpecifier::OArg: // %D
558       case analyze_format_string::ConversionSpecifier::uArg: // %d
559       case analyze_format_string::ConversionSpecifier::UArg: // %D
560       case analyze_format_string::ConversionSpecifier::xArg: // %d
561       case analyze_format_string::ConversionSpecifier::XArg: // %D
562         Precision = 1;
563         break;
564       case analyze_format_string::ConversionSpecifier::fArg: // %f
565       case analyze_format_string::ConversionSpecifier::FArg: // %F
566       case analyze_format_string::ConversionSpecifier::eArg: // %e
567       case analyze_format_string::ConversionSpecifier::EArg: // %E
568       case analyze_format_string::ConversionSpecifier::gArg: // %g
569       case analyze_format_string::ConversionSpecifier::GArg: // %G
570         Precision = 6;
571         break;
572       case analyze_format_string::ConversionSpecifier::pArg: // %d
573         Precision = 1;
574         break;
575       }
576       break;
577     case analyze_format_string::OptionalAmount::Constant:
578       Precision = FW.getConstantAmount();
579       break;
580     default:
581       break;
582     }
583     return Precision;
584   }
585 };
586 
587 } // namespace
588 
589 /// Check a call to BuiltinID for buffer overflows. If BuiltinID is a
590 /// __builtin_*_chk function, then use the object size argument specified in the
591 /// source. Otherwise, infer the object size using __builtin_object_size.
592 void Sema::checkFortifiedBuiltinMemoryFunction(FunctionDecl *FD,
593                                                CallExpr *TheCall) {
594   // FIXME: There are some more useful checks we could be doing here:
595   //  - Evaluate strlen of strcpy arguments, use as object size.
596 
597   if (TheCall->isValueDependent() || TheCall->isTypeDependent() ||
598       isConstantEvaluated())
599     return;
600 
601   unsigned BuiltinID = FD->getBuiltinID(/*ConsiderWrappers=*/true);
602   if (!BuiltinID)
603     return;
604 
605   const TargetInfo &TI = getASTContext().getTargetInfo();
606   unsigned SizeTypeWidth = TI.getTypeWidth(TI.getSizeType());
607 
608   unsigned DiagID = 0;
609   bool IsChkVariant = false;
610   Optional<llvm::APSInt> UsedSize;
611   unsigned SizeIndex, ObjectIndex;
612   switch (BuiltinID) {
613   default:
614     return;
615   case Builtin::BIsprintf:
616   case Builtin::BI__builtin___sprintf_chk: {
617     size_t FormatIndex = BuiltinID == Builtin::BIsprintf ? 1 : 3;
618     auto *FormatExpr = TheCall->getArg(FormatIndex)->IgnoreParenImpCasts();
619 
620     if (auto *Format = dyn_cast<StringLiteral>(FormatExpr)) {
621 
622       if (!Format->isAscii() && !Format->isUTF8())
623         return;
624 
625       StringRef FormatStrRef = Format->getString();
626       EstimateSizeFormatHandler H(FormatStrRef);
627       const char *FormatBytes = FormatStrRef.data();
628       const ConstantArrayType *T =
629           Context.getAsConstantArrayType(Format->getType());
630       assert(T && "String literal not of constant array type!");
631       size_t TypeSize = T->getSize().getZExtValue();
632 
633       // In case there's a null byte somewhere.
634       size_t StrLen =
635           std::min(std::max(TypeSize, size_t(1)) - 1, FormatStrRef.find(0));
636       if (!analyze_format_string::ParsePrintfString(
637               H, FormatBytes, FormatBytes + StrLen, getLangOpts(),
638               Context.getTargetInfo(), false)) {
639         DiagID = diag::warn_fortify_source_format_overflow;
640         UsedSize = llvm::APSInt::getUnsigned(H.getSizeLowerBound())
641                        .extOrTrunc(SizeTypeWidth);
642         if (BuiltinID == Builtin::BI__builtin___sprintf_chk) {
643           IsChkVariant = true;
644           ObjectIndex = 2;
645         } else {
646           IsChkVariant = false;
647           ObjectIndex = 0;
648         }
649         break;
650       }
651     }
652     return;
653   }
654   case Builtin::BI__builtin___memcpy_chk:
655   case Builtin::BI__builtin___memmove_chk:
656   case Builtin::BI__builtin___memset_chk:
657   case Builtin::BI__builtin___strlcat_chk:
658   case Builtin::BI__builtin___strlcpy_chk:
659   case Builtin::BI__builtin___strncat_chk:
660   case Builtin::BI__builtin___strncpy_chk:
661   case Builtin::BI__builtin___stpncpy_chk:
662   case Builtin::BI__builtin___memccpy_chk:
663   case Builtin::BI__builtin___mempcpy_chk: {
664     DiagID = diag::warn_builtin_chk_overflow;
665     IsChkVariant = true;
666     SizeIndex = TheCall->getNumArgs() - 2;
667     ObjectIndex = TheCall->getNumArgs() - 1;
668     break;
669   }
670 
671   case Builtin::BI__builtin___snprintf_chk:
672   case Builtin::BI__builtin___vsnprintf_chk: {
673     DiagID = diag::warn_builtin_chk_overflow;
674     IsChkVariant = true;
675     SizeIndex = 1;
676     ObjectIndex = 3;
677     break;
678   }
679 
680   case Builtin::BIstrncat:
681   case Builtin::BI__builtin_strncat:
682   case Builtin::BIstrncpy:
683   case Builtin::BI__builtin_strncpy:
684   case Builtin::BIstpncpy:
685   case Builtin::BI__builtin_stpncpy: {
686     // Whether these functions overflow depends on the runtime strlen of the
687     // string, not just the buffer size, so emitting the "always overflow"
688     // diagnostic isn't quite right. We should still diagnose passing a buffer
689     // size larger than the destination buffer though; this is a runtime abort
690     // in _FORTIFY_SOURCE mode, and is quite suspicious otherwise.
691     DiagID = diag::warn_fortify_source_size_mismatch;
692     SizeIndex = TheCall->getNumArgs() - 1;
693     ObjectIndex = 0;
694     break;
695   }
696 
697   case Builtin::BImemcpy:
698   case Builtin::BI__builtin_memcpy:
699   case Builtin::BImemmove:
700   case Builtin::BI__builtin_memmove:
701   case Builtin::BImemset:
702   case Builtin::BI__builtin_memset:
703   case Builtin::BImempcpy:
704   case Builtin::BI__builtin_mempcpy: {
705     DiagID = diag::warn_fortify_source_overflow;
706     SizeIndex = TheCall->getNumArgs() - 1;
707     ObjectIndex = 0;
708     break;
709   }
710   case Builtin::BIsnprintf:
711   case Builtin::BI__builtin_snprintf:
712   case Builtin::BIvsnprintf:
713   case Builtin::BI__builtin_vsnprintf: {
714     DiagID = diag::warn_fortify_source_size_mismatch;
715     SizeIndex = 1;
716     ObjectIndex = 0;
717     break;
718   }
719   }
720 
721   llvm::APSInt ObjectSize;
722   // For __builtin___*_chk, the object size is explicitly provided by the caller
723   // (usually using __builtin_object_size). Use that value to check this call.
724   if (IsChkVariant) {
725     Expr::EvalResult Result;
726     Expr *SizeArg = TheCall->getArg(ObjectIndex);
727     if (!SizeArg->EvaluateAsInt(Result, getASTContext()))
728       return;
729     ObjectSize = Result.Val.getInt();
730 
731   // Otherwise, try to evaluate an imaginary call to __builtin_object_size.
732   } else {
733     // If the parameter has a pass_object_size attribute, then we should use its
734     // (potentially) more strict checking mode. Otherwise, conservatively assume
735     // type 0.
736     int BOSType = 0;
737     if (const auto *POS =
738             FD->getParamDecl(ObjectIndex)->getAttr<PassObjectSizeAttr>())
739       BOSType = POS->getType();
740 
741     Expr *ObjArg = TheCall->getArg(ObjectIndex);
742     uint64_t Result;
743     if (!ObjArg->tryEvaluateObjectSize(Result, getASTContext(), BOSType))
744       return;
745     // Get the object size in the target's size_t width.
746     ObjectSize = llvm::APSInt::getUnsigned(Result).extOrTrunc(SizeTypeWidth);
747   }
748 
749   // Evaluate the number of bytes of the object that this call will use.
750   if (!UsedSize) {
751     Expr::EvalResult Result;
752     Expr *UsedSizeArg = TheCall->getArg(SizeIndex);
753     if (!UsedSizeArg->EvaluateAsInt(Result, getASTContext()))
754       return;
755     UsedSize = Result.Val.getInt().extOrTrunc(SizeTypeWidth);
756   }
757 
758   if (UsedSize.getValue().ule(ObjectSize))
759     return;
760 
761   StringRef FunctionName = getASTContext().BuiltinInfo.getName(BuiltinID);
762   // Skim off the details of whichever builtin was called to produce a better
763   // diagnostic, as it's unlikley that the user wrote the __builtin explicitly.
764   if (IsChkVariant) {
765     FunctionName = FunctionName.drop_front(std::strlen("__builtin___"));
766     FunctionName = FunctionName.drop_back(std::strlen("_chk"));
767   } else if (FunctionName.startswith("__builtin_")) {
768     FunctionName = FunctionName.drop_front(std::strlen("__builtin_"));
769   }
770 
771   DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
772                       PDiag(DiagID)
773                           << FunctionName << ObjectSize.toString(/*Radix=*/10)
774                           << UsedSize.getValue().toString(/*Radix=*/10));
775 }
776 
777 static bool SemaBuiltinSEHScopeCheck(Sema &SemaRef, CallExpr *TheCall,
778                                      Scope::ScopeFlags NeededScopeFlags,
779                                      unsigned DiagID) {
780   // Scopes aren't available during instantiation. Fortunately, builtin
781   // functions cannot be template args so they cannot be formed through template
782   // instantiation. Therefore checking once during the parse is sufficient.
783   if (SemaRef.inTemplateInstantiation())
784     return false;
785 
786   Scope *S = SemaRef.getCurScope();
787   while (S && !S->isSEHExceptScope())
788     S = S->getParent();
789   if (!S || !(S->getFlags() & NeededScopeFlags)) {
790     auto *DRE = cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
791     SemaRef.Diag(TheCall->getExprLoc(), DiagID)
792         << DRE->getDecl()->getIdentifier();
793     return true;
794   }
795 
796   return false;
797 }
798 
799 static inline bool isBlockPointer(Expr *Arg) {
800   return Arg->getType()->isBlockPointerType();
801 }
802 
803 /// OpenCL C v2.0, s6.13.17.2 - Checks that the block parameters are all local
804 /// void*, which is a requirement of device side enqueue.
805 static bool checkOpenCLBlockArgs(Sema &S, Expr *BlockArg) {
806   const BlockPointerType *BPT =
807       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
808   ArrayRef<QualType> Params =
809       BPT->getPointeeType()->castAs<FunctionProtoType>()->getParamTypes();
810   unsigned ArgCounter = 0;
811   bool IllegalParams = false;
812   // Iterate through the block parameters until either one is found that is not
813   // a local void*, or the block is valid.
814   for (ArrayRef<QualType>::iterator I = Params.begin(), E = Params.end();
815        I != E; ++I, ++ArgCounter) {
816     if (!(*I)->isPointerType() || !(*I)->getPointeeType()->isVoidType() ||
817         (*I)->getPointeeType().getQualifiers().getAddressSpace() !=
818             LangAS::opencl_local) {
819       // Get the location of the error. If a block literal has been passed
820       // (BlockExpr) then we can point straight to the offending argument,
821       // else we just point to the variable reference.
822       SourceLocation ErrorLoc;
823       if (isa<BlockExpr>(BlockArg)) {
824         BlockDecl *BD = cast<BlockExpr>(BlockArg)->getBlockDecl();
825         ErrorLoc = BD->getParamDecl(ArgCounter)->getBeginLoc();
826       } else if (isa<DeclRefExpr>(BlockArg)) {
827         ErrorLoc = cast<DeclRefExpr>(BlockArg)->getBeginLoc();
828       }
829       S.Diag(ErrorLoc,
830              diag::err_opencl_enqueue_kernel_blocks_non_local_void_args);
831       IllegalParams = true;
832     }
833   }
834 
835   return IllegalParams;
836 }
837 
838 static bool checkOpenCLSubgroupExt(Sema &S, CallExpr *Call) {
839   if (!S.getOpenCLOptions().isEnabled("cl_khr_subgroups")) {
840     S.Diag(Call->getBeginLoc(), diag::err_opencl_requires_extension)
841         << 1 << Call->getDirectCallee() << "cl_khr_subgroups";
842     return true;
843   }
844   return false;
845 }
846 
847 static bool SemaOpenCLBuiltinNDRangeAndBlock(Sema &S, CallExpr *TheCall) {
848   if (checkArgCount(S, TheCall, 2))
849     return true;
850 
851   if (checkOpenCLSubgroupExt(S, TheCall))
852     return true;
853 
854   // First argument is an ndrange_t type.
855   Expr *NDRangeArg = TheCall->getArg(0);
856   if (NDRangeArg->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
857     S.Diag(NDRangeArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
858         << TheCall->getDirectCallee() << "'ndrange_t'";
859     return true;
860   }
861 
862   Expr *BlockArg = TheCall->getArg(1);
863   if (!isBlockPointer(BlockArg)) {
864     S.Diag(BlockArg->getBeginLoc(), diag::err_opencl_builtin_expected_type)
865         << TheCall->getDirectCallee() << "block";
866     return true;
867   }
868   return checkOpenCLBlockArgs(S, BlockArg);
869 }
870 
871 /// OpenCL C v2.0, s6.13.17.6 - Check the argument to the
872 /// get_kernel_work_group_size
873 /// and get_kernel_preferred_work_group_size_multiple builtin functions.
874 static bool SemaOpenCLBuiltinKernelWorkGroupSize(Sema &S, CallExpr *TheCall) {
875   if (checkArgCount(S, TheCall, 1))
876     return true;
877 
878   Expr *BlockArg = TheCall->getArg(0);
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 /// Diagnose integer type and any valid implicit conversion to it.
888 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E,
889                                       const QualType &IntType);
890 
891 static bool checkOpenCLEnqueueLocalSizeArgs(Sema &S, CallExpr *TheCall,
892                                             unsigned Start, unsigned End) {
893   bool IllegalParams = false;
894   for (unsigned I = Start; I <= End; ++I)
895     IllegalParams |= checkOpenCLEnqueueIntType(S, TheCall->getArg(I),
896                                               S.Context.getSizeType());
897   return IllegalParams;
898 }
899 
900 /// OpenCL v2.0, s6.13.17.1 - Check that sizes are provided for all
901 /// 'local void*' parameter of passed block.
902 static bool checkOpenCLEnqueueVariadicArgs(Sema &S, CallExpr *TheCall,
903                                            Expr *BlockArg,
904                                            unsigned NumNonVarArgs) {
905   const BlockPointerType *BPT =
906       cast<BlockPointerType>(BlockArg->getType().getCanonicalType());
907   unsigned NumBlockParams =
908       BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams();
909   unsigned TotalNumArgs = TheCall->getNumArgs();
910 
911   // For each argument passed to the block, a corresponding uint needs to
912   // be passed to describe the size of the local memory.
913   if (TotalNumArgs != NumBlockParams + NumNonVarArgs) {
914     S.Diag(TheCall->getBeginLoc(),
915            diag::err_opencl_enqueue_kernel_local_size_args);
916     return true;
917   }
918 
919   // Check that the sizes of the local memory are specified by integers.
920   return checkOpenCLEnqueueLocalSizeArgs(S, TheCall, NumNonVarArgs,
921                                          TotalNumArgs - 1);
922 }
923 
924 /// OpenCL C v2.0, s6.13.17 - Enqueue kernel function contains four different
925 /// overload formats specified in Table 6.13.17.1.
926 /// int enqueue_kernel(queue_t queue,
927 ///                    kernel_enqueue_flags_t flags,
928 ///                    const ndrange_t ndrange,
929 ///                    void (^block)(void))
930 /// int enqueue_kernel(queue_t queue,
931 ///                    kernel_enqueue_flags_t flags,
932 ///                    const ndrange_t ndrange,
933 ///                    uint num_events_in_wait_list,
934 ///                    clk_event_t *event_wait_list,
935 ///                    clk_event_t *event_ret,
936 ///                    void (^block)(void))
937 /// int enqueue_kernel(queue_t queue,
938 ///                    kernel_enqueue_flags_t flags,
939 ///                    const ndrange_t ndrange,
940 ///                    void (^block)(local void*, ...),
941 ///                    uint size0, ...)
942 /// int enqueue_kernel(queue_t queue,
943 ///                    kernel_enqueue_flags_t flags,
944 ///                    const ndrange_t ndrange,
945 ///                    uint num_events_in_wait_list,
946 ///                    clk_event_t *event_wait_list,
947 ///                    clk_event_t *event_ret,
948 ///                    void (^block)(local void*, ...),
949 ///                    uint size0, ...)
950 static bool SemaOpenCLBuiltinEnqueueKernel(Sema &S, CallExpr *TheCall) {
951   unsigned NumArgs = TheCall->getNumArgs();
952 
953   if (NumArgs < 4) {
954     S.Diag(TheCall->getBeginLoc(),
955            diag::err_typecheck_call_too_few_args_at_least)
956         << 0 << 4 << NumArgs;
957     return true;
958   }
959 
960   Expr *Arg0 = TheCall->getArg(0);
961   Expr *Arg1 = TheCall->getArg(1);
962   Expr *Arg2 = TheCall->getArg(2);
963   Expr *Arg3 = TheCall->getArg(3);
964 
965   // First argument always needs to be a queue_t type.
966   if (!Arg0->getType()->isQueueT()) {
967     S.Diag(TheCall->getArg(0)->getBeginLoc(),
968            diag::err_opencl_builtin_expected_type)
969         << TheCall->getDirectCallee() << S.Context.OCLQueueTy;
970     return true;
971   }
972 
973   // Second argument always needs to be a kernel_enqueue_flags_t enum value.
974   if (!Arg1->getType()->isIntegerType()) {
975     S.Diag(TheCall->getArg(1)->getBeginLoc(),
976            diag::err_opencl_builtin_expected_type)
977         << TheCall->getDirectCallee() << "'kernel_enqueue_flags_t' (i.e. uint)";
978     return true;
979   }
980 
981   // Third argument is always an ndrange_t type.
982   if (Arg2->getType().getUnqualifiedType().getAsString() != "ndrange_t") {
983     S.Diag(TheCall->getArg(2)->getBeginLoc(),
984            diag::err_opencl_builtin_expected_type)
985         << TheCall->getDirectCallee() << "'ndrange_t'";
986     return true;
987   }
988 
989   // With four arguments, there is only one form that the function could be
990   // called in: no events and no variable arguments.
991   if (NumArgs == 4) {
992     // check that the last argument is the right block type.
993     if (!isBlockPointer(Arg3)) {
994       S.Diag(Arg3->getBeginLoc(), diag::err_opencl_builtin_expected_type)
995           << TheCall->getDirectCallee() << "block";
996       return true;
997     }
998     // we have a block type, check the prototype
999     const BlockPointerType *BPT =
1000         cast<BlockPointerType>(Arg3->getType().getCanonicalType());
1001     if (BPT->getPointeeType()->castAs<FunctionProtoType>()->getNumParams() > 0) {
1002       S.Diag(Arg3->getBeginLoc(),
1003              diag::err_opencl_enqueue_kernel_blocks_no_args);
1004       return true;
1005     }
1006     return false;
1007   }
1008   // we can have block + varargs.
1009   if (isBlockPointer(Arg3))
1010     return (checkOpenCLBlockArgs(S, Arg3) ||
1011             checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg3, 4));
1012   // last two cases with either exactly 7 args or 7 args and varargs.
1013   if (NumArgs >= 7) {
1014     // check common block argument.
1015     Expr *Arg6 = TheCall->getArg(6);
1016     if (!isBlockPointer(Arg6)) {
1017       S.Diag(Arg6->getBeginLoc(), diag::err_opencl_builtin_expected_type)
1018           << TheCall->getDirectCallee() << "block";
1019       return true;
1020     }
1021     if (checkOpenCLBlockArgs(S, Arg6))
1022       return true;
1023 
1024     // Forth argument has to be any integer type.
1025     if (!Arg3->getType()->isIntegerType()) {
1026       S.Diag(TheCall->getArg(3)->getBeginLoc(),
1027              diag::err_opencl_builtin_expected_type)
1028           << TheCall->getDirectCallee() << "integer";
1029       return true;
1030     }
1031     // check remaining common arguments.
1032     Expr *Arg4 = TheCall->getArg(4);
1033     Expr *Arg5 = TheCall->getArg(5);
1034 
1035     // Fifth argument is always passed as a pointer to clk_event_t.
1036     if (!Arg4->isNullPointerConstant(S.Context,
1037                                      Expr::NPC_ValueDependentIsNotNull) &&
1038         !Arg4->getType()->getPointeeOrArrayElementType()->isClkEventT()) {
1039       S.Diag(TheCall->getArg(4)->getBeginLoc(),
1040              diag::err_opencl_builtin_expected_type)
1041           << TheCall->getDirectCallee()
1042           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1043       return true;
1044     }
1045 
1046     // Sixth argument is always passed as a pointer to clk_event_t.
1047     if (!Arg5->isNullPointerConstant(S.Context,
1048                                      Expr::NPC_ValueDependentIsNotNull) &&
1049         !(Arg5->getType()->isPointerType() &&
1050           Arg5->getType()->getPointeeType()->isClkEventT())) {
1051       S.Diag(TheCall->getArg(5)->getBeginLoc(),
1052              diag::err_opencl_builtin_expected_type)
1053           << TheCall->getDirectCallee()
1054           << S.Context.getPointerType(S.Context.OCLClkEventTy);
1055       return true;
1056     }
1057 
1058     if (NumArgs == 7)
1059       return false;
1060 
1061     return checkOpenCLEnqueueVariadicArgs(S, TheCall, Arg6, 7);
1062   }
1063 
1064   // None of the specific case has been detected, give generic error
1065   S.Diag(TheCall->getBeginLoc(),
1066          diag::err_opencl_enqueue_kernel_incorrect_args);
1067   return true;
1068 }
1069 
1070 /// Returns OpenCL access qual.
1071 static OpenCLAccessAttr *getOpenCLArgAccess(const Decl *D) {
1072     return D->getAttr<OpenCLAccessAttr>();
1073 }
1074 
1075 /// Returns true if pipe element type is different from the pointer.
1076 static bool checkOpenCLPipeArg(Sema &S, CallExpr *Call) {
1077   const Expr *Arg0 = Call->getArg(0);
1078   // First argument type should always be pipe.
1079   if (!Arg0->getType()->isPipeType()) {
1080     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1081         << Call->getDirectCallee() << Arg0->getSourceRange();
1082     return true;
1083   }
1084   OpenCLAccessAttr *AccessQual =
1085       getOpenCLArgAccess(cast<DeclRefExpr>(Arg0)->getDecl());
1086   // Validates the access qualifier is compatible with the call.
1087   // OpenCL v2.0 s6.13.16 - The access qualifiers for pipe should only be
1088   // read_only and write_only, and assumed to be read_only if no qualifier is
1089   // specified.
1090   switch (Call->getDirectCallee()->getBuiltinID()) {
1091   case Builtin::BIread_pipe:
1092   case Builtin::BIreserve_read_pipe:
1093   case Builtin::BIcommit_read_pipe:
1094   case Builtin::BIwork_group_reserve_read_pipe:
1095   case Builtin::BIsub_group_reserve_read_pipe:
1096   case Builtin::BIwork_group_commit_read_pipe:
1097   case Builtin::BIsub_group_commit_read_pipe:
1098     if (!(!AccessQual || AccessQual->isReadOnly())) {
1099       S.Diag(Arg0->getBeginLoc(),
1100              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1101           << "read_only" << Arg0->getSourceRange();
1102       return true;
1103     }
1104     break;
1105   case Builtin::BIwrite_pipe:
1106   case Builtin::BIreserve_write_pipe:
1107   case Builtin::BIcommit_write_pipe:
1108   case Builtin::BIwork_group_reserve_write_pipe:
1109   case Builtin::BIsub_group_reserve_write_pipe:
1110   case Builtin::BIwork_group_commit_write_pipe:
1111   case Builtin::BIsub_group_commit_write_pipe:
1112     if (!(AccessQual && AccessQual->isWriteOnly())) {
1113       S.Diag(Arg0->getBeginLoc(),
1114              diag::err_opencl_builtin_pipe_invalid_access_modifier)
1115           << "write_only" << Arg0->getSourceRange();
1116       return true;
1117     }
1118     break;
1119   default:
1120     break;
1121   }
1122   return false;
1123 }
1124 
1125 /// Returns true if pipe element type is different from the pointer.
1126 static bool checkOpenCLPipePacketType(Sema &S, CallExpr *Call, unsigned Idx) {
1127   const Expr *Arg0 = Call->getArg(0);
1128   const Expr *ArgIdx = Call->getArg(Idx);
1129   const PipeType *PipeTy = cast<PipeType>(Arg0->getType());
1130   const QualType EltTy = PipeTy->getElementType();
1131   const PointerType *ArgTy = ArgIdx->getType()->getAs<PointerType>();
1132   // The Idx argument should be a pointer and the type of the pointer and
1133   // the type of pipe element should also be the same.
1134   if (!ArgTy ||
1135       !S.Context.hasSameType(
1136           EltTy, ArgTy->getPointeeType()->getCanonicalTypeInternal())) {
1137     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1138         << Call->getDirectCallee() << S.Context.getPointerType(EltTy)
1139         << ArgIdx->getType() << ArgIdx->getSourceRange();
1140     return true;
1141   }
1142   return false;
1143 }
1144 
1145 // Performs semantic analysis for the read/write_pipe call.
1146 // \param S Reference to the semantic analyzer.
1147 // \param Call A pointer to the builtin call.
1148 // \return True if a semantic error has been found, false otherwise.
1149 static bool SemaBuiltinRWPipe(Sema &S, CallExpr *Call) {
1150   // OpenCL v2.0 s6.13.16.2 - The built-in read/write
1151   // functions have two forms.
1152   switch (Call->getNumArgs()) {
1153   case 2:
1154     if (checkOpenCLPipeArg(S, Call))
1155       return true;
1156     // The call with 2 arguments should be
1157     // read/write_pipe(pipe T, T*).
1158     // Check packet type T.
1159     if (checkOpenCLPipePacketType(S, Call, 1))
1160       return true;
1161     break;
1162 
1163   case 4: {
1164     if (checkOpenCLPipeArg(S, Call))
1165       return true;
1166     // The call with 4 arguments should be
1167     // read/write_pipe(pipe T, reserve_id_t, uint, T*).
1168     // Check reserve_id_t.
1169     if (!Call->getArg(1)->getType()->isReserveIDT()) {
1170       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1171           << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1172           << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1173       return true;
1174     }
1175 
1176     // Check the index.
1177     const Expr *Arg2 = Call->getArg(2);
1178     if (!Arg2->getType()->isIntegerType() &&
1179         !Arg2->getType()->isUnsignedIntegerType()) {
1180       S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1181           << Call->getDirectCallee() << S.Context.UnsignedIntTy
1182           << Arg2->getType() << Arg2->getSourceRange();
1183       return true;
1184     }
1185 
1186     // Check packet type T.
1187     if (checkOpenCLPipePacketType(S, Call, 3))
1188       return true;
1189   } break;
1190   default:
1191     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_arg_num)
1192         << Call->getDirectCallee() << Call->getSourceRange();
1193     return true;
1194   }
1195 
1196   return false;
1197 }
1198 
1199 // Performs a semantic analysis on the {work_group_/sub_group_
1200 //        /_}reserve_{read/write}_pipe
1201 // \param S Reference to the semantic analyzer.
1202 // \param Call The call to the builtin function to be analyzed.
1203 // \return True if a semantic error was found, false otherwise.
1204 static bool SemaBuiltinReserveRWPipe(Sema &S, CallExpr *Call) {
1205   if (checkArgCount(S, Call, 2))
1206     return true;
1207 
1208   if (checkOpenCLPipeArg(S, Call))
1209     return true;
1210 
1211   // Check the reserve size.
1212   if (!Call->getArg(1)->getType()->isIntegerType() &&
1213       !Call->getArg(1)->getType()->isUnsignedIntegerType()) {
1214     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1215         << Call->getDirectCallee() << S.Context.UnsignedIntTy
1216         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1217     return true;
1218   }
1219 
1220   // Since return type of reserve_read/write_pipe built-in function is
1221   // reserve_id_t, which is not defined in the builtin def file , we used int
1222   // as return type and need to override the return type of these functions.
1223   Call->setType(S.Context.OCLReserveIDTy);
1224 
1225   return false;
1226 }
1227 
1228 // Performs a semantic analysis on {work_group_/sub_group_
1229 //        /_}commit_{read/write}_pipe
1230 // \param S Reference to the semantic analyzer.
1231 // \param Call The call to the builtin function to be analyzed.
1232 // \return True if a semantic error was found, false otherwise.
1233 static bool SemaBuiltinCommitRWPipe(Sema &S, CallExpr *Call) {
1234   if (checkArgCount(S, Call, 2))
1235     return true;
1236 
1237   if (checkOpenCLPipeArg(S, Call))
1238     return true;
1239 
1240   // Check reserve_id_t.
1241   if (!Call->getArg(1)->getType()->isReserveIDT()) {
1242     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_invalid_arg)
1243         << Call->getDirectCallee() << S.Context.OCLReserveIDTy
1244         << Call->getArg(1)->getType() << Call->getArg(1)->getSourceRange();
1245     return true;
1246   }
1247 
1248   return false;
1249 }
1250 
1251 // Performs a semantic analysis on the call to built-in Pipe
1252 //        Query Functions.
1253 // \param S Reference to the semantic analyzer.
1254 // \param Call The call to the builtin function to be analyzed.
1255 // \return True if a semantic error was found, false otherwise.
1256 static bool SemaBuiltinPipePackets(Sema &S, CallExpr *Call) {
1257   if (checkArgCount(S, Call, 1))
1258     return true;
1259 
1260   if (!Call->getArg(0)->getType()->isPipeType()) {
1261     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_pipe_first_arg)
1262         << Call->getDirectCallee() << Call->getArg(0)->getSourceRange();
1263     return true;
1264   }
1265 
1266   return false;
1267 }
1268 
1269 // OpenCL v2.0 s6.13.9 - Address space qualifier functions.
1270 // Performs semantic analysis for the to_global/local/private call.
1271 // \param S Reference to the semantic analyzer.
1272 // \param BuiltinID ID of the builtin function.
1273 // \param Call A pointer to the builtin call.
1274 // \return True if a semantic error has been found, false otherwise.
1275 static bool SemaOpenCLBuiltinToAddr(Sema &S, unsigned BuiltinID,
1276                                     CallExpr *Call) {
1277   if (checkArgCount(S, Call, 1))
1278     return true;
1279 
1280   auto RT = Call->getArg(0)->getType();
1281   if (!RT->isPointerType() || RT->getPointeeType()
1282       .getAddressSpace() == LangAS::opencl_constant) {
1283     S.Diag(Call->getBeginLoc(), diag::err_opencl_builtin_to_addr_invalid_arg)
1284         << Call->getArg(0) << Call->getDirectCallee() << Call->getSourceRange();
1285     return true;
1286   }
1287 
1288   if (RT->getPointeeType().getAddressSpace() != LangAS::opencl_generic) {
1289     S.Diag(Call->getArg(0)->getBeginLoc(),
1290            diag::warn_opencl_generic_address_space_arg)
1291         << Call->getDirectCallee()->getNameInfo().getAsString()
1292         << Call->getArg(0)->getSourceRange();
1293   }
1294 
1295   RT = RT->getPointeeType();
1296   auto Qual = RT.getQualifiers();
1297   switch (BuiltinID) {
1298   case Builtin::BIto_global:
1299     Qual.setAddressSpace(LangAS::opencl_global);
1300     break;
1301   case Builtin::BIto_local:
1302     Qual.setAddressSpace(LangAS::opencl_local);
1303     break;
1304   case Builtin::BIto_private:
1305     Qual.setAddressSpace(LangAS::opencl_private);
1306     break;
1307   default:
1308     llvm_unreachable("Invalid builtin function");
1309   }
1310   Call->setType(S.Context.getPointerType(S.Context.getQualifiedType(
1311       RT.getUnqualifiedType(), Qual)));
1312 
1313   return false;
1314 }
1315 
1316 static ExprResult SemaBuiltinLaunder(Sema &S, CallExpr *TheCall) {
1317   if (checkArgCount(S, TheCall, 1))
1318     return ExprError();
1319 
1320   // Compute __builtin_launder's parameter type from the argument.
1321   // The parameter type is:
1322   //  * The type of the argument if it's not an array or function type,
1323   //  Otherwise,
1324   //  * The decayed argument type.
1325   QualType ParamTy = [&]() {
1326     QualType ArgTy = TheCall->getArg(0)->getType();
1327     if (const ArrayType *Ty = ArgTy->getAsArrayTypeUnsafe())
1328       return S.Context.getPointerType(Ty->getElementType());
1329     if (ArgTy->isFunctionType()) {
1330       return S.Context.getPointerType(ArgTy);
1331     }
1332     return ArgTy;
1333   }();
1334 
1335   TheCall->setType(ParamTy);
1336 
1337   auto DiagSelect = [&]() -> llvm::Optional<unsigned> {
1338     if (!ParamTy->isPointerType())
1339       return 0;
1340     if (ParamTy->isFunctionPointerType())
1341       return 1;
1342     if (ParamTy->isVoidPointerType())
1343       return 2;
1344     return llvm::Optional<unsigned>{};
1345   }();
1346   if (DiagSelect.hasValue()) {
1347     S.Diag(TheCall->getBeginLoc(), diag::err_builtin_launder_invalid_arg)
1348         << DiagSelect.getValue() << TheCall->getSourceRange();
1349     return ExprError();
1350   }
1351 
1352   // We either have an incomplete class type, or we have a class template
1353   // whose instantiation has not been forced. Example:
1354   //
1355   //   template <class T> struct Foo { T value; };
1356   //   Foo<int> *p = nullptr;
1357   //   auto *d = __builtin_launder(p);
1358   if (S.RequireCompleteType(TheCall->getBeginLoc(), ParamTy->getPointeeType(),
1359                             diag::err_incomplete_type))
1360     return ExprError();
1361 
1362   assert(ParamTy->getPointeeType()->isObjectType() &&
1363          "Unhandled non-object pointer case");
1364 
1365   InitializedEntity Entity =
1366       InitializedEntity::InitializeParameter(S.Context, ParamTy, false);
1367   ExprResult Arg =
1368       S.PerformCopyInitialization(Entity, SourceLocation(), TheCall->getArg(0));
1369   if (Arg.isInvalid())
1370     return ExprError();
1371   TheCall->setArg(0, Arg.get());
1372 
1373   return TheCall;
1374 }
1375 
1376 // Emit an error and return true if the current architecture is not in the list
1377 // of supported architectures.
1378 static bool
1379 CheckBuiltinTargetSupport(Sema &S, unsigned BuiltinID, CallExpr *TheCall,
1380                           ArrayRef<llvm::Triple::ArchType> SupportedArchs) {
1381   llvm::Triple::ArchType CurArch =
1382       S.getASTContext().getTargetInfo().getTriple().getArch();
1383   if (llvm::is_contained(SupportedArchs, CurArch))
1384     return false;
1385   S.Diag(TheCall->getBeginLoc(), diag::err_builtin_target_unsupported)
1386       << TheCall->getSourceRange();
1387   return true;
1388 }
1389 
1390 static void CheckNonNullArgument(Sema &S, const Expr *ArgExpr,
1391                                  SourceLocation CallSiteLoc);
1392 
1393 bool Sema::CheckTSBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
1394                                       CallExpr *TheCall) {
1395   switch (TI.getTriple().getArch()) {
1396   default:
1397     // Some builtins don't require additional checking, so just consider these
1398     // acceptable.
1399     return false;
1400   case llvm::Triple::arm:
1401   case llvm::Triple::armeb:
1402   case llvm::Triple::thumb:
1403   case llvm::Triple::thumbeb:
1404     return CheckARMBuiltinFunctionCall(TI, BuiltinID, TheCall);
1405   case llvm::Triple::aarch64:
1406   case llvm::Triple::aarch64_32:
1407   case llvm::Triple::aarch64_be:
1408     return CheckAArch64BuiltinFunctionCall(TI, BuiltinID, TheCall);
1409   case llvm::Triple::bpfeb:
1410   case llvm::Triple::bpfel:
1411     return CheckBPFBuiltinFunctionCall(BuiltinID, TheCall);
1412   case llvm::Triple::hexagon:
1413     return CheckHexagonBuiltinFunctionCall(BuiltinID, TheCall);
1414   case llvm::Triple::mips:
1415   case llvm::Triple::mipsel:
1416   case llvm::Triple::mips64:
1417   case llvm::Triple::mips64el:
1418     return CheckMipsBuiltinFunctionCall(TI, BuiltinID, TheCall);
1419   case llvm::Triple::systemz:
1420     return CheckSystemZBuiltinFunctionCall(BuiltinID, TheCall);
1421   case llvm::Triple::x86:
1422   case llvm::Triple::x86_64:
1423     return CheckX86BuiltinFunctionCall(TI, BuiltinID, TheCall);
1424   case llvm::Triple::ppc:
1425   case llvm::Triple::ppc64:
1426   case llvm::Triple::ppc64le:
1427     return CheckPPCBuiltinFunctionCall(TI, BuiltinID, TheCall);
1428   case llvm::Triple::amdgcn:
1429     return CheckAMDGCNBuiltinFunctionCall(BuiltinID, TheCall);
1430   }
1431 }
1432 
1433 ExprResult
1434 Sema::CheckBuiltinFunctionCall(FunctionDecl *FDecl, unsigned BuiltinID,
1435                                CallExpr *TheCall) {
1436   ExprResult TheCallResult(TheCall);
1437 
1438   // Find out if any arguments are required to be integer constant expressions.
1439   unsigned ICEArguments = 0;
1440   ASTContext::GetBuiltinTypeError Error;
1441   Context.GetBuiltinType(BuiltinID, Error, &ICEArguments);
1442   if (Error != ASTContext::GE_None)
1443     ICEArguments = 0;  // Don't diagnose previously diagnosed errors.
1444 
1445   // If any arguments are required to be ICE's, check and diagnose.
1446   for (unsigned ArgNo = 0; ICEArguments != 0; ++ArgNo) {
1447     // Skip arguments not required to be ICE's.
1448     if ((ICEArguments & (1 << ArgNo)) == 0) continue;
1449 
1450     llvm::APSInt Result;
1451     if (SemaBuiltinConstantArg(TheCall, ArgNo, Result))
1452       return true;
1453     ICEArguments &= ~(1 << ArgNo);
1454   }
1455 
1456   switch (BuiltinID) {
1457   case Builtin::BI__builtin___CFStringMakeConstantString:
1458     assert(TheCall->getNumArgs() == 1 &&
1459            "Wrong # arguments to builtin CFStringMakeConstantString");
1460     if (CheckObjCString(TheCall->getArg(0)))
1461       return ExprError();
1462     break;
1463   case Builtin::BI__builtin_ms_va_start:
1464   case Builtin::BI__builtin_stdarg_start:
1465   case Builtin::BI__builtin_va_start:
1466     if (SemaBuiltinVAStart(BuiltinID, TheCall))
1467       return ExprError();
1468     break;
1469   case Builtin::BI__va_start: {
1470     switch (Context.getTargetInfo().getTriple().getArch()) {
1471     case llvm::Triple::aarch64:
1472     case llvm::Triple::arm:
1473     case llvm::Triple::thumb:
1474       if (SemaBuiltinVAStartARMMicrosoft(TheCall))
1475         return ExprError();
1476       break;
1477     default:
1478       if (SemaBuiltinVAStart(BuiltinID, TheCall))
1479         return ExprError();
1480       break;
1481     }
1482     break;
1483   }
1484 
1485   // The acquire, release, and no fence variants are ARM and AArch64 only.
1486   case Builtin::BI_interlockedbittestandset_acq:
1487   case Builtin::BI_interlockedbittestandset_rel:
1488   case Builtin::BI_interlockedbittestandset_nf:
1489   case Builtin::BI_interlockedbittestandreset_acq:
1490   case Builtin::BI_interlockedbittestandreset_rel:
1491   case Builtin::BI_interlockedbittestandreset_nf:
1492     if (CheckBuiltinTargetSupport(
1493             *this, BuiltinID, TheCall,
1494             {llvm::Triple::arm, llvm::Triple::thumb, llvm::Triple::aarch64}))
1495       return ExprError();
1496     break;
1497 
1498   // The 64-bit bittest variants are x64, ARM, and AArch64 only.
1499   case Builtin::BI_bittest64:
1500   case Builtin::BI_bittestandcomplement64:
1501   case Builtin::BI_bittestandreset64:
1502   case Builtin::BI_bittestandset64:
1503   case Builtin::BI_interlockedbittestandreset64:
1504   case Builtin::BI_interlockedbittestandset64:
1505     if (CheckBuiltinTargetSupport(*this, BuiltinID, TheCall,
1506                                   {llvm::Triple::x86_64, llvm::Triple::arm,
1507                                    llvm::Triple::thumb, llvm::Triple::aarch64}))
1508       return ExprError();
1509     break;
1510 
1511   case Builtin::BI__builtin_isgreater:
1512   case Builtin::BI__builtin_isgreaterequal:
1513   case Builtin::BI__builtin_isless:
1514   case Builtin::BI__builtin_islessequal:
1515   case Builtin::BI__builtin_islessgreater:
1516   case Builtin::BI__builtin_isunordered:
1517     if (SemaBuiltinUnorderedCompare(TheCall))
1518       return ExprError();
1519     break;
1520   case Builtin::BI__builtin_fpclassify:
1521     if (SemaBuiltinFPClassification(TheCall, 6))
1522       return ExprError();
1523     break;
1524   case Builtin::BI__builtin_isfinite:
1525   case Builtin::BI__builtin_isinf:
1526   case Builtin::BI__builtin_isinf_sign:
1527   case Builtin::BI__builtin_isnan:
1528   case Builtin::BI__builtin_isnormal:
1529   case Builtin::BI__builtin_signbit:
1530   case Builtin::BI__builtin_signbitf:
1531   case Builtin::BI__builtin_signbitl:
1532     if (SemaBuiltinFPClassification(TheCall, 1))
1533       return ExprError();
1534     break;
1535   case Builtin::BI__builtin_shufflevector:
1536     return SemaBuiltinShuffleVector(TheCall);
1537     // TheCall will be freed by the smart pointer here, but that's fine, since
1538     // SemaBuiltinShuffleVector guts it, but then doesn't release it.
1539   case Builtin::BI__builtin_prefetch:
1540     if (SemaBuiltinPrefetch(TheCall))
1541       return ExprError();
1542     break;
1543   case Builtin::BI__builtin_alloca_with_align:
1544     if (SemaBuiltinAllocaWithAlign(TheCall))
1545       return ExprError();
1546     LLVM_FALLTHROUGH;
1547   case Builtin::BI__builtin_alloca:
1548     Diag(TheCall->getBeginLoc(), diag::warn_alloca)
1549         << TheCall->getDirectCallee();
1550     break;
1551   case Builtin::BI__assume:
1552   case Builtin::BI__builtin_assume:
1553     if (SemaBuiltinAssume(TheCall))
1554       return ExprError();
1555     break;
1556   case Builtin::BI__builtin_assume_aligned:
1557     if (SemaBuiltinAssumeAligned(TheCall))
1558       return ExprError();
1559     break;
1560   case Builtin::BI__builtin_dynamic_object_size:
1561   case Builtin::BI__builtin_object_size:
1562     if (SemaBuiltinConstantArgRange(TheCall, 1, 0, 3))
1563       return ExprError();
1564     break;
1565   case Builtin::BI__builtin_longjmp:
1566     if (SemaBuiltinLongjmp(TheCall))
1567       return ExprError();
1568     break;
1569   case Builtin::BI__builtin_setjmp:
1570     if (SemaBuiltinSetjmp(TheCall))
1571       return ExprError();
1572     break;
1573   case Builtin::BI__builtin_classify_type:
1574     if (checkArgCount(*this, TheCall, 1)) return true;
1575     TheCall->setType(Context.IntTy);
1576     break;
1577   case Builtin::BI__builtin_complex:
1578     if (SemaBuiltinComplex(TheCall))
1579       return ExprError();
1580     break;
1581   case Builtin::BI__builtin_constant_p: {
1582     if (checkArgCount(*this, TheCall, 1)) return true;
1583     ExprResult Arg = DefaultFunctionArrayLvalueConversion(TheCall->getArg(0));
1584     if (Arg.isInvalid()) return true;
1585     TheCall->setArg(0, Arg.get());
1586     TheCall->setType(Context.IntTy);
1587     break;
1588   }
1589   case Builtin::BI__builtin_launder:
1590     return SemaBuiltinLaunder(*this, TheCall);
1591   case Builtin::BI__sync_fetch_and_add:
1592   case Builtin::BI__sync_fetch_and_add_1:
1593   case Builtin::BI__sync_fetch_and_add_2:
1594   case Builtin::BI__sync_fetch_and_add_4:
1595   case Builtin::BI__sync_fetch_and_add_8:
1596   case Builtin::BI__sync_fetch_and_add_16:
1597   case Builtin::BI__sync_fetch_and_sub:
1598   case Builtin::BI__sync_fetch_and_sub_1:
1599   case Builtin::BI__sync_fetch_and_sub_2:
1600   case Builtin::BI__sync_fetch_and_sub_4:
1601   case Builtin::BI__sync_fetch_and_sub_8:
1602   case Builtin::BI__sync_fetch_and_sub_16:
1603   case Builtin::BI__sync_fetch_and_or:
1604   case Builtin::BI__sync_fetch_and_or_1:
1605   case Builtin::BI__sync_fetch_and_or_2:
1606   case Builtin::BI__sync_fetch_and_or_4:
1607   case Builtin::BI__sync_fetch_and_or_8:
1608   case Builtin::BI__sync_fetch_and_or_16:
1609   case Builtin::BI__sync_fetch_and_and:
1610   case Builtin::BI__sync_fetch_and_and_1:
1611   case Builtin::BI__sync_fetch_and_and_2:
1612   case Builtin::BI__sync_fetch_and_and_4:
1613   case Builtin::BI__sync_fetch_and_and_8:
1614   case Builtin::BI__sync_fetch_and_and_16:
1615   case Builtin::BI__sync_fetch_and_xor:
1616   case Builtin::BI__sync_fetch_and_xor_1:
1617   case Builtin::BI__sync_fetch_and_xor_2:
1618   case Builtin::BI__sync_fetch_and_xor_4:
1619   case Builtin::BI__sync_fetch_and_xor_8:
1620   case Builtin::BI__sync_fetch_and_xor_16:
1621   case Builtin::BI__sync_fetch_and_nand:
1622   case Builtin::BI__sync_fetch_and_nand_1:
1623   case Builtin::BI__sync_fetch_and_nand_2:
1624   case Builtin::BI__sync_fetch_and_nand_4:
1625   case Builtin::BI__sync_fetch_and_nand_8:
1626   case Builtin::BI__sync_fetch_and_nand_16:
1627   case Builtin::BI__sync_add_and_fetch:
1628   case Builtin::BI__sync_add_and_fetch_1:
1629   case Builtin::BI__sync_add_and_fetch_2:
1630   case Builtin::BI__sync_add_and_fetch_4:
1631   case Builtin::BI__sync_add_and_fetch_8:
1632   case Builtin::BI__sync_add_and_fetch_16:
1633   case Builtin::BI__sync_sub_and_fetch:
1634   case Builtin::BI__sync_sub_and_fetch_1:
1635   case Builtin::BI__sync_sub_and_fetch_2:
1636   case Builtin::BI__sync_sub_and_fetch_4:
1637   case Builtin::BI__sync_sub_and_fetch_8:
1638   case Builtin::BI__sync_sub_and_fetch_16:
1639   case Builtin::BI__sync_and_and_fetch:
1640   case Builtin::BI__sync_and_and_fetch_1:
1641   case Builtin::BI__sync_and_and_fetch_2:
1642   case Builtin::BI__sync_and_and_fetch_4:
1643   case Builtin::BI__sync_and_and_fetch_8:
1644   case Builtin::BI__sync_and_and_fetch_16:
1645   case Builtin::BI__sync_or_and_fetch:
1646   case Builtin::BI__sync_or_and_fetch_1:
1647   case Builtin::BI__sync_or_and_fetch_2:
1648   case Builtin::BI__sync_or_and_fetch_4:
1649   case Builtin::BI__sync_or_and_fetch_8:
1650   case Builtin::BI__sync_or_and_fetch_16:
1651   case Builtin::BI__sync_xor_and_fetch:
1652   case Builtin::BI__sync_xor_and_fetch_1:
1653   case Builtin::BI__sync_xor_and_fetch_2:
1654   case Builtin::BI__sync_xor_and_fetch_4:
1655   case Builtin::BI__sync_xor_and_fetch_8:
1656   case Builtin::BI__sync_xor_and_fetch_16:
1657   case Builtin::BI__sync_nand_and_fetch:
1658   case Builtin::BI__sync_nand_and_fetch_1:
1659   case Builtin::BI__sync_nand_and_fetch_2:
1660   case Builtin::BI__sync_nand_and_fetch_4:
1661   case Builtin::BI__sync_nand_and_fetch_8:
1662   case Builtin::BI__sync_nand_and_fetch_16:
1663   case Builtin::BI__sync_val_compare_and_swap:
1664   case Builtin::BI__sync_val_compare_and_swap_1:
1665   case Builtin::BI__sync_val_compare_and_swap_2:
1666   case Builtin::BI__sync_val_compare_and_swap_4:
1667   case Builtin::BI__sync_val_compare_and_swap_8:
1668   case Builtin::BI__sync_val_compare_and_swap_16:
1669   case Builtin::BI__sync_bool_compare_and_swap:
1670   case Builtin::BI__sync_bool_compare_and_swap_1:
1671   case Builtin::BI__sync_bool_compare_and_swap_2:
1672   case Builtin::BI__sync_bool_compare_and_swap_4:
1673   case Builtin::BI__sync_bool_compare_and_swap_8:
1674   case Builtin::BI__sync_bool_compare_and_swap_16:
1675   case Builtin::BI__sync_lock_test_and_set:
1676   case Builtin::BI__sync_lock_test_and_set_1:
1677   case Builtin::BI__sync_lock_test_and_set_2:
1678   case Builtin::BI__sync_lock_test_and_set_4:
1679   case Builtin::BI__sync_lock_test_and_set_8:
1680   case Builtin::BI__sync_lock_test_and_set_16:
1681   case Builtin::BI__sync_lock_release:
1682   case Builtin::BI__sync_lock_release_1:
1683   case Builtin::BI__sync_lock_release_2:
1684   case Builtin::BI__sync_lock_release_4:
1685   case Builtin::BI__sync_lock_release_8:
1686   case Builtin::BI__sync_lock_release_16:
1687   case Builtin::BI__sync_swap:
1688   case Builtin::BI__sync_swap_1:
1689   case Builtin::BI__sync_swap_2:
1690   case Builtin::BI__sync_swap_4:
1691   case Builtin::BI__sync_swap_8:
1692   case Builtin::BI__sync_swap_16:
1693     return SemaBuiltinAtomicOverloaded(TheCallResult);
1694   case Builtin::BI__sync_synchronize:
1695     Diag(TheCall->getBeginLoc(), diag::warn_atomic_implicit_seq_cst)
1696         << TheCall->getCallee()->getSourceRange();
1697     break;
1698   case Builtin::BI__builtin_nontemporal_load:
1699   case Builtin::BI__builtin_nontemporal_store:
1700     return SemaBuiltinNontemporalOverloaded(TheCallResult);
1701   case Builtin::BI__builtin_memcpy_inline: {
1702     clang::Expr *SizeOp = TheCall->getArg(2);
1703     // We warn about copying to or from `nullptr` pointers when `size` is
1704     // greater than 0. When `size` is value dependent we cannot evaluate its
1705     // value so we bail out.
1706     if (SizeOp->isValueDependent())
1707       break;
1708     if (!SizeOp->EvaluateKnownConstInt(Context).isNullValue()) {
1709       CheckNonNullArgument(*this, TheCall->getArg(0), TheCall->getExprLoc());
1710       CheckNonNullArgument(*this, TheCall->getArg(1), TheCall->getExprLoc());
1711     }
1712     break;
1713   }
1714 #define BUILTIN(ID, TYPE, ATTRS)
1715 #define ATOMIC_BUILTIN(ID, TYPE, ATTRS) \
1716   case Builtin::BI##ID: \
1717     return SemaAtomicOpsOverloaded(TheCallResult, AtomicExpr::AO##ID);
1718 #include "clang/Basic/Builtins.def"
1719   case Builtin::BI__annotation:
1720     if (SemaBuiltinMSVCAnnotation(*this, TheCall))
1721       return ExprError();
1722     break;
1723   case Builtin::BI__builtin_annotation:
1724     if (SemaBuiltinAnnotation(*this, TheCall))
1725       return ExprError();
1726     break;
1727   case Builtin::BI__builtin_addressof:
1728     if (SemaBuiltinAddressof(*this, TheCall))
1729       return ExprError();
1730     break;
1731   case Builtin::BI__builtin_is_aligned:
1732   case Builtin::BI__builtin_align_up:
1733   case Builtin::BI__builtin_align_down:
1734     if (SemaBuiltinAlignment(*this, TheCall, BuiltinID))
1735       return ExprError();
1736     break;
1737   case Builtin::BI__builtin_add_overflow:
1738   case Builtin::BI__builtin_sub_overflow:
1739   case Builtin::BI__builtin_mul_overflow:
1740     if (SemaBuiltinOverflow(*this, TheCall, BuiltinID))
1741       return ExprError();
1742     break;
1743   case Builtin::BI__builtin_operator_new:
1744   case Builtin::BI__builtin_operator_delete: {
1745     bool IsDelete = BuiltinID == Builtin::BI__builtin_operator_delete;
1746     ExprResult Res =
1747         SemaBuiltinOperatorNewDeleteOverloaded(TheCallResult, IsDelete);
1748     if (Res.isInvalid())
1749       CorrectDelayedTyposInExpr(TheCallResult.get());
1750     return Res;
1751   }
1752   case Builtin::BI__builtin_dump_struct: {
1753     // We first want to ensure we are called with 2 arguments
1754     if (checkArgCount(*this, TheCall, 2))
1755       return ExprError();
1756     // Ensure that the first argument is of type 'struct XX *'
1757     const Expr *PtrArg = TheCall->getArg(0)->IgnoreParenImpCasts();
1758     const QualType PtrArgType = PtrArg->getType();
1759     if (!PtrArgType->isPointerType() ||
1760         !PtrArgType->getPointeeType()->isRecordType()) {
1761       Diag(PtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1762           << PtrArgType << "structure pointer" << 1 << 0 << 3 << 1 << PtrArgType
1763           << "structure pointer";
1764       return ExprError();
1765     }
1766 
1767     // Ensure that the second argument is of type 'FunctionType'
1768     const Expr *FnPtrArg = TheCall->getArg(1)->IgnoreImpCasts();
1769     const QualType FnPtrArgType = FnPtrArg->getType();
1770     if (!FnPtrArgType->isPointerType()) {
1771       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1772           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1773           << FnPtrArgType << "'int (*)(const char *, ...)'";
1774       return ExprError();
1775     }
1776 
1777     const auto *FuncType =
1778         FnPtrArgType->getPointeeType()->getAs<FunctionType>();
1779 
1780     if (!FuncType) {
1781       Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1782           << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3 << 2
1783           << FnPtrArgType << "'int (*)(const char *, ...)'";
1784       return ExprError();
1785     }
1786 
1787     if (const auto *FT = dyn_cast<FunctionProtoType>(FuncType)) {
1788       if (!FT->getNumParams()) {
1789         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1790             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1791             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1792         return ExprError();
1793       }
1794       QualType PT = FT->getParamType(0);
1795       if (!FT->isVariadic() || FT->getReturnType() != Context.IntTy ||
1796           !PT->isPointerType() || !PT->getPointeeType()->isCharType() ||
1797           !PT->getPointeeType().isConstQualified()) {
1798         Diag(FnPtrArg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
1799             << FnPtrArgType << "'int (*)(const char *, ...)'" << 1 << 0 << 3
1800             << 2 << FnPtrArgType << "'int (*)(const char *, ...)'";
1801         return ExprError();
1802       }
1803     }
1804 
1805     TheCall->setType(Context.IntTy);
1806     break;
1807   }
1808   case Builtin::BI__builtin_expect_with_probability: {
1809     // We first want to ensure we are called with 3 arguments
1810     if (checkArgCount(*this, TheCall, 3))
1811       return ExprError();
1812     // then check probability is constant float in range [0.0, 1.0]
1813     const Expr *ProbArg = TheCall->getArg(2);
1814     SmallVector<PartialDiagnosticAt, 8> Notes;
1815     Expr::EvalResult Eval;
1816     Eval.Diag = &Notes;
1817     if ((!ProbArg->EvaluateAsConstantExpr(Eval, Context)) ||
1818         !Eval.Val.isFloat()) {
1819       Diag(ProbArg->getBeginLoc(), diag::err_probability_not_constant_float)
1820           << ProbArg->getSourceRange();
1821       for (const PartialDiagnosticAt &PDiag : Notes)
1822         Diag(PDiag.first, PDiag.second);
1823       return ExprError();
1824     }
1825     llvm::APFloat Probability = Eval.Val.getFloat();
1826     bool LoseInfo = false;
1827     Probability.convert(llvm::APFloat::IEEEdouble(),
1828                         llvm::RoundingMode::Dynamic, &LoseInfo);
1829     if (!(Probability >= llvm::APFloat(0.0) &&
1830           Probability <= llvm::APFloat(1.0))) {
1831       Diag(ProbArg->getBeginLoc(), diag::err_probability_out_of_range)
1832           << ProbArg->getSourceRange();
1833       return ExprError();
1834     }
1835     break;
1836   }
1837   case Builtin::BI__builtin_preserve_access_index:
1838     if (SemaBuiltinPreserveAI(*this, TheCall))
1839       return ExprError();
1840     break;
1841   case Builtin::BI__builtin_call_with_static_chain:
1842     if (SemaBuiltinCallWithStaticChain(*this, TheCall))
1843       return ExprError();
1844     break;
1845   case Builtin::BI__exception_code:
1846   case Builtin::BI_exception_code:
1847     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHExceptScope,
1848                                  diag::err_seh___except_block))
1849       return ExprError();
1850     break;
1851   case Builtin::BI__exception_info:
1852   case Builtin::BI_exception_info:
1853     if (SemaBuiltinSEHScopeCheck(*this, TheCall, Scope::SEHFilterScope,
1854                                  diag::err_seh___except_filter))
1855       return ExprError();
1856     break;
1857   case Builtin::BI__GetExceptionInfo:
1858     if (checkArgCount(*this, TheCall, 1))
1859       return ExprError();
1860 
1861     if (CheckCXXThrowOperand(
1862             TheCall->getBeginLoc(),
1863             Context.getExceptionObjectType(FDecl->getParamDecl(0)->getType()),
1864             TheCall))
1865       return ExprError();
1866 
1867     TheCall->setType(Context.VoidPtrTy);
1868     break;
1869   // OpenCL v2.0, s6.13.16 - Pipe functions
1870   case Builtin::BIread_pipe:
1871   case Builtin::BIwrite_pipe:
1872     // Since those two functions are declared with var args, we need a semantic
1873     // check for the argument.
1874     if (SemaBuiltinRWPipe(*this, TheCall))
1875       return ExprError();
1876     break;
1877   case Builtin::BIreserve_read_pipe:
1878   case Builtin::BIreserve_write_pipe:
1879   case Builtin::BIwork_group_reserve_read_pipe:
1880   case Builtin::BIwork_group_reserve_write_pipe:
1881     if (SemaBuiltinReserveRWPipe(*this, TheCall))
1882       return ExprError();
1883     break;
1884   case Builtin::BIsub_group_reserve_read_pipe:
1885   case Builtin::BIsub_group_reserve_write_pipe:
1886     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1887         SemaBuiltinReserveRWPipe(*this, TheCall))
1888       return ExprError();
1889     break;
1890   case Builtin::BIcommit_read_pipe:
1891   case Builtin::BIcommit_write_pipe:
1892   case Builtin::BIwork_group_commit_read_pipe:
1893   case Builtin::BIwork_group_commit_write_pipe:
1894     if (SemaBuiltinCommitRWPipe(*this, TheCall))
1895       return ExprError();
1896     break;
1897   case Builtin::BIsub_group_commit_read_pipe:
1898   case Builtin::BIsub_group_commit_write_pipe:
1899     if (checkOpenCLSubgroupExt(*this, TheCall) ||
1900         SemaBuiltinCommitRWPipe(*this, TheCall))
1901       return ExprError();
1902     break;
1903   case Builtin::BIget_pipe_num_packets:
1904   case Builtin::BIget_pipe_max_packets:
1905     if (SemaBuiltinPipePackets(*this, TheCall))
1906       return ExprError();
1907     break;
1908   case Builtin::BIto_global:
1909   case Builtin::BIto_local:
1910   case Builtin::BIto_private:
1911     if (SemaOpenCLBuiltinToAddr(*this, BuiltinID, TheCall))
1912       return ExprError();
1913     break;
1914   // OpenCL v2.0, s6.13.17 - Enqueue kernel functions.
1915   case Builtin::BIenqueue_kernel:
1916     if (SemaOpenCLBuiltinEnqueueKernel(*this, TheCall))
1917       return ExprError();
1918     break;
1919   case Builtin::BIget_kernel_work_group_size:
1920   case Builtin::BIget_kernel_preferred_work_group_size_multiple:
1921     if (SemaOpenCLBuiltinKernelWorkGroupSize(*this, TheCall))
1922       return ExprError();
1923     break;
1924   case Builtin::BIget_kernel_max_sub_group_size_for_ndrange:
1925   case Builtin::BIget_kernel_sub_group_count_for_ndrange:
1926     if (SemaOpenCLBuiltinNDRangeAndBlock(*this, TheCall))
1927       return ExprError();
1928     break;
1929   case Builtin::BI__builtin_os_log_format:
1930     Cleanup.setExprNeedsCleanups(true);
1931     LLVM_FALLTHROUGH;
1932   case Builtin::BI__builtin_os_log_format_buffer_size:
1933     if (SemaBuiltinOSLogFormat(TheCall))
1934       return ExprError();
1935     break;
1936   case Builtin::BI__builtin_frame_address:
1937   case Builtin::BI__builtin_return_address: {
1938     if (SemaBuiltinConstantArgRange(TheCall, 0, 0, 0xFFFF))
1939       return ExprError();
1940 
1941     // -Wframe-address warning if non-zero passed to builtin
1942     // return/frame address.
1943     Expr::EvalResult Result;
1944     if (TheCall->getArg(0)->EvaluateAsInt(Result, getASTContext()) &&
1945         Result.Val.getInt() != 0)
1946       Diag(TheCall->getBeginLoc(), diag::warn_frame_address)
1947           << ((BuiltinID == Builtin::BI__builtin_return_address)
1948                   ? "__builtin_return_address"
1949                   : "__builtin_frame_address")
1950           << TheCall->getSourceRange();
1951     break;
1952   }
1953 
1954   case Builtin::BI__builtin_matrix_transpose:
1955     return SemaBuiltinMatrixTranspose(TheCall, TheCallResult);
1956 
1957   case Builtin::BI__builtin_matrix_column_major_load:
1958     return SemaBuiltinMatrixColumnMajorLoad(TheCall, TheCallResult);
1959 
1960   case Builtin::BI__builtin_matrix_column_major_store:
1961     return SemaBuiltinMatrixColumnMajorStore(TheCall, TheCallResult);
1962   }
1963 
1964   // Since the target specific builtins for each arch overlap, only check those
1965   // of the arch we are compiling for.
1966   if (Context.BuiltinInfo.isTSBuiltin(BuiltinID)) {
1967     if (Context.BuiltinInfo.isAuxBuiltinID(BuiltinID)) {
1968       assert(Context.getAuxTargetInfo() &&
1969              "Aux Target Builtin, but not an aux target?");
1970 
1971       if (CheckTSBuiltinFunctionCall(
1972               *Context.getAuxTargetInfo(),
1973               Context.BuiltinInfo.getAuxBuiltinID(BuiltinID), TheCall))
1974         return ExprError();
1975     } else {
1976       if (CheckTSBuiltinFunctionCall(Context.getTargetInfo(), BuiltinID,
1977                                      TheCall))
1978         return ExprError();
1979     }
1980   }
1981 
1982   return TheCallResult;
1983 }
1984 
1985 // Get the valid immediate range for the specified NEON type code.
1986 static unsigned RFT(unsigned t, bool shift = false, bool ForceQuad = false) {
1987   NeonTypeFlags Type(t);
1988   int IsQuad = ForceQuad ? true : Type.isQuad();
1989   switch (Type.getEltType()) {
1990   case NeonTypeFlags::Int8:
1991   case NeonTypeFlags::Poly8:
1992     return shift ? 7 : (8 << IsQuad) - 1;
1993   case NeonTypeFlags::Int16:
1994   case NeonTypeFlags::Poly16:
1995     return shift ? 15 : (4 << IsQuad) - 1;
1996   case NeonTypeFlags::Int32:
1997     return shift ? 31 : (2 << IsQuad) - 1;
1998   case NeonTypeFlags::Int64:
1999   case NeonTypeFlags::Poly64:
2000     return shift ? 63 : (1 << IsQuad) - 1;
2001   case NeonTypeFlags::Poly128:
2002     return shift ? 127 : (1 << IsQuad) - 1;
2003   case NeonTypeFlags::Float16:
2004     assert(!shift && "cannot shift float types!");
2005     return (4 << IsQuad) - 1;
2006   case NeonTypeFlags::Float32:
2007     assert(!shift && "cannot shift float types!");
2008     return (2 << IsQuad) - 1;
2009   case NeonTypeFlags::Float64:
2010     assert(!shift && "cannot shift float types!");
2011     return (1 << IsQuad) - 1;
2012   case NeonTypeFlags::BFloat16:
2013     assert(!shift && "cannot shift float types!");
2014     return (4 << IsQuad) - 1;
2015   }
2016   llvm_unreachable("Invalid NeonTypeFlag!");
2017 }
2018 
2019 /// getNeonEltType - Return the QualType corresponding to the elements of
2020 /// the vector type specified by the NeonTypeFlags.  This is used to check
2021 /// the pointer arguments for Neon load/store intrinsics.
2022 static QualType getNeonEltType(NeonTypeFlags Flags, ASTContext &Context,
2023                                bool IsPolyUnsigned, bool IsInt64Long) {
2024   switch (Flags.getEltType()) {
2025   case NeonTypeFlags::Int8:
2026     return Flags.isUnsigned() ? Context.UnsignedCharTy : Context.SignedCharTy;
2027   case NeonTypeFlags::Int16:
2028     return Flags.isUnsigned() ? Context.UnsignedShortTy : Context.ShortTy;
2029   case NeonTypeFlags::Int32:
2030     return Flags.isUnsigned() ? Context.UnsignedIntTy : Context.IntTy;
2031   case NeonTypeFlags::Int64:
2032     if (IsInt64Long)
2033       return Flags.isUnsigned() ? Context.UnsignedLongTy : Context.LongTy;
2034     else
2035       return Flags.isUnsigned() ? Context.UnsignedLongLongTy
2036                                 : Context.LongLongTy;
2037   case NeonTypeFlags::Poly8:
2038     return IsPolyUnsigned ? Context.UnsignedCharTy : Context.SignedCharTy;
2039   case NeonTypeFlags::Poly16:
2040     return IsPolyUnsigned ? Context.UnsignedShortTy : Context.ShortTy;
2041   case NeonTypeFlags::Poly64:
2042     if (IsInt64Long)
2043       return Context.UnsignedLongTy;
2044     else
2045       return Context.UnsignedLongLongTy;
2046   case NeonTypeFlags::Poly128:
2047     break;
2048   case NeonTypeFlags::Float16:
2049     return Context.HalfTy;
2050   case NeonTypeFlags::Float32:
2051     return Context.FloatTy;
2052   case NeonTypeFlags::Float64:
2053     return Context.DoubleTy;
2054   case NeonTypeFlags::BFloat16:
2055     return Context.BFloat16Ty;
2056   }
2057   llvm_unreachable("Invalid NeonTypeFlag!");
2058 }
2059 
2060 bool Sema::CheckSVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2061   // Range check SVE intrinsics that take immediate values.
2062   SmallVector<std::tuple<int,int,int>, 3> ImmChecks;
2063 
2064   switch (BuiltinID) {
2065   default:
2066     return false;
2067 #define GET_SVE_IMMEDIATE_CHECK
2068 #include "clang/Basic/arm_sve_sema_rangechecks.inc"
2069 #undef GET_SVE_IMMEDIATE_CHECK
2070   }
2071 
2072   // Perform all the immediate checks for this builtin call.
2073   bool HasError = false;
2074   for (auto &I : ImmChecks) {
2075     int ArgNum, CheckTy, ElementSizeInBits;
2076     std::tie(ArgNum, CheckTy, ElementSizeInBits) = I;
2077 
2078     typedef bool(*OptionSetCheckFnTy)(int64_t Value);
2079 
2080     // Function that checks whether the operand (ArgNum) is an immediate
2081     // that is one of the predefined values.
2082     auto CheckImmediateInSet = [&](OptionSetCheckFnTy CheckImm,
2083                                    int ErrDiag) -> bool {
2084       // We can't check the value of a dependent argument.
2085       Expr *Arg = TheCall->getArg(ArgNum);
2086       if (Arg->isTypeDependent() || Arg->isValueDependent())
2087         return false;
2088 
2089       // Check constant-ness first.
2090       llvm::APSInt Imm;
2091       if (SemaBuiltinConstantArg(TheCall, ArgNum, Imm))
2092         return true;
2093 
2094       if (!CheckImm(Imm.getSExtValue()))
2095         return Diag(TheCall->getBeginLoc(), ErrDiag) << Arg->getSourceRange();
2096       return false;
2097     };
2098 
2099     switch ((SVETypeFlags::ImmCheckType)CheckTy) {
2100     case SVETypeFlags::ImmCheck0_31:
2101       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 31))
2102         HasError = true;
2103       break;
2104     case SVETypeFlags::ImmCheck0_13:
2105       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 13))
2106         HasError = true;
2107       break;
2108     case SVETypeFlags::ImmCheck1_16:
2109       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, 16))
2110         HasError = true;
2111       break;
2112     case SVETypeFlags::ImmCheck0_7:
2113       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 7))
2114         HasError = true;
2115       break;
2116     case SVETypeFlags::ImmCheckExtract:
2117       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2118                                       (2048 / ElementSizeInBits) - 1))
2119         HasError = true;
2120       break;
2121     case SVETypeFlags::ImmCheckShiftRight:
2122       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1, ElementSizeInBits))
2123         HasError = true;
2124       break;
2125     case SVETypeFlags::ImmCheckShiftRightNarrow:
2126       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 1,
2127                                       ElementSizeInBits / 2))
2128         HasError = true;
2129       break;
2130     case SVETypeFlags::ImmCheckShiftLeft:
2131       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2132                                       ElementSizeInBits - 1))
2133         HasError = true;
2134       break;
2135     case SVETypeFlags::ImmCheckLaneIndex:
2136       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2137                                       (128 / (1 * ElementSizeInBits)) - 1))
2138         HasError = true;
2139       break;
2140     case SVETypeFlags::ImmCheckLaneIndexCompRotate:
2141       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2142                                       (128 / (2 * ElementSizeInBits)) - 1))
2143         HasError = true;
2144       break;
2145     case SVETypeFlags::ImmCheckLaneIndexDot:
2146       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0,
2147                                       (128 / (4 * ElementSizeInBits)) - 1))
2148         HasError = true;
2149       break;
2150     case SVETypeFlags::ImmCheckComplexRot90_270:
2151       if (CheckImmediateInSet([](int64_t V) { return V == 90 || V == 270; },
2152                               diag::err_rotation_argument_to_cadd))
2153         HasError = true;
2154       break;
2155     case SVETypeFlags::ImmCheckComplexRotAll90:
2156       if (CheckImmediateInSet(
2157               [](int64_t V) {
2158                 return V == 0 || V == 90 || V == 180 || V == 270;
2159               },
2160               diag::err_rotation_argument_to_cmla))
2161         HasError = true;
2162       break;
2163     case SVETypeFlags::ImmCheck0_1:
2164       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 1))
2165         HasError = true;
2166       break;
2167     case SVETypeFlags::ImmCheck0_2:
2168       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 2))
2169         HasError = true;
2170       break;
2171     case SVETypeFlags::ImmCheck0_3:
2172       if (SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, 3))
2173         HasError = true;
2174       break;
2175     }
2176   }
2177 
2178   return HasError;
2179 }
2180 
2181 bool Sema::CheckNeonBuiltinFunctionCall(const TargetInfo &TI,
2182                                         unsigned BuiltinID, CallExpr *TheCall) {
2183   llvm::APSInt Result;
2184   uint64_t mask = 0;
2185   unsigned TV = 0;
2186   int PtrArgNum = -1;
2187   bool HasConstPtr = false;
2188   switch (BuiltinID) {
2189 #define GET_NEON_OVERLOAD_CHECK
2190 #include "clang/Basic/arm_neon.inc"
2191 #include "clang/Basic/arm_fp16.inc"
2192 #undef GET_NEON_OVERLOAD_CHECK
2193   }
2194 
2195   // For NEON intrinsics which are overloaded on vector element type, validate
2196   // the immediate which specifies which variant to emit.
2197   unsigned ImmArg = TheCall->getNumArgs()-1;
2198   if (mask) {
2199     if (SemaBuiltinConstantArg(TheCall, ImmArg, Result))
2200       return true;
2201 
2202     TV = Result.getLimitedValue(64);
2203     if ((TV > 63) || (mask & (1ULL << TV)) == 0)
2204       return Diag(TheCall->getBeginLoc(), diag::err_invalid_neon_type_code)
2205              << TheCall->getArg(ImmArg)->getSourceRange();
2206   }
2207 
2208   if (PtrArgNum >= 0) {
2209     // Check that pointer arguments have the specified type.
2210     Expr *Arg = TheCall->getArg(PtrArgNum);
2211     if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Arg))
2212       Arg = ICE->getSubExpr();
2213     ExprResult RHS = DefaultFunctionArrayLvalueConversion(Arg);
2214     QualType RHSTy = RHS.get()->getType();
2215 
2216     llvm::Triple::ArchType Arch = TI.getTriple().getArch();
2217     bool IsPolyUnsigned = Arch == llvm::Triple::aarch64 ||
2218                           Arch == llvm::Triple::aarch64_32 ||
2219                           Arch == llvm::Triple::aarch64_be;
2220     bool IsInt64Long = TI.getInt64Type() == TargetInfo::SignedLong;
2221     QualType EltTy =
2222         getNeonEltType(NeonTypeFlags(TV), Context, IsPolyUnsigned, IsInt64Long);
2223     if (HasConstPtr)
2224       EltTy = EltTy.withConst();
2225     QualType LHSTy = Context.getPointerType(EltTy);
2226     AssignConvertType ConvTy;
2227     ConvTy = CheckSingleAssignmentConstraints(LHSTy, RHS);
2228     if (RHS.isInvalid())
2229       return true;
2230     if (DiagnoseAssignmentResult(ConvTy, Arg->getBeginLoc(), LHSTy, RHSTy,
2231                                  RHS.get(), AA_Assigning))
2232       return true;
2233   }
2234 
2235   // For NEON intrinsics which take an immediate value as part of the
2236   // instruction, range check them here.
2237   unsigned i = 0, l = 0, u = 0;
2238   switch (BuiltinID) {
2239   default:
2240     return false;
2241   #define GET_NEON_IMMEDIATE_CHECK
2242   #include "clang/Basic/arm_neon.inc"
2243   #include "clang/Basic/arm_fp16.inc"
2244   #undef GET_NEON_IMMEDIATE_CHECK
2245   }
2246 
2247   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2248 }
2249 
2250 bool Sema::CheckMVEBuiltinFunctionCall(unsigned BuiltinID, CallExpr *TheCall) {
2251   switch (BuiltinID) {
2252   default:
2253     return false;
2254   #include "clang/Basic/arm_mve_builtin_sema.inc"
2255   }
2256 }
2257 
2258 bool Sema::CheckCDEBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2259                                        CallExpr *TheCall) {
2260   bool Err = false;
2261   switch (BuiltinID) {
2262   default:
2263     return false;
2264 #include "clang/Basic/arm_cde_builtin_sema.inc"
2265   }
2266 
2267   if (Err)
2268     return true;
2269 
2270   return CheckARMCoprocessorImmediate(TI, TheCall->getArg(0), /*WantCDE*/ true);
2271 }
2272 
2273 bool Sema::CheckARMCoprocessorImmediate(const TargetInfo &TI,
2274                                         const Expr *CoprocArg, bool WantCDE) {
2275   if (isConstantEvaluated())
2276     return false;
2277 
2278   // We can't check the value of a dependent argument.
2279   if (CoprocArg->isTypeDependent() || CoprocArg->isValueDependent())
2280     return false;
2281 
2282   llvm::APSInt CoprocNoAP = *CoprocArg->getIntegerConstantExpr(Context);
2283   int64_t CoprocNo = CoprocNoAP.getExtValue();
2284   assert(CoprocNo >= 0 && "Coprocessor immediate must be non-negative");
2285 
2286   uint32_t CDECoprocMask = TI.getARMCDECoprocMask();
2287   bool IsCDECoproc = CoprocNo <= 7 && (CDECoprocMask & (1 << CoprocNo));
2288 
2289   if (IsCDECoproc != WantCDE)
2290     return Diag(CoprocArg->getBeginLoc(), diag::err_arm_invalid_coproc)
2291            << (int)CoprocNo << (int)WantCDE << CoprocArg->getSourceRange();
2292 
2293   return false;
2294 }
2295 
2296 bool Sema::CheckARMBuiltinExclusiveCall(unsigned BuiltinID, CallExpr *TheCall,
2297                                         unsigned MaxWidth) {
2298   assert((BuiltinID == ARM::BI__builtin_arm_ldrex ||
2299           BuiltinID == ARM::BI__builtin_arm_ldaex ||
2300           BuiltinID == ARM::BI__builtin_arm_strex ||
2301           BuiltinID == ARM::BI__builtin_arm_stlex ||
2302           BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2303           BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2304           BuiltinID == AArch64::BI__builtin_arm_strex ||
2305           BuiltinID == AArch64::BI__builtin_arm_stlex) &&
2306          "unexpected ARM builtin");
2307   bool IsLdrex = BuiltinID == ARM::BI__builtin_arm_ldrex ||
2308                  BuiltinID == ARM::BI__builtin_arm_ldaex ||
2309                  BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2310                  BuiltinID == AArch64::BI__builtin_arm_ldaex;
2311 
2312   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
2313 
2314   // Ensure that we have the proper number of arguments.
2315   if (checkArgCount(*this, TheCall, IsLdrex ? 1 : 2))
2316     return true;
2317 
2318   // Inspect the pointer argument of the atomic builtin.  This should always be
2319   // a pointer type, whose element is an integral scalar or pointer type.
2320   // Because it is a pointer type, we don't have to worry about any implicit
2321   // casts here.
2322   Expr *PointerArg = TheCall->getArg(IsLdrex ? 0 : 1);
2323   ExprResult PointerArgRes = DefaultFunctionArrayLvalueConversion(PointerArg);
2324   if (PointerArgRes.isInvalid())
2325     return true;
2326   PointerArg = PointerArgRes.get();
2327 
2328   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
2329   if (!pointerType) {
2330     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
2331         << PointerArg->getType() << PointerArg->getSourceRange();
2332     return true;
2333   }
2334 
2335   // ldrex takes a "const volatile T*" and strex takes a "volatile T*". Our next
2336   // task is to insert the appropriate casts into the AST. First work out just
2337   // what the appropriate type is.
2338   QualType ValType = pointerType->getPointeeType();
2339   QualType AddrType = ValType.getUnqualifiedType().withVolatile();
2340   if (IsLdrex)
2341     AddrType.addConst();
2342 
2343   // Issue a warning if the cast is dodgy.
2344   CastKind CastNeeded = CK_NoOp;
2345   if (!AddrType.isAtLeastAsQualifiedAs(ValType)) {
2346     CastNeeded = CK_BitCast;
2347     Diag(DRE->getBeginLoc(), diag::ext_typecheck_convert_discards_qualifiers)
2348         << PointerArg->getType() << Context.getPointerType(AddrType)
2349         << AA_Passing << PointerArg->getSourceRange();
2350   }
2351 
2352   // Finally, do the cast and replace the argument with the corrected version.
2353   AddrType = Context.getPointerType(AddrType);
2354   PointerArgRes = ImpCastExprToType(PointerArg, AddrType, CastNeeded);
2355   if (PointerArgRes.isInvalid())
2356     return true;
2357   PointerArg = PointerArgRes.get();
2358 
2359   TheCall->setArg(IsLdrex ? 0 : 1, PointerArg);
2360 
2361   // In general, we allow ints, floats and pointers to be loaded and stored.
2362   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
2363       !ValType->isBlockPointerType() && !ValType->isFloatingType()) {
2364     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intfltptr)
2365         << PointerArg->getType() << PointerArg->getSourceRange();
2366     return true;
2367   }
2368 
2369   // But ARM doesn't have instructions to deal with 128-bit versions.
2370   if (Context.getTypeSize(ValType) > MaxWidth) {
2371     assert(MaxWidth == 64 && "Diagnostic unexpectedly inaccurate");
2372     Diag(DRE->getBeginLoc(), diag::err_atomic_exclusive_builtin_pointer_size)
2373         << PointerArg->getType() << PointerArg->getSourceRange();
2374     return true;
2375   }
2376 
2377   switch (ValType.getObjCLifetime()) {
2378   case Qualifiers::OCL_None:
2379   case Qualifiers::OCL_ExplicitNone:
2380     // okay
2381     break;
2382 
2383   case Qualifiers::OCL_Weak:
2384   case Qualifiers::OCL_Strong:
2385   case Qualifiers::OCL_Autoreleasing:
2386     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
2387         << ValType << PointerArg->getSourceRange();
2388     return true;
2389   }
2390 
2391   if (IsLdrex) {
2392     TheCall->setType(ValType);
2393     return false;
2394   }
2395 
2396   // Initialize the argument to be stored.
2397   ExprResult ValArg = TheCall->getArg(0);
2398   InitializedEntity Entity = InitializedEntity::InitializeParameter(
2399       Context, ValType, /*consume*/ false);
2400   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
2401   if (ValArg.isInvalid())
2402     return true;
2403   TheCall->setArg(0, ValArg.get());
2404 
2405   // __builtin_arm_strex always returns an int. It's marked as such in the .def,
2406   // but the custom checker bypasses all default analysis.
2407   TheCall->setType(Context.IntTy);
2408   return false;
2409 }
2410 
2411 bool Sema::CheckARMBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
2412                                        CallExpr *TheCall) {
2413   if (BuiltinID == ARM::BI__builtin_arm_ldrex ||
2414       BuiltinID == ARM::BI__builtin_arm_ldaex ||
2415       BuiltinID == ARM::BI__builtin_arm_strex ||
2416       BuiltinID == ARM::BI__builtin_arm_stlex) {
2417     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 64);
2418   }
2419 
2420   if (BuiltinID == ARM::BI__builtin_arm_prefetch) {
2421     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2422       SemaBuiltinConstantArgRange(TheCall, 2, 0, 1);
2423   }
2424 
2425   if (BuiltinID == ARM::BI__builtin_arm_rsr64 ||
2426       BuiltinID == ARM::BI__builtin_arm_wsr64)
2427     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 3, false);
2428 
2429   if (BuiltinID == ARM::BI__builtin_arm_rsr ||
2430       BuiltinID == ARM::BI__builtin_arm_rsrp ||
2431       BuiltinID == ARM::BI__builtin_arm_wsr ||
2432       BuiltinID == ARM::BI__builtin_arm_wsrp)
2433     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2434 
2435   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2436     return true;
2437   if (CheckMVEBuiltinFunctionCall(BuiltinID, TheCall))
2438     return true;
2439   if (CheckCDEBuiltinFunctionCall(TI, BuiltinID, TheCall))
2440     return true;
2441 
2442   // For intrinsics which take an immediate value as part of the instruction,
2443   // range check them here.
2444   // FIXME: VFP Intrinsics should error if VFP not present.
2445   switch (BuiltinID) {
2446   default: return false;
2447   case ARM::BI__builtin_arm_ssat:
2448     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 32);
2449   case ARM::BI__builtin_arm_usat:
2450     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 31);
2451   case ARM::BI__builtin_arm_ssat16:
2452     return SemaBuiltinConstantArgRange(TheCall, 1, 1, 16);
2453   case ARM::BI__builtin_arm_usat16:
2454     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
2455   case ARM::BI__builtin_arm_vcvtr_f:
2456   case ARM::BI__builtin_arm_vcvtr_d:
2457     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
2458   case ARM::BI__builtin_arm_dmb:
2459   case ARM::BI__builtin_arm_dsb:
2460   case ARM::BI__builtin_arm_isb:
2461   case ARM::BI__builtin_arm_dbg:
2462     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15);
2463   case ARM::BI__builtin_arm_cdp:
2464   case ARM::BI__builtin_arm_cdp2:
2465   case ARM::BI__builtin_arm_mcr:
2466   case ARM::BI__builtin_arm_mcr2:
2467   case ARM::BI__builtin_arm_mrc:
2468   case ARM::BI__builtin_arm_mrc2:
2469   case ARM::BI__builtin_arm_mcrr:
2470   case ARM::BI__builtin_arm_mcrr2:
2471   case ARM::BI__builtin_arm_mrrc:
2472   case ARM::BI__builtin_arm_mrrc2:
2473   case ARM::BI__builtin_arm_ldc:
2474   case ARM::BI__builtin_arm_ldcl:
2475   case ARM::BI__builtin_arm_ldc2:
2476   case ARM::BI__builtin_arm_ldc2l:
2477   case ARM::BI__builtin_arm_stc:
2478   case ARM::BI__builtin_arm_stcl:
2479   case ARM::BI__builtin_arm_stc2:
2480   case ARM::BI__builtin_arm_stc2l:
2481     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 15) ||
2482            CheckARMCoprocessorImmediate(TI, TheCall->getArg(0),
2483                                         /*WantCDE*/ false);
2484   }
2485 }
2486 
2487 bool Sema::CheckAArch64BuiltinFunctionCall(const TargetInfo &TI,
2488                                            unsigned BuiltinID,
2489                                            CallExpr *TheCall) {
2490   if (BuiltinID == AArch64::BI__builtin_arm_ldrex ||
2491       BuiltinID == AArch64::BI__builtin_arm_ldaex ||
2492       BuiltinID == AArch64::BI__builtin_arm_strex ||
2493       BuiltinID == AArch64::BI__builtin_arm_stlex) {
2494     return CheckARMBuiltinExclusiveCall(BuiltinID, TheCall, 128);
2495   }
2496 
2497   if (BuiltinID == AArch64::BI__builtin_arm_prefetch) {
2498     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
2499       SemaBuiltinConstantArgRange(TheCall, 2, 0, 2) ||
2500       SemaBuiltinConstantArgRange(TheCall, 3, 0, 1) ||
2501       SemaBuiltinConstantArgRange(TheCall, 4, 0, 1);
2502   }
2503 
2504   if (BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
2505       BuiltinID == AArch64::BI__builtin_arm_wsr64)
2506     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2507 
2508   // Memory Tagging Extensions (MTE) Intrinsics
2509   if (BuiltinID == AArch64::BI__builtin_arm_irg ||
2510       BuiltinID == AArch64::BI__builtin_arm_addg ||
2511       BuiltinID == AArch64::BI__builtin_arm_gmi ||
2512       BuiltinID == AArch64::BI__builtin_arm_ldg ||
2513       BuiltinID == AArch64::BI__builtin_arm_stg ||
2514       BuiltinID == AArch64::BI__builtin_arm_subp) {
2515     return SemaBuiltinARMMemoryTaggingCall(BuiltinID, TheCall);
2516   }
2517 
2518   if (BuiltinID == AArch64::BI__builtin_arm_rsr ||
2519       BuiltinID == AArch64::BI__builtin_arm_rsrp ||
2520       BuiltinID == AArch64::BI__builtin_arm_wsr ||
2521       BuiltinID == AArch64::BI__builtin_arm_wsrp)
2522     return SemaBuiltinARMSpecialReg(BuiltinID, TheCall, 0, 5, true);
2523 
2524   // Only check the valid encoding range. Any constant in this range would be
2525   // converted to a register of the form S1_2_C3_C4_5. Let the hardware throw
2526   // an exception for incorrect registers. This matches MSVC behavior.
2527   if (BuiltinID == AArch64::BI_ReadStatusReg ||
2528       BuiltinID == AArch64::BI_WriteStatusReg)
2529     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 0x7fff);
2530 
2531   if (BuiltinID == AArch64::BI__getReg)
2532     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31);
2533 
2534   if (CheckNeonBuiltinFunctionCall(TI, BuiltinID, TheCall))
2535     return true;
2536 
2537   if (CheckSVEBuiltinFunctionCall(BuiltinID, TheCall))
2538     return true;
2539 
2540   // For intrinsics which take an immediate value as part of the instruction,
2541   // range check them here.
2542   unsigned i = 0, l = 0, u = 0;
2543   switch (BuiltinID) {
2544   default: return false;
2545   case AArch64::BI__builtin_arm_dmb:
2546   case AArch64::BI__builtin_arm_dsb:
2547   case AArch64::BI__builtin_arm_isb: l = 0; u = 15; break;
2548   case AArch64::BI__builtin_arm_tcancel: l = 0; u = 65535; break;
2549   }
2550 
2551   return SemaBuiltinConstantArgRange(TheCall, i, l, u + l);
2552 }
2553 
2554 static bool isValidBPFPreserveFieldInfoArg(Expr *Arg) {
2555   if (Arg->getType()->getAsPlaceholderType())
2556     return false;
2557 
2558   // The first argument needs to be a record field access.
2559   // If it is an array element access, we delay decision
2560   // to BPF backend to check whether the access is a
2561   // field access or not.
2562   return (Arg->IgnoreParens()->getObjectKind() == OK_BitField ||
2563           dyn_cast<MemberExpr>(Arg->IgnoreParens()) ||
2564           dyn_cast<ArraySubscriptExpr>(Arg->IgnoreParens()));
2565 }
2566 
2567 static bool isEltOfVectorTy(ASTContext &Context, CallExpr *Call, Sema &S,
2568                             QualType VectorTy, QualType EltTy) {
2569   QualType VectorEltTy = VectorTy->castAs<VectorType>()->getElementType();
2570   if (!Context.hasSameType(VectorEltTy, EltTy)) {
2571     S.Diag(Call->getBeginLoc(), diag::err_typecheck_call_different_arg_types)
2572         << Call->getSourceRange() << VectorEltTy << EltTy;
2573     return false;
2574   }
2575   return true;
2576 }
2577 
2578 static bool isValidBPFPreserveTypeInfoArg(Expr *Arg) {
2579   QualType ArgType = Arg->getType();
2580   if (ArgType->getAsPlaceholderType())
2581     return false;
2582 
2583   // for TYPE_EXISTENCE/TYPE_SIZEOF reloc type
2584   // format:
2585   //   1. __builtin_preserve_type_info(*(<type> *)0, flag);
2586   //   2. <type> var;
2587   //      __builtin_preserve_type_info(var, flag);
2588   if (!dyn_cast<DeclRefExpr>(Arg->IgnoreParens()) &&
2589       !dyn_cast<UnaryOperator>(Arg->IgnoreParens()))
2590     return false;
2591 
2592   // Typedef type.
2593   if (ArgType->getAs<TypedefType>())
2594     return true;
2595 
2596   // Record type or Enum type.
2597   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2598   if (const auto *RT = Ty->getAs<RecordType>()) {
2599     if (!RT->getDecl()->getDeclName().isEmpty())
2600       return true;
2601   } else if (const auto *ET = Ty->getAs<EnumType>()) {
2602     if (!ET->getDecl()->getDeclName().isEmpty())
2603       return true;
2604   }
2605 
2606   return false;
2607 }
2608 
2609 static bool isValidBPFPreserveEnumValueArg(Expr *Arg) {
2610   QualType ArgType = Arg->getType();
2611   if (ArgType->getAsPlaceholderType())
2612     return false;
2613 
2614   // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type
2615   // format:
2616   //   __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>,
2617   //                                 flag);
2618   const auto *UO = dyn_cast<UnaryOperator>(Arg->IgnoreParens());
2619   if (!UO)
2620     return false;
2621 
2622   const auto *CE = dyn_cast<CStyleCastExpr>(UO->getSubExpr());
2623   if (!CE || CE->getCastKind() != CK_IntegralToPointer)
2624     return false;
2625 
2626   // The integer must be from an EnumConstantDecl.
2627   const auto *DR = dyn_cast<DeclRefExpr>(CE->getSubExpr());
2628   if (!DR)
2629     return false;
2630 
2631   const EnumConstantDecl *Enumerator =
2632       dyn_cast<EnumConstantDecl>(DR->getDecl());
2633   if (!Enumerator)
2634     return false;
2635 
2636   // The type must be EnumType.
2637   const Type *Ty = ArgType->getUnqualifiedDesugaredType();
2638   const auto *ET = Ty->getAs<EnumType>();
2639   if (!ET)
2640     return false;
2641 
2642   // The enum value must be supported.
2643   for (auto *EDI : ET->getDecl()->enumerators()) {
2644     if (EDI == Enumerator)
2645       return true;
2646   }
2647 
2648   return false;
2649 }
2650 
2651 bool Sema::CheckBPFBuiltinFunctionCall(unsigned BuiltinID,
2652                                        CallExpr *TheCall) {
2653   assert((BuiltinID == BPF::BI__builtin_preserve_field_info ||
2654           BuiltinID == BPF::BI__builtin_btf_type_id ||
2655           BuiltinID == BPF::BI__builtin_preserve_type_info ||
2656           BuiltinID == BPF::BI__builtin_preserve_enum_value) &&
2657          "unexpected BPF builtin");
2658 
2659   if (checkArgCount(*this, TheCall, 2))
2660     return true;
2661 
2662   // The second argument needs to be a constant int
2663   Expr *Arg = TheCall->getArg(1);
2664   Optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Context);
2665   diag::kind kind;
2666   if (!Value) {
2667     if (BuiltinID == BPF::BI__builtin_preserve_field_info)
2668       kind = diag::err_preserve_field_info_not_const;
2669     else if (BuiltinID == BPF::BI__builtin_btf_type_id)
2670       kind = diag::err_btf_type_id_not_const;
2671     else if (BuiltinID == BPF::BI__builtin_preserve_type_info)
2672       kind = diag::err_preserve_type_info_not_const;
2673     else
2674       kind = diag::err_preserve_enum_value_not_const;
2675     Diag(Arg->getBeginLoc(), kind) << 2 << Arg->getSourceRange();
2676     return true;
2677   }
2678 
2679   // The first argument
2680   Arg = TheCall->getArg(0);
2681   bool InvalidArg = false;
2682   bool ReturnUnsignedInt = true;
2683   if (BuiltinID == BPF::BI__builtin_preserve_field_info) {
2684     if (!isValidBPFPreserveFieldInfoArg(Arg)) {
2685       InvalidArg = true;
2686       kind = diag::err_preserve_field_info_not_field;
2687     }
2688   } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) {
2689     if (!isValidBPFPreserveTypeInfoArg(Arg)) {
2690       InvalidArg = true;
2691       kind = diag::err_preserve_type_info_invalid;
2692     }
2693   } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) {
2694     if (!isValidBPFPreserveEnumValueArg(Arg)) {
2695       InvalidArg = true;
2696       kind = diag::err_preserve_enum_value_invalid;
2697     }
2698     ReturnUnsignedInt = false;
2699   }
2700 
2701   if (InvalidArg) {
2702     Diag(Arg->getBeginLoc(), kind) << 1 << Arg->getSourceRange();
2703     return true;
2704   }
2705 
2706   if (ReturnUnsignedInt)
2707     TheCall->setType(Context.UnsignedIntTy);
2708   else
2709     TheCall->setType(Context.UnsignedLongTy);
2710   return false;
2711 }
2712 
2713 bool Sema::CheckHexagonBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2714   struct ArgInfo {
2715     uint8_t OpNum;
2716     bool IsSigned;
2717     uint8_t BitWidth;
2718     uint8_t Align;
2719   };
2720   struct BuiltinInfo {
2721     unsigned BuiltinID;
2722     ArgInfo Infos[2];
2723   };
2724 
2725   static BuiltinInfo Infos[] = {
2726     { Hexagon::BI__builtin_circ_ldd,                  {{ 3, true,  4,  3 }} },
2727     { Hexagon::BI__builtin_circ_ldw,                  {{ 3, true,  4,  2 }} },
2728     { Hexagon::BI__builtin_circ_ldh,                  {{ 3, true,  4,  1 }} },
2729     { Hexagon::BI__builtin_circ_lduh,                 {{ 3, true,  4,  1 }} },
2730     { Hexagon::BI__builtin_circ_ldb,                  {{ 3, true,  4,  0 }} },
2731     { Hexagon::BI__builtin_circ_ldub,                 {{ 3, true,  4,  0 }} },
2732     { Hexagon::BI__builtin_circ_std,                  {{ 3, true,  4,  3 }} },
2733     { Hexagon::BI__builtin_circ_stw,                  {{ 3, true,  4,  2 }} },
2734     { Hexagon::BI__builtin_circ_sth,                  {{ 3, true,  4,  1 }} },
2735     { Hexagon::BI__builtin_circ_sthhi,                {{ 3, true,  4,  1 }} },
2736     { Hexagon::BI__builtin_circ_stb,                  {{ 3, true,  4,  0 }} },
2737 
2738     { Hexagon::BI__builtin_HEXAGON_L2_loadrub_pci,    {{ 1, true,  4,  0 }} },
2739     { Hexagon::BI__builtin_HEXAGON_L2_loadrb_pci,     {{ 1, true,  4,  0 }} },
2740     { Hexagon::BI__builtin_HEXAGON_L2_loadruh_pci,    {{ 1, true,  4,  1 }} },
2741     { Hexagon::BI__builtin_HEXAGON_L2_loadrh_pci,     {{ 1, true,  4,  1 }} },
2742     { Hexagon::BI__builtin_HEXAGON_L2_loadri_pci,     {{ 1, true,  4,  2 }} },
2743     { Hexagon::BI__builtin_HEXAGON_L2_loadrd_pci,     {{ 1, true,  4,  3 }} },
2744     { Hexagon::BI__builtin_HEXAGON_S2_storerb_pci,    {{ 1, true,  4,  0 }} },
2745     { Hexagon::BI__builtin_HEXAGON_S2_storerh_pci,    {{ 1, true,  4,  1 }} },
2746     { Hexagon::BI__builtin_HEXAGON_S2_storerf_pci,    {{ 1, true,  4,  1 }} },
2747     { Hexagon::BI__builtin_HEXAGON_S2_storeri_pci,    {{ 1, true,  4,  2 }} },
2748     { Hexagon::BI__builtin_HEXAGON_S2_storerd_pci,    {{ 1, true,  4,  3 }} },
2749 
2750     { Hexagon::BI__builtin_HEXAGON_A2_combineii,      {{ 1, true,  8,  0 }} },
2751     { Hexagon::BI__builtin_HEXAGON_A2_tfrih,          {{ 1, false, 16, 0 }} },
2752     { Hexagon::BI__builtin_HEXAGON_A2_tfril,          {{ 1, false, 16, 0 }} },
2753     { Hexagon::BI__builtin_HEXAGON_A2_tfrpi,          {{ 0, true,  8,  0 }} },
2754     { Hexagon::BI__builtin_HEXAGON_A4_bitspliti,      {{ 1, false, 5,  0 }} },
2755     { Hexagon::BI__builtin_HEXAGON_A4_cmpbeqi,        {{ 1, false, 8,  0 }} },
2756     { Hexagon::BI__builtin_HEXAGON_A4_cmpbgti,        {{ 1, true,  8,  0 }} },
2757     { Hexagon::BI__builtin_HEXAGON_A4_cround_ri,      {{ 1, false, 5,  0 }} },
2758     { Hexagon::BI__builtin_HEXAGON_A4_round_ri,       {{ 1, false, 5,  0 }} },
2759     { Hexagon::BI__builtin_HEXAGON_A4_round_ri_sat,   {{ 1, false, 5,  0 }} },
2760     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbeqi,       {{ 1, false, 8,  0 }} },
2761     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgti,       {{ 1, true,  8,  0 }} },
2762     { Hexagon::BI__builtin_HEXAGON_A4_vcmpbgtui,      {{ 1, false, 7,  0 }} },
2763     { Hexagon::BI__builtin_HEXAGON_A4_vcmpheqi,       {{ 1, true,  8,  0 }} },
2764     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgti,       {{ 1, true,  8,  0 }} },
2765     { Hexagon::BI__builtin_HEXAGON_A4_vcmphgtui,      {{ 1, false, 7,  0 }} },
2766     { Hexagon::BI__builtin_HEXAGON_A4_vcmpweqi,       {{ 1, true,  8,  0 }} },
2767     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgti,       {{ 1, true,  8,  0 }} },
2768     { Hexagon::BI__builtin_HEXAGON_A4_vcmpwgtui,      {{ 1, false, 7,  0 }} },
2769     { Hexagon::BI__builtin_HEXAGON_C2_bitsclri,       {{ 1, false, 6,  0 }} },
2770     { Hexagon::BI__builtin_HEXAGON_C2_muxii,          {{ 2, true,  8,  0 }} },
2771     { Hexagon::BI__builtin_HEXAGON_C4_nbitsclri,      {{ 1, false, 6,  0 }} },
2772     { Hexagon::BI__builtin_HEXAGON_F2_dfclass,        {{ 1, false, 5,  0 }} },
2773     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_n,        {{ 0, false, 10, 0 }} },
2774     { Hexagon::BI__builtin_HEXAGON_F2_dfimm_p,        {{ 0, false, 10, 0 }} },
2775     { Hexagon::BI__builtin_HEXAGON_F2_sfclass,        {{ 1, false, 5,  0 }} },
2776     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_n,        {{ 0, false, 10, 0 }} },
2777     { Hexagon::BI__builtin_HEXAGON_F2_sfimm_p,        {{ 0, false, 10, 0 }} },
2778     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addi,     {{ 2, false, 6,  0 }} },
2779     { Hexagon::BI__builtin_HEXAGON_M4_mpyri_addr_u2,  {{ 1, false, 6,  2 }} },
2780     { Hexagon::BI__builtin_HEXAGON_S2_addasl_rrri,    {{ 2, false, 3,  0 }} },
2781     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_acc,    {{ 2, false, 6,  0 }} },
2782     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_and,    {{ 2, false, 6,  0 }} },
2783     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p,        {{ 1, false, 6,  0 }} },
2784     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_nac,    {{ 2, false, 6,  0 }} },
2785     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_or,     {{ 2, false, 6,  0 }} },
2786     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_p_xacc,   {{ 2, false, 6,  0 }} },
2787     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_acc,    {{ 2, false, 5,  0 }} },
2788     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_and,    {{ 2, false, 5,  0 }} },
2789     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r,        {{ 1, false, 5,  0 }} },
2790     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_nac,    {{ 2, false, 5,  0 }} },
2791     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_or,     {{ 2, false, 5,  0 }} },
2792     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_sat,    {{ 1, false, 5,  0 }} },
2793     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_r_xacc,   {{ 2, false, 5,  0 }} },
2794     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vh,       {{ 1, false, 4,  0 }} },
2795     { Hexagon::BI__builtin_HEXAGON_S2_asl_i_vw,       {{ 1, false, 5,  0 }} },
2796     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_acc,    {{ 2, false, 6,  0 }} },
2797     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_and,    {{ 2, false, 6,  0 }} },
2798     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p,        {{ 1, false, 6,  0 }} },
2799     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_nac,    {{ 2, false, 6,  0 }} },
2800     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_or,     {{ 2, false, 6,  0 }} },
2801     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd_goodsyntax,
2802                                                       {{ 1, false, 6,  0 }} },
2803     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_p_rnd,    {{ 1, false, 6,  0 }} },
2804     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_acc,    {{ 2, false, 5,  0 }} },
2805     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_and,    {{ 2, false, 5,  0 }} },
2806     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r,        {{ 1, false, 5,  0 }} },
2807     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_nac,    {{ 2, false, 5,  0 }} },
2808     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_or,     {{ 2, false, 5,  0 }} },
2809     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd_goodsyntax,
2810                                                       {{ 1, false, 5,  0 }} },
2811     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_r_rnd,    {{ 1, false, 5,  0 }} },
2812     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_svw_trun, {{ 1, false, 5,  0 }} },
2813     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vh,       {{ 1, false, 4,  0 }} },
2814     { Hexagon::BI__builtin_HEXAGON_S2_asr_i_vw,       {{ 1, false, 5,  0 }} },
2815     { Hexagon::BI__builtin_HEXAGON_S2_clrbit_i,       {{ 1, false, 5,  0 }} },
2816     { Hexagon::BI__builtin_HEXAGON_S2_extractu,       {{ 1, false, 5,  0 },
2817                                                        { 2, false, 5,  0 }} },
2818     { Hexagon::BI__builtin_HEXAGON_S2_extractup,      {{ 1, false, 6,  0 },
2819                                                        { 2, false, 6,  0 }} },
2820     { Hexagon::BI__builtin_HEXAGON_S2_insert,         {{ 2, false, 5,  0 },
2821                                                        { 3, false, 5,  0 }} },
2822     { Hexagon::BI__builtin_HEXAGON_S2_insertp,        {{ 2, false, 6,  0 },
2823                                                        { 3, false, 6,  0 }} },
2824     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_acc,    {{ 2, false, 6,  0 }} },
2825     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_and,    {{ 2, false, 6,  0 }} },
2826     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p,        {{ 1, false, 6,  0 }} },
2827     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_nac,    {{ 2, false, 6,  0 }} },
2828     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_or,     {{ 2, false, 6,  0 }} },
2829     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_p_xacc,   {{ 2, false, 6,  0 }} },
2830     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_acc,    {{ 2, false, 5,  0 }} },
2831     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_and,    {{ 2, false, 5,  0 }} },
2832     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r,        {{ 1, false, 5,  0 }} },
2833     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_nac,    {{ 2, false, 5,  0 }} },
2834     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_or,     {{ 2, false, 5,  0 }} },
2835     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_r_xacc,   {{ 2, false, 5,  0 }} },
2836     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vh,       {{ 1, false, 4,  0 }} },
2837     { Hexagon::BI__builtin_HEXAGON_S2_lsr_i_vw,       {{ 1, false, 5,  0 }} },
2838     { Hexagon::BI__builtin_HEXAGON_S2_setbit_i,       {{ 1, false, 5,  0 }} },
2839     { Hexagon::BI__builtin_HEXAGON_S2_tableidxb_goodsyntax,
2840                                                       {{ 2, false, 4,  0 },
2841                                                        { 3, false, 5,  0 }} },
2842     { Hexagon::BI__builtin_HEXAGON_S2_tableidxd_goodsyntax,
2843                                                       {{ 2, false, 4,  0 },
2844                                                        { 3, false, 5,  0 }} },
2845     { Hexagon::BI__builtin_HEXAGON_S2_tableidxh_goodsyntax,
2846                                                       {{ 2, false, 4,  0 },
2847                                                        { 3, false, 5,  0 }} },
2848     { Hexagon::BI__builtin_HEXAGON_S2_tableidxw_goodsyntax,
2849                                                       {{ 2, false, 4,  0 },
2850                                                        { 3, false, 5,  0 }} },
2851     { Hexagon::BI__builtin_HEXAGON_S2_togglebit_i,    {{ 1, false, 5,  0 }} },
2852     { Hexagon::BI__builtin_HEXAGON_S2_tstbit_i,       {{ 1, false, 5,  0 }} },
2853     { Hexagon::BI__builtin_HEXAGON_S2_valignib,       {{ 2, false, 3,  0 }} },
2854     { Hexagon::BI__builtin_HEXAGON_S2_vspliceib,      {{ 2, false, 3,  0 }} },
2855     { Hexagon::BI__builtin_HEXAGON_S4_addi_asl_ri,    {{ 2, false, 5,  0 }} },
2856     { Hexagon::BI__builtin_HEXAGON_S4_addi_lsr_ri,    {{ 2, false, 5,  0 }} },
2857     { Hexagon::BI__builtin_HEXAGON_S4_andi_asl_ri,    {{ 2, false, 5,  0 }} },
2858     { Hexagon::BI__builtin_HEXAGON_S4_andi_lsr_ri,    {{ 2, false, 5,  0 }} },
2859     { Hexagon::BI__builtin_HEXAGON_S4_clbaddi,        {{ 1, true , 6,  0 }} },
2860     { Hexagon::BI__builtin_HEXAGON_S4_clbpaddi,       {{ 1, true,  6,  0 }} },
2861     { Hexagon::BI__builtin_HEXAGON_S4_extract,        {{ 1, false, 5,  0 },
2862                                                        { 2, false, 5,  0 }} },
2863     { Hexagon::BI__builtin_HEXAGON_S4_extractp,       {{ 1, false, 6,  0 },
2864                                                        { 2, false, 6,  0 }} },
2865     { Hexagon::BI__builtin_HEXAGON_S4_lsli,           {{ 0, true,  6,  0 }} },
2866     { Hexagon::BI__builtin_HEXAGON_S4_ntstbit_i,      {{ 1, false, 5,  0 }} },
2867     { Hexagon::BI__builtin_HEXAGON_S4_ori_asl_ri,     {{ 2, false, 5,  0 }} },
2868     { Hexagon::BI__builtin_HEXAGON_S4_ori_lsr_ri,     {{ 2, false, 5,  0 }} },
2869     { Hexagon::BI__builtin_HEXAGON_S4_subi_asl_ri,    {{ 2, false, 5,  0 }} },
2870     { Hexagon::BI__builtin_HEXAGON_S4_subi_lsr_ri,    {{ 2, false, 5,  0 }} },
2871     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate_acc,  {{ 3, false, 2,  0 }} },
2872     { Hexagon::BI__builtin_HEXAGON_S4_vrcrotate,      {{ 2, false, 2,  0 }} },
2873     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_rnd_sat_goodsyntax,
2874                                                       {{ 1, false, 4,  0 }} },
2875     { Hexagon::BI__builtin_HEXAGON_S5_asrhub_sat,     {{ 1, false, 4,  0 }} },
2876     { Hexagon::BI__builtin_HEXAGON_S5_vasrhrnd_goodsyntax,
2877                                                       {{ 1, false, 4,  0 }} },
2878     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p,        {{ 1, false, 6,  0 }} },
2879     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_acc,    {{ 2, false, 6,  0 }} },
2880     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_and,    {{ 2, false, 6,  0 }} },
2881     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_nac,    {{ 2, false, 6,  0 }} },
2882     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_or,     {{ 2, false, 6,  0 }} },
2883     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_p_xacc,   {{ 2, false, 6,  0 }} },
2884     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r,        {{ 1, false, 5,  0 }} },
2885     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_acc,    {{ 2, false, 5,  0 }} },
2886     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_and,    {{ 2, false, 5,  0 }} },
2887     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_nac,    {{ 2, false, 5,  0 }} },
2888     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_or,     {{ 2, false, 5,  0 }} },
2889     { Hexagon::BI__builtin_HEXAGON_S6_rol_i_r_xacc,   {{ 2, false, 5,  0 }} },
2890     { Hexagon::BI__builtin_HEXAGON_V6_valignbi,       {{ 2, false, 3,  0 }} },
2891     { Hexagon::BI__builtin_HEXAGON_V6_valignbi_128B,  {{ 2, false, 3,  0 }} },
2892     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi,      {{ 2, false, 3,  0 }} },
2893     { Hexagon::BI__builtin_HEXAGON_V6_vlalignbi_128B, {{ 2, false, 3,  0 }} },
2894     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi,      {{ 2, false, 1,  0 }} },
2895     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_128B, {{ 2, false, 1,  0 }} },
2896     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc,  {{ 3, false, 1,  0 }} },
2897     { Hexagon::BI__builtin_HEXAGON_V6_vrmpybusi_acc_128B,
2898                                                       {{ 3, false, 1,  0 }} },
2899     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi,       {{ 2, false, 1,  0 }} },
2900     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_128B,  {{ 2, false, 1,  0 }} },
2901     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc,   {{ 3, false, 1,  0 }} },
2902     { Hexagon::BI__builtin_HEXAGON_V6_vrmpyubi_acc_128B,
2903                                                       {{ 3, false, 1,  0 }} },
2904     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi,       {{ 2, false, 1,  0 }} },
2905     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_128B,  {{ 2, false, 1,  0 }} },
2906     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc,   {{ 3, false, 1,  0 }} },
2907     { Hexagon::BI__builtin_HEXAGON_V6_vrsadubi_acc_128B,
2908                                                       {{ 3, false, 1,  0 }} },
2909   };
2910 
2911   // Use a dynamically initialized static to sort the table exactly once on
2912   // first run.
2913   static const bool SortOnce =
2914       (llvm::sort(Infos,
2915                  [](const BuiltinInfo &LHS, const BuiltinInfo &RHS) {
2916                    return LHS.BuiltinID < RHS.BuiltinID;
2917                  }),
2918        true);
2919   (void)SortOnce;
2920 
2921   const BuiltinInfo *F = llvm::partition_point(
2922       Infos, [=](const BuiltinInfo &BI) { return BI.BuiltinID < BuiltinID; });
2923   if (F == std::end(Infos) || F->BuiltinID != BuiltinID)
2924     return false;
2925 
2926   bool Error = false;
2927 
2928   for (const ArgInfo &A : F->Infos) {
2929     // Ignore empty ArgInfo elements.
2930     if (A.BitWidth == 0)
2931       continue;
2932 
2933     int32_t Min = A.IsSigned ? -(1 << (A.BitWidth - 1)) : 0;
2934     int32_t Max = (1 << (A.IsSigned ? A.BitWidth - 1 : A.BitWidth)) - 1;
2935     if (!A.Align) {
2936       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max);
2937     } else {
2938       unsigned M = 1 << A.Align;
2939       Min *= M;
2940       Max *= M;
2941       Error |= SemaBuiltinConstantArgRange(TheCall, A.OpNum, Min, Max) |
2942                SemaBuiltinConstantArgMultiple(TheCall, A.OpNum, M);
2943     }
2944   }
2945   return Error;
2946 }
2947 
2948 bool Sema::CheckHexagonBuiltinFunctionCall(unsigned BuiltinID,
2949                                            CallExpr *TheCall) {
2950   return CheckHexagonBuiltinArgument(BuiltinID, TheCall);
2951 }
2952 
2953 bool Sema::CheckMipsBuiltinFunctionCall(const TargetInfo &TI,
2954                                         unsigned BuiltinID, CallExpr *TheCall) {
2955   return CheckMipsBuiltinCpu(TI, BuiltinID, TheCall) ||
2956          CheckMipsBuiltinArgument(BuiltinID, TheCall);
2957 }
2958 
2959 bool Sema::CheckMipsBuiltinCpu(const TargetInfo &TI, unsigned BuiltinID,
2960                                CallExpr *TheCall) {
2961 
2962   if (Mips::BI__builtin_mips_addu_qb <= BuiltinID &&
2963       BuiltinID <= Mips::BI__builtin_mips_lwx) {
2964     if (!TI.hasFeature("dsp"))
2965       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_dsp);
2966   }
2967 
2968   if (Mips::BI__builtin_mips_absq_s_qb <= BuiltinID &&
2969       BuiltinID <= Mips::BI__builtin_mips_subuh_r_qb) {
2970     if (!TI.hasFeature("dspr2"))
2971       return Diag(TheCall->getBeginLoc(),
2972                   diag::err_mips_builtin_requires_dspr2);
2973   }
2974 
2975   if (Mips::BI__builtin_msa_add_a_b <= BuiltinID &&
2976       BuiltinID <= Mips::BI__builtin_msa_xori_b) {
2977     if (!TI.hasFeature("msa"))
2978       return Diag(TheCall->getBeginLoc(), diag::err_mips_builtin_requires_msa);
2979   }
2980 
2981   return false;
2982 }
2983 
2984 // CheckMipsBuiltinArgument - Checks the constant value passed to the
2985 // intrinsic is correct. The switch statement is ordered by DSP, MSA. The
2986 // ordering for DSP is unspecified. MSA is ordered by the data format used
2987 // by the underlying instruction i.e., df/m, df/n and then by size.
2988 //
2989 // FIXME: The size tests here should instead be tablegen'd along with the
2990 //        definitions from include/clang/Basic/BuiltinsMips.def.
2991 // FIXME: GCC is strict on signedness for some of these intrinsics, we should
2992 //        be too.
2993 bool Sema::CheckMipsBuiltinArgument(unsigned BuiltinID, CallExpr *TheCall) {
2994   unsigned i = 0, l = 0, u = 0, m = 0;
2995   switch (BuiltinID) {
2996   default: return false;
2997   case Mips::BI__builtin_mips_wrdsp: i = 1; l = 0; u = 63; break;
2998   case Mips::BI__builtin_mips_rddsp: i = 0; l = 0; u = 63; break;
2999   case Mips::BI__builtin_mips_append: i = 2; l = 0; u = 31; break;
3000   case Mips::BI__builtin_mips_balign: i = 2; l = 0; u = 3; break;
3001   case Mips::BI__builtin_mips_precr_sra_ph_w: i = 2; l = 0; u = 31; break;
3002   case Mips::BI__builtin_mips_precr_sra_r_ph_w: i = 2; l = 0; u = 31; break;
3003   case Mips::BI__builtin_mips_prepend: i = 2; l = 0; u = 31; break;
3004   // MSA intrinsics. Instructions (which the intrinsics maps to) which use the
3005   // df/m field.
3006   // These intrinsics take an unsigned 3 bit immediate.
3007   case Mips::BI__builtin_msa_bclri_b:
3008   case Mips::BI__builtin_msa_bnegi_b:
3009   case Mips::BI__builtin_msa_bseti_b:
3010   case Mips::BI__builtin_msa_sat_s_b:
3011   case Mips::BI__builtin_msa_sat_u_b:
3012   case Mips::BI__builtin_msa_slli_b:
3013   case Mips::BI__builtin_msa_srai_b:
3014   case Mips::BI__builtin_msa_srari_b:
3015   case Mips::BI__builtin_msa_srli_b:
3016   case Mips::BI__builtin_msa_srlri_b: i = 1; l = 0; u = 7; break;
3017   case Mips::BI__builtin_msa_binsli_b:
3018   case Mips::BI__builtin_msa_binsri_b: i = 2; l = 0; u = 7; break;
3019   // These intrinsics take an unsigned 4 bit immediate.
3020   case Mips::BI__builtin_msa_bclri_h:
3021   case Mips::BI__builtin_msa_bnegi_h:
3022   case Mips::BI__builtin_msa_bseti_h:
3023   case Mips::BI__builtin_msa_sat_s_h:
3024   case Mips::BI__builtin_msa_sat_u_h:
3025   case Mips::BI__builtin_msa_slli_h:
3026   case Mips::BI__builtin_msa_srai_h:
3027   case Mips::BI__builtin_msa_srari_h:
3028   case Mips::BI__builtin_msa_srli_h:
3029   case Mips::BI__builtin_msa_srlri_h: i = 1; l = 0; u = 15; break;
3030   case Mips::BI__builtin_msa_binsli_h:
3031   case Mips::BI__builtin_msa_binsri_h: i = 2; l = 0; u = 15; break;
3032   // These intrinsics take an unsigned 5 bit immediate.
3033   // The first block of intrinsics actually have an unsigned 5 bit field,
3034   // not a df/n field.
3035   case Mips::BI__builtin_msa_cfcmsa:
3036   case Mips::BI__builtin_msa_ctcmsa: i = 0; l = 0; u = 31; break;
3037   case Mips::BI__builtin_msa_clei_u_b:
3038   case Mips::BI__builtin_msa_clei_u_h:
3039   case Mips::BI__builtin_msa_clei_u_w:
3040   case Mips::BI__builtin_msa_clei_u_d:
3041   case Mips::BI__builtin_msa_clti_u_b:
3042   case Mips::BI__builtin_msa_clti_u_h:
3043   case Mips::BI__builtin_msa_clti_u_w:
3044   case Mips::BI__builtin_msa_clti_u_d:
3045   case Mips::BI__builtin_msa_maxi_u_b:
3046   case Mips::BI__builtin_msa_maxi_u_h:
3047   case Mips::BI__builtin_msa_maxi_u_w:
3048   case Mips::BI__builtin_msa_maxi_u_d:
3049   case Mips::BI__builtin_msa_mini_u_b:
3050   case Mips::BI__builtin_msa_mini_u_h:
3051   case Mips::BI__builtin_msa_mini_u_w:
3052   case Mips::BI__builtin_msa_mini_u_d:
3053   case Mips::BI__builtin_msa_addvi_b:
3054   case Mips::BI__builtin_msa_addvi_h:
3055   case Mips::BI__builtin_msa_addvi_w:
3056   case Mips::BI__builtin_msa_addvi_d:
3057   case Mips::BI__builtin_msa_bclri_w:
3058   case Mips::BI__builtin_msa_bnegi_w:
3059   case Mips::BI__builtin_msa_bseti_w:
3060   case Mips::BI__builtin_msa_sat_s_w:
3061   case Mips::BI__builtin_msa_sat_u_w:
3062   case Mips::BI__builtin_msa_slli_w:
3063   case Mips::BI__builtin_msa_srai_w:
3064   case Mips::BI__builtin_msa_srari_w:
3065   case Mips::BI__builtin_msa_srli_w:
3066   case Mips::BI__builtin_msa_srlri_w:
3067   case Mips::BI__builtin_msa_subvi_b:
3068   case Mips::BI__builtin_msa_subvi_h:
3069   case Mips::BI__builtin_msa_subvi_w:
3070   case Mips::BI__builtin_msa_subvi_d: i = 1; l = 0; u = 31; break;
3071   case Mips::BI__builtin_msa_binsli_w:
3072   case Mips::BI__builtin_msa_binsri_w: i = 2; l = 0; u = 31; break;
3073   // These intrinsics take an unsigned 6 bit immediate.
3074   case Mips::BI__builtin_msa_bclri_d:
3075   case Mips::BI__builtin_msa_bnegi_d:
3076   case Mips::BI__builtin_msa_bseti_d:
3077   case Mips::BI__builtin_msa_sat_s_d:
3078   case Mips::BI__builtin_msa_sat_u_d:
3079   case Mips::BI__builtin_msa_slli_d:
3080   case Mips::BI__builtin_msa_srai_d:
3081   case Mips::BI__builtin_msa_srari_d:
3082   case Mips::BI__builtin_msa_srli_d:
3083   case Mips::BI__builtin_msa_srlri_d: i = 1; l = 0; u = 63; break;
3084   case Mips::BI__builtin_msa_binsli_d:
3085   case Mips::BI__builtin_msa_binsri_d: i = 2; l = 0; u = 63; break;
3086   // These intrinsics take a signed 5 bit immediate.
3087   case Mips::BI__builtin_msa_ceqi_b:
3088   case Mips::BI__builtin_msa_ceqi_h:
3089   case Mips::BI__builtin_msa_ceqi_w:
3090   case Mips::BI__builtin_msa_ceqi_d:
3091   case Mips::BI__builtin_msa_clti_s_b:
3092   case Mips::BI__builtin_msa_clti_s_h:
3093   case Mips::BI__builtin_msa_clti_s_w:
3094   case Mips::BI__builtin_msa_clti_s_d:
3095   case Mips::BI__builtin_msa_clei_s_b:
3096   case Mips::BI__builtin_msa_clei_s_h:
3097   case Mips::BI__builtin_msa_clei_s_w:
3098   case Mips::BI__builtin_msa_clei_s_d:
3099   case Mips::BI__builtin_msa_maxi_s_b:
3100   case Mips::BI__builtin_msa_maxi_s_h:
3101   case Mips::BI__builtin_msa_maxi_s_w:
3102   case Mips::BI__builtin_msa_maxi_s_d:
3103   case Mips::BI__builtin_msa_mini_s_b:
3104   case Mips::BI__builtin_msa_mini_s_h:
3105   case Mips::BI__builtin_msa_mini_s_w:
3106   case Mips::BI__builtin_msa_mini_s_d: i = 1; l = -16; u = 15; break;
3107   // These intrinsics take an unsigned 8 bit immediate.
3108   case Mips::BI__builtin_msa_andi_b:
3109   case Mips::BI__builtin_msa_nori_b:
3110   case Mips::BI__builtin_msa_ori_b:
3111   case Mips::BI__builtin_msa_shf_b:
3112   case Mips::BI__builtin_msa_shf_h:
3113   case Mips::BI__builtin_msa_shf_w:
3114   case Mips::BI__builtin_msa_xori_b: i = 1; l = 0; u = 255; break;
3115   case Mips::BI__builtin_msa_bseli_b:
3116   case Mips::BI__builtin_msa_bmnzi_b:
3117   case Mips::BI__builtin_msa_bmzi_b: i = 2; l = 0; u = 255; break;
3118   // df/n format
3119   // These intrinsics take an unsigned 4 bit immediate.
3120   case Mips::BI__builtin_msa_copy_s_b:
3121   case Mips::BI__builtin_msa_copy_u_b:
3122   case Mips::BI__builtin_msa_insve_b:
3123   case Mips::BI__builtin_msa_splati_b: i = 1; l = 0; u = 15; break;
3124   case Mips::BI__builtin_msa_sldi_b: i = 2; l = 0; u = 15; break;
3125   // These intrinsics take an unsigned 3 bit immediate.
3126   case Mips::BI__builtin_msa_copy_s_h:
3127   case Mips::BI__builtin_msa_copy_u_h:
3128   case Mips::BI__builtin_msa_insve_h:
3129   case Mips::BI__builtin_msa_splati_h: i = 1; l = 0; u = 7; break;
3130   case Mips::BI__builtin_msa_sldi_h: i = 2; l = 0; u = 7; break;
3131   // These intrinsics take an unsigned 2 bit immediate.
3132   case Mips::BI__builtin_msa_copy_s_w:
3133   case Mips::BI__builtin_msa_copy_u_w:
3134   case Mips::BI__builtin_msa_insve_w:
3135   case Mips::BI__builtin_msa_splati_w: i = 1; l = 0; u = 3; break;
3136   case Mips::BI__builtin_msa_sldi_w: i = 2; l = 0; u = 3; break;
3137   // These intrinsics take an unsigned 1 bit immediate.
3138   case Mips::BI__builtin_msa_copy_s_d:
3139   case Mips::BI__builtin_msa_copy_u_d:
3140   case Mips::BI__builtin_msa_insve_d:
3141   case Mips::BI__builtin_msa_splati_d: i = 1; l = 0; u = 1; break;
3142   case Mips::BI__builtin_msa_sldi_d: i = 2; l = 0; u = 1; break;
3143   // Memory offsets and immediate loads.
3144   // These intrinsics take a signed 10 bit immediate.
3145   case Mips::BI__builtin_msa_ldi_b: i = 0; l = -128; u = 255; break;
3146   case Mips::BI__builtin_msa_ldi_h:
3147   case Mips::BI__builtin_msa_ldi_w:
3148   case Mips::BI__builtin_msa_ldi_d: i = 0; l = -512; u = 511; break;
3149   case Mips::BI__builtin_msa_ld_b: i = 1; l = -512; u = 511; m = 1; break;
3150   case Mips::BI__builtin_msa_ld_h: i = 1; l = -1024; u = 1022; m = 2; break;
3151   case Mips::BI__builtin_msa_ld_w: i = 1; l = -2048; u = 2044; m = 4; break;
3152   case Mips::BI__builtin_msa_ld_d: i = 1; l = -4096; u = 4088; m = 8; break;
3153   case Mips::BI__builtin_msa_ldr_d: i = 1; l = -4096; u = 4088; m = 8; break;
3154   case Mips::BI__builtin_msa_ldr_w: i = 1; l = -2048; u = 2044; m = 4; break;
3155   case Mips::BI__builtin_msa_st_b: i = 2; l = -512; u = 511; m = 1; break;
3156   case Mips::BI__builtin_msa_st_h: i = 2; l = -1024; u = 1022; m = 2; break;
3157   case Mips::BI__builtin_msa_st_w: i = 2; l = -2048; u = 2044; m = 4; break;
3158   case Mips::BI__builtin_msa_st_d: i = 2; l = -4096; u = 4088; m = 8; break;
3159   case Mips::BI__builtin_msa_str_d: i = 2; l = -4096; u = 4088; m = 8; break;
3160   case Mips::BI__builtin_msa_str_w: i = 2; l = -2048; u = 2044; m = 4; break;
3161   }
3162 
3163   if (!m)
3164     return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3165 
3166   return SemaBuiltinConstantArgRange(TheCall, i, l, u) ||
3167          SemaBuiltinConstantArgMultiple(TheCall, i, m);
3168 }
3169 
3170 /// DecodePPCMMATypeFromStr - This decodes one PPC MMA type descriptor from Str,
3171 /// advancing the pointer over the consumed characters. The decoded type is
3172 /// returned. If the decoded type represents a constant integer with a
3173 /// constraint on its value then Mask is set to that value. The type descriptors
3174 /// used in Str are specific to PPC MMA builtins and are documented in the file
3175 /// defining the PPC builtins.
3176 static QualType DecodePPCMMATypeFromStr(ASTContext &Context, const char *&Str,
3177                                         unsigned &Mask) {
3178   bool RequireICE = false;
3179   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
3180   switch (*Str++) {
3181   case 'V':
3182     return Context.getVectorType(Context.UnsignedCharTy, 16,
3183                                  VectorType::VectorKind::AltiVecVector);
3184   case 'i': {
3185     char *End;
3186     unsigned size = strtoul(Str, &End, 10);
3187     assert(End != Str && "Missing constant parameter constraint");
3188     Str = End;
3189     Mask = size;
3190     return Context.IntTy;
3191   }
3192   case 'W': {
3193     char *End;
3194     unsigned size = strtoul(Str, &End, 10);
3195     assert(End != Str && "Missing PowerPC MMA type size");
3196     Str = End;
3197     QualType Type;
3198     switch (size) {
3199   #define PPC_MMA_VECTOR_TYPE(typeName, Id, size) \
3200     case size: Type = Context.Id##Ty; break;
3201   #include "clang/Basic/PPCTypes.def"
3202     default: llvm_unreachable("Invalid PowerPC MMA vector type");
3203     }
3204     bool CheckVectorArgs = false;
3205     while (!CheckVectorArgs) {
3206       switch (*Str++) {
3207       case '*':
3208         Type = Context.getPointerType(Type);
3209         break;
3210       case 'C':
3211         Type = Type.withConst();
3212         break;
3213       default:
3214         CheckVectorArgs = true;
3215         --Str;
3216         break;
3217       }
3218     }
3219     return Type;
3220   }
3221   default:
3222     return Context.DecodeTypeStr(--Str, Context, Error, RequireICE, true);
3223   }
3224 }
3225 
3226 bool Sema::CheckPPCBuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3227                                        CallExpr *TheCall) {
3228   unsigned i = 0, l = 0, u = 0;
3229   bool Is64BitBltin = BuiltinID == PPC::BI__builtin_divde ||
3230                       BuiltinID == PPC::BI__builtin_divdeu ||
3231                       BuiltinID == PPC::BI__builtin_bpermd;
3232   bool IsTarget64Bit = TI.getTypeWidth(TI.getIntPtrType()) == 64;
3233   bool IsBltinExtDiv = BuiltinID == PPC::BI__builtin_divwe ||
3234                        BuiltinID == PPC::BI__builtin_divweu ||
3235                        BuiltinID == PPC::BI__builtin_divde ||
3236                        BuiltinID == PPC::BI__builtin_divdeu;
3237 
3238   if (Is64BitBltin && !IsTarget64Bit)
3239     return Diag(TheCall->getBeginLoc(), diag::err_64_bit_builtin_32_bit_tgt)
3240            << TheCall->getSourceRange();
3241 
3242   if ((IsBltinExtDiv && !TI.hasFeature("extdiv")) ||
3243       (BuiltinID == PPC::BI__builtin_bpermd && !TI.hasFeature("bpermd")))
3244     return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3245            << TheCall->getSourceRange();
3246 
3247   auto SemaVSXCheck = [&](CallExpr *TheCall) -> bool {
3248     if (!TI.hasFeature("vsx"))
3249       return Diag(TheCall->getBeginLoc(), diag::err_ppc_builtin_only_on_pwr7)
3250              << TheCall->getSourceRange();
3251     return false;
3252   };
3253 
3254   switch (BuiltinID) {
3255   default: return false;
3256   case PPC::BI__builtin_altivec_crypto_vshasigmaw:
3257   case PPC::BI__builtin_altivec_crypto_vshasigmad:
3258     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 1) ||
3259            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3260   case PPC::BI__builtin_altivec_dss:
3261     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 3);
3262   case PPC::BI__builtin_tbegin:
3263   case PPC::BI__builtin_tend: i = 0; l = 0; u = 1; break;
3264   case PPC::BI__builtin_tsr: i = 0; l = 0; u = 7; break;
3265   case PPC::BI__builtin_tabortwc:
3266   case PPC::BI__builtin_tabortdc: i = 0; l = 0; u = 31; break;
3267   case PPC::BI__builtin_tabortwci:
3268   case PPC::BI__builtin_tabortdci:
3269     return SemaBuiltinConstantArgRange(TheCall, 0, 0, 31) ||
3270            SemaBuiltinConstantArgRange(TheCall, 2, 0, 31);
3271   case PPC::BI__builtin_altivec_dst:
3272   case PPC::BI__builtin_altivec_dstt:
3273   case PPC::BI__builtin_altivec_dstst:
3274   case PPC::BI__builtin_altivec_dststt:
3275     return SemaBuiltinConstantArgRange(TheCall, 2, 0, 3);
3276   case PPC::BI__builtin_vsx_xxpermdi:
3277   case PPC::BI__builtin_vsx_xxsldwi:
3278     return SemaBuiltinVSX(TheCall);
3279   case PPC::BI__builtin_unpack_vector_int128:
3280     return SemaVSXCheck(TheCall) ||
3281            SemaBuiltinConstantArgRange(TheCall, 1, 0, 1);
3282   case PPC::BI__builtin_pack_vector_int128:
3283     return SemaVSXCheck(TheCall);
3284   case PPC::BI__builtin_altivec_vgnb:
3285      return SemaBuiltinConstantArgRange(TheCall, 1, 2, 7);
3286   case PPC::BI__builtin_altivec_vec_replace_elt:
3287   case PPC::BI__builtin_altivec_vec_replace_unaligned: {
3288     QualType VecTy = TheCall->getArg(0)->getType();
3289     QualType EltTy = TheCall->getArg(1)->getType();
3290     unsigned Width = Context.getIntWidth(EltTy);
3291     return SemaBuiltinConstantArgRange(TheCall, 2, 0, Width == 32 ? 12 : 8) ||
3292            !isEltOfVectorTy(Context, TheCall, *this, VecTy, EltTy);
3293   }
3294   case PPC::BI__builtin_vsx_xxeval:
3295      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 255);
3296   case PPC::BI__builtin_altivec_vsldbi:
3297      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3298   case PPC::BI__builtin_altivec_vsrdbi:
3299      return SemaBuiltinConstantArgRange(TheCall, 2, 0, 7);
3300   case PPC::BI__builtin_vsx_xxpermx:
3301      return SemaBuiltinConstantArgRange(TheCall, 3, 0, 7);
3302 #define MMA_BUILTIN(Name, Types, Acc) \
3303   case PPC::BI__builtin_mma_##Name: \
3304     return SemaBuiltinPPCMMACall(TheCall, Types);
3305 #include "clang/Basic/BuiltinsPPC.def"
3306   }
3307   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3308 }
3309 
3310 bool Sema::CheckAMDGCNBuiltinFunctionCall(unsigned BuiltinID,
3311                                           CallExpr *TheCall) {
3312   // position of memory order and scope arguments in the builtin
3313   unsigned OrderIndex, ScopeIndex;
3314   switch (BuiltinID) {
3315   case AMDGPU::BI__builtin_amdgcn_atomic_inc32:
3316   case AMDGPU::BI__builtin_amdgcn_atomic_inc64:
3317   case AMDGPU::BI__builtin_amdgcn_atomic_dec32:
3318   case AMDGPU::BI__builtin_amdgcn_atomic_dec64:
3319     OrderIndex = 2;
3320     ScopeIndex = 3;
3321     break;
3322   case AMDGPU::BI__builtin_amdgcn_fence:
3323     OrderIndex = 0;
3324     ScopeIndex = 1;
3325     break;
3326   default:
3327     return false;
3328   }
3329 
3330   ExprResult Arg = TheCall->getArg(OrderIndex);
3331   auto ArgExpr = Arg.get();
3332   Expr::EvalResult ArgResult;
3333 
3334   if (!ArgExpr->EvaluateAsInt(ArgResult, Context))
3335     return Diag(ArgExpr->getExprLoc(), diag::err_typecheck_expect_int)
3336            << ArgExpr->getType();
3337   int ord = ArgResult.Val.getInt().getZExtValue();
3338 
3339   // Check valididty of memory ordering as per C11 / C++11's memody model.
3340   switch (static_cast<llvm::AtomicOrderingCABI>(ord)) {
3341   case llvm::AtomicOrderingCABI::acquire:
3342   case llvm::AtomicOrderingCABI::release:
3343   case llvm::AtomicOrderingCABI::acq_rel:
3344   case llvm::AtomicOrderingCABI::seq_cst:
3345     break;
3346   default: {
3347     return Diag(ArgExpr->getBeginLoc(),
3348                 diag::warn_atomic_op_has_invalid_memory_order)
3349            << ArgExpr->getSourceRange();
3350   }
3351   }
3352 
3353   Arg = TheCall->getArg(ScopeIndex);
3354   ArgExpr = Arg.get();
3355   Expr::EvalResult ArgResult1;
3356   // Check that sync scope is a constant literal
3357   if (!ArgExpr->EvaluateAsConstantExpr(ArgResult1, Context))
3358     return Diag(ArgExpr->getExprLoc(), diag::err_expr_not_string_literal)
3359            << ArgExpr->getType();
3360 
3361   return false;
3362 }
3363 
3364 bool Sema::CheckSystemZBuiltinFunctionCall(unsigned BuiltinID,
3365                                            CallExpr *TheCall) {
3366   if (BuiltinID == SystemZ::BI__builtin_tabort) {
3367     Expr *Arg = TheCall->getArg(0);
3368     if (Optional<llvm::APSInt> AbortCode = Arg->getIntegerConstantExpr(Context))
3369       if (AbortCode->getSExtValue() >= 0 && AbortCode->getSExtValue() < 256)
3370         return Diag(Arg->getBeginLoc(), diag::err_systemz_invalid_tabort_code)
3371                << Arg->getSourceRange();
3372   }
3373 
3374   // For intrinsics which take an immediate value as part of the instruction,
3375   // range check them here.
3376   unsigned i = 0, l = 0, u = 0;
3377   switch (BuiltinID) {
3378   default: return false;
3379   case SystemZ::BI__builtin_s390_lcbb: i = 1; l = 0; u = 15; break;
3380   case SystemZ::BI__builtin_s390_verimb:
3381   case SystemZ::BI__builtin_s390_verimh:
3382   case SystemZ::BI__builtin_s390_verimf:
3383   case SystemZ::BI__builtin_s390_verimg: i = 3; l = 0; u = 255; break;
3384   case SystemZ::BI__builtin_s390_vfaeb:
3385   case SystemZ::BI__builtin_s390_vfaeh:
3386   case SystemZ::BI__builtin_s390_vfaef:
3387   case SystemZ::BI__builtin_s390_vfaebs:
3388   case SystemZ::BI__builtin_s390_vfaehs:
3389   case SystemZ::BI__builtin_s390_vfaefs:
3390   case SystemZ::BI__builtin_s390_vfaezb:
3391   case SystemZ::BI__builtin_s390_vfaezh:
3392   case SystemZ::BI__builtin_s390_vfaezf:
3393   case SystemZ::BI__builtin_s390_vfaezbs:
3394   case SystemZ::BI__builtin_s390_vfaezhs:
3395   case SystemZ::BI__builtin_s390_vfaezfs: i = 2; l = 0; u = 15; break;
3396   case SystemZ::BI__builtin_s390_vfisb:
3397   case SystemZ::BI__builtin_s390_vfidb:
3398     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15) ||
3399            SemaBuiltinConstantArgRange(TheCall, 2, 0, 15);
3400   case SystemZ::BI__builtin_s390_vftcisb:
3401   case SystemZ::BI__builtin_s390_vftcidb: i = 1; l = 0; u = 4095; break;
3402   case SystemZ::BI__builtin_s390_vlbb: i = 1; l = 0; u = 15; break;
3403   case SystemZ::BI__builtin_s390_vpdi: i = 2; l = 0; u = 15; break;
3404   case SystemZ::BI__builtin_s390_vsldb: i = 2; l = 0; u = 15; break;
3405   case SystemZ::BI__builtin_s390_vstrcb:
3406   case SystemZ::BI__builtin_s390_vstrch:
3407   case SystemZ::BI__builtin_s390_vstrcf:
3408   case SystemZ::BI__builtin_s390_vstrczb:
3409   case SystemZ::BI__builtin_s390_vstrczh:
3410   case SystemZ::BI__builtin_s390_vstrczf:
3411   case SystemZ::BI__builtin_s390_vstrcbs:
3412   case SystemZ::BI__builtin_s390_vstrchs:
3413   case SystemZ::BI__builtin_s390_vstrcfs:
3414   case SystemZ::BI__builtin_s390_vstrczbs:
3415   case SystemZ::BI__builtin_s390_vstrczhs:
3416   case SystemZ::BI__builtin_s390_vstrczfs: i = 3; l = 0; u = 15; break;
3417   case SystemZ::BI__builtin_s390_vmslg: i = 3; l = 0; u = 15; break;
3418   case SystemZ::BI__builtin_s390_vfminsb:
3419   case SystemZ::BI__builtin_s390_vfmaxsb:
3420   case SystemZ::BI__builtin_s390_vfmindb:
3421   case SystemZ::BI__builtin_s390_vfmaxdb: i = 2; l = 0; u = 15; break;
3422   case SystemZ::BI__builtin_s390_vsld: i = 2; l = 0; u = 7; break;
3423   case SystemZ::BI__builtin_s390_vsrd: i = 2; l = 0; u = 7; break;
3424   }
3425   return SemaBuiltinConstantArgRange(TheCall, i, l, u);
3426 }
3427 
3428 /// SemaBuiltinCpuSupports - Handle __builtin_cpu_supports(char *).
3429 /// This checks that the target supports __builtin_cpu_supports and
3430 /// that the string argument is constant and valid.
3431 static bool SemaBuiltinCpuSupports(Sema &S, const TargetInfo &TI,
3432                                    CallExpr *TheCall) {
3433   Expr *Arg = TheCall->getArg(0);
3434 
3435   // Check if the argument is a string literal.
3436   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3437     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3438            << Arg->getSourceRange();
3439 
3440   // Check the contents of the string.
3441   StringRef Feature =
3442       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3443   if (!TI.validateCpuSupports(Feature))
3444     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_supports)
3445            << Arg->getSourceRange();
3446   return false;
3447 }
3448 
3449 /// SemaBuiltinCpuIs - Handle __builtin_cpu_is(char *).
3450 /// This checks that the target supports __builtin_cpu_is and
3451 /// that the string argument is constant and valid.
3452 static bool SemaBuiltinCpuIs(Sema &S, const TargetInfo &TI, CallExpr *TheCall) {
3453   Expr *Arg = TheCall->getArg(0);
3454 
3455   // Check if the argument is a string literal.
3456   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
3457     return S.Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
3458            << Arg->getSourceRange();
3459 
3460   // Check the contents of the string.
3461   StringRef Feature =
3462       cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
3463   if (!TI.validateCpuIs(Feature))
3464     return S.Diag(TheCall->getBeginLoc(), diag::err_invalid_cpu_is)
3465            << Arg->getSourceRange();
3466   return false;
3467 }
3468 
3469 // Check if the rounding mode is legal.
3470 bool Sema::CheckX86BuiltinRoundingOrSAE(unsigned BuiltinID, CallExpr *TheCall) {
3471   // Indicates if this instruction has rounding control or just SAE.
3472   bool HasRC = false;
3473 
3474   unsigned ArgNum = 0;
3475   switch (BuiltinID) {
3476   default:
3477     return false;
3478   case X86::BI__builtin_ia32_vcvttsd2si32:
3479   case X86::BI__builtin_ia32_vcvttsd2si64:
3480   case X86::BI__builtin_ia32_vcvttsd2usi32:
3481   case X86::BI__builtin_ia32_vcvttsd2usi64:
3482   case X86::BI__builtin_ia32_vcvttss2si32:
3483   case X86::BI__builtin_ia32_vcvttss2si64:
3484   case X86::BI__builtin_ia32_vcvttss2usi32:
3485   case X86::BI__builtin_ia32_vcvttss2usi64:
3486     ArgNum = 1;
3487     break;
3488   case X86::BI__builtin_ia32_maxpd512:
3489   case X86::BI__builtin_ia32_maxps512:
3490   case X86::BI__builtin_ia32_minpd512:
3491   case X86::BI__builtin_ia32_minps512:
3492     ArgNum = 2;
3493     break;
3494   case X86::BI__builtin_ia32_cvtps2pd512_mask:
3495   case X86::BI__builtin_ia32_cvttpd2dq512_mask:
3496   case X86::BI__builtin_ia32_cvttpd2qq512_mask:
3497   case X86::BI__builtin_ia32_cvttpd2udq512_mask:
3498   case X86::BI__builtin_ia32_cvttpd2uqq512_mask:
3499   case X86::BI__builtin_ia32_cvttps2dq512_mask:
3500   case X86::BI__builtin_ia32_cvttps2qq512_mask:
3501   case X86::BI__builtin_ia32_cvttps2udq512_mask:
3502   case X86::BI__builtin_ia32_cvttps2uqq512_mask:
3503   case X86::BI__builtin_ia32_exp2pd_mask:
3504   case X86::BI__builtin_ia32_exp2ps_mask:
3505   case X86::BI__builtin_ia32_getexppd512_mask:
3506   case X86::BI__builtin_ia32_getexpps512_mask:
3507   case X86::BI__builtin_ia32_rcp28pd_mask:
3508   case X86::BI__builtin_ia32_rcp28ps_mask:
3509   case X86::BI__builtin_ia32_rsqrt28pd_mask:
3510   case X86::BI__builtin_ia32_rsqrt28ps_mask:
3511   case X86::BI__builtin_ia32_vcomisd:
3512   case X86::BI__builtin_ia32_vcomiss:
3513   case X86::BI__builtin_ia32_vcvtph2ps512_mask:
3514     ArgNum = 3;
3515     break;
3516   case X86::BI__builtin_ia32_cmppd512_mask:
3517   case X86::BI__builtin_ia32_cmpps512_mask:
3518   case X86::BI__builtin_ia32_cmpsd_mask:
3519   case X86::BI__builtin_ia32_cmpss_mask:
3520   case X86::BI__builtin_ia32_cvtss2sd_round_mask:
3521   case X86::BI__builtin_ia32_getexpsd128_round_mask:
3522   case X86::BI__builtin_ia32_getexpss128_round_mask:
3523   case X86::BI__builtin_ia32_getmantpd512_mask:
3524   case X86::BI__builtin_ia32_getmantps512_mask:
3525   case X86::BI__builtin_ia32_maxsd_round_mask:
3526   case X86::BI__builtin_ia32_maxss_round_mask:
3527   case X86::BI__builtin_ia32_minsd_round_mask:
3528   case X86::BI__builtin_ia32_minss_round_mask:
3529   case X86::BI__builtin_ia32_rcp28sd_round_mask:
3530   case X86::BI__builtin_ia32_rcp28ss_round_mask:
3531   case X86::BI__builtin_ia32_reducepd512_mask:
3532   case X86::BI__builtin_ia32_reduceps512_mask:
3533   case X86::BI__builtin_ia32_rndscalepd_mask:
3534   case X86::BI__builtin_ia32_rndscaleps_mask:
3535   case X86::BI__builtin_ia32_rsqrt28sd_round_mask:
3536   case X86::BI__builtin_ia32_rsqrt28ss_round_mask:
3537     ArgNum = 4;
3538     break;
3539   case X86::BI__builtin_ia32_fixupimmpd512_mask:
3540   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
3541   case X86::BI__builtin_ia32_fixupimmps512_mask:
3542   case X86::BI__builtin_ia32_fixupimmps512_maskz:
3543   case X86::BI__builtin_ia32_fixupimmsd_mask:
3544   case X86::BI__builtin_ia32_fixupimmsd_maskz:
3545   case X86::BI__builtin_ia32_fixupimmss_mask:
3546   case X86::BI__builtin_ia32_fixupimmss_maskz:
3547   case X86::BI__builtin_ia32_getmantsd_round_mask:
3548   case X86::BI__builtin_ia32_getmantss_round_mask:
3549   case X86::BI__builtin_ia32_rangepd512_mask:
3550   case X86::BI__builtin_ia32_rangeps512_mask:
3551   case X86::BI__builtin_ia32_rangesd128_round_mask:
3552   case X86::BI__builtin_ia32_rangess128_round_mask:
3553   case X86::BI__builtin_ia32_reducesd_mask:
3554   case X86::BI__builtin_ia32_reducess_mask:
3555   case X86::BI__builtin_ia32_rndscalesd_round_mask:
3556   case X86::BI__builtin_ia32_rndscaless_round_mask:
3557     ArgNum = 5;
3558     break;
3559   case X86::BI__builtin_ia32_vcvtsd2si64:
3560   case X86::BI__builtin_ia32_vcvtsd2si32:
3561   case X86::BI__builtin_ia32_vcvtsd2usi32:
3562   case X86::BI__builtin_ia32_vcvtsd2usi64:
3563   case X86::BI__builtin_ia32_vcvtss2si32:
3564   case X86::BI__builtin_ia32_vcvtss2si64:
3565   case X86::BI__builtin_ia32_vcvtss2usi32:
3566   case X86::BI__builtin_ia32_vcvtss2usi64:
3567   case X86::BI__builtin_ia32_sqrtpd512:
3568   case X86::BI__builtin_ia32_sqrtps512:
3569     ArgNum = 1;
3570     HasRC = true;
3571     break;
3572   case X86::BI__builtin_ia32_addpd512:
3573   case X86::BI__builtin_ia32_addps512:
3574   case X86::BI__builtin_ia32_divpd512:
3575   case X86::BI__builtin_ia32_divps512:
3576   case X86::BI__builtin_ia32_mulpd512:
3577   case X86::BI__builtin_ia32_mulps512:
3578   case X86::BI__builtin_ia32_subpd512:
3579   case X86::BI__builtin_ia32_subps512:
3580   case X86::BI__builtin_ia32_cvtsi2sd64:
3581   case X86::BI__builtin_ia32_cvtsi2ss32:
3582   case X86::BI__builtin_ia32_cvtsi2ss64:
3583   case X86::BI__builtin_ia32_cvtusi2sd64:
3584   case X86::BI__builtin_ia32_cvtusi2ss32:
3585   case X86::BI__builtin_ia32_cvtusi2ss64:
3586     ArgNum = 2;
3587     HasRC = true;
3588     break;
3589   case X86::BI__builtin_ia32_cvtdq2ps512_mask:
3590   case X86::BI__builtin_ia32_cvtudq2ps512_mask:
3591   case X86::BI__builtin_ia32_cvtpd2ps512_mask:
3592   case X86::BI__builtin_ia32_cvtpd2dq512_mask:
3593   case X86::BI__builtin_ia32_cvtpd2qq512_mask:
3594   case X86::BI__builtin_ia32_cvtpd2udq512_mask:
3595   case X86::BI__builtin_ia32_cvtpd2uqq512_mask:
3596   case X86::BI__builtin_ia32_cvtps2dq512_mask:
3597   case X86::BI__builtin_ia32_cvtps2qq512_mask:
3598   case X86::BI__builtin_ia32_cvtps2udq512_mask:
3599   case X86::BI__builtin_ia32_cvtps2uqq512_mask:
3600   case X86::BI__builtin_ia32_cvtqq2pd512_mask:
3601   case X86::BI__builtin_ia32_cvtqq2ps512_mask:
3602   case X86::BI__builtin_ia32_cvtuqq2pd512_mask:
3603   case X86::BI__builtin_ia32_cvtuqq2ps512_mask:
3604     ArgNum = 3;
3605     HasRC = true;
3606     break;
3607   case X86::BI__builtin_ia32_addss_round_mask:
3608   case X86::BI__builtin_ia32_addsd_round_mask:
3609   case X86::BI__builtin_ia32_divss_round_mask:
3610   case X86::BI__builtin_ia32_divsd_round_mask:
3611   case X86::BI__builtin_ia32_mulss_round_mask:
3612   case X86::BI__builtin_ia32_mulsd_round_mask:
3613   case X86::BI__builtin_ia32_subss_round_mask:
3614   case X86::BI__builtin_ia32_subsd_round_mask:
3615   case X86::BI__builtin_ia32_scalefpd512_mask:
3616   case X86::BI__builtin_ia32_scalefps512_mask:
3617   case X86::BI__builtin_ia32_scalefsd_round_mask:
3618   case X86::BI__builtin_ia32_scalefss_round_mask:
3619   case X86::BI__builtin_ia32_cvtsd2ss_round_mask:
3620   case X86::BI__builtin_ia32_sqrtsd_round_mask:
3621   case X86::BI__builtin_ia32_sqrtss_round_mask:
3622   case X86::BI__builtin_ia32_vfmaddsd3_mask:
3623   case X86::BI__builtin_ia32_vfmaddsd3_maskz:
3624   case X86::BI__builtin_ia32_vfmaddsd3_mask3:
3625   case X86::BI__builtin_ia32_vfmaddss3_mask:
3626   case X86::BI__builtin_ia32_vfmaddss3_maskz:
3627   case X86::BI__builtin_ia32_vfmaddss3_mask3:
3628   case X86::BI__builtin_ia32_vfmaddpd512_mask:
3629   case X86::BI__builtin_ia32_vfmaddpd512_maskz:
3630   case X86::BI__builtin_ia32_vfmaddpd512_mask3:
3631   case X86::BI__builtin_ia32_vfmsubpd512_mask3:
3632   case X86::BI__builtin_ia32_vfmaddps512_mask:
3633   case X86::BI__builtin_ia32_vfmaddps512_maskz:
3634   case X86::BI__builtin_ia32_vfmaddps512_mask3:
3635   case X86::BI__builtin_ia32_vfmsubps512_mask3:
3636   case X86::BI__builtin_ia32_vfmaddsubpd512_mask:
3637   case X86::BI__builtin_ia32_vfmaddsubpd512_maskz:
3638   case X86::BI__builtin_ia32_vfmaddsubpd512_mask3:
3639   case X86::BI__builtin_ia32_vfmsubaddpd512_mask3:
3640   case X86::BI__builtin_ia32_vfmaddsubps512_mask:
3641   case X86::BI__builtin_ia32_vfmaddsubps512_maskz:
3642   case X86::BI__builtin_ia32_vfmaddsubps512_mask3:
3643   case X86::BI__builtin_ia32_vfmsubaddps512_mask3:
3644     ArgNum = 4;
3645     HasRC = true;
3646     break;
3647   }
3648 
3649   llvm::APSInt Result;
3650 
3651   // We can't check the value of a dependent argument.
3652   Expr *Arg = TheCall->getArg(ArgNum);
3653   if (Arg->isTypeDependent() || Arg->isValueDependent())
3654     return false;
3655 
3656   // Check constant-ness first.
3657   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3658     return true;
3659 
3660   // Make sure rounding mode is either ROUND_CUR_DIRECTION or ROUND_NO_EXC bit
3661   // is set. If the intrinsic has rounding control(bits 1:0), make sure its only
3662   // combined with ROUND_NO_EXC. If the intrinsic does not have rounding
3663   // control, allow ROUND_NO_EXC and ROUND_CUR_DIRECTION together.
3664   if (Result == 4/*ROUND_CUR_DIRECTION*/ ||
3665       Result == 8/*ROUND_NO_EXC*/ ||
3666       (!HasRC && Result == 12/*ROUND_CUR_DIRECTION|ROUND_NO_EXC*/) ||
3667       (HasRC && Result.getZExtValue() >= 8 && Result.getZExtValue() <= 11))
3668     return false;
3669 
3670   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_rounding)
3671          << Arg->getSourceRange();
3672 }
3673 
3674 // Check if the gather/scatter scale is legal.
3675 bool Sema::CheckX86BuiltinGatherScatterScale(unsigned BuiltinID,
3676                                              CallExpr *TheCall) {
3677   unsigned ArgNum = 0;
3678   switch (BuiltinID) {
3679   default:
3680     return false;
3681   case X86::BI__builtin_ia32_gatherpfdpd:
3682   case X86::BI__builtin_ia32_gatherpfdps:
3683   case X86::BI__builtin_ia32_gatherpfqpd:
3684   case X86::BI__builtin_ia32_gatherpfqps:
3685   case X86::BI__builtin_ia32_scatterpfdpd:
3686   case X86::BI__builtin_ia32_scatterpfdps:
3687   case X86::BI__builtin_ia32_scatterpfqpd:
3688   case X86::BI__builtin_ia32_scatterpfqps:
3689     ArgNum = 3;
3690     break;
3691   case X86::BI__builtin_ia32_gatherd_pd:
3692   case X86::BI__builtin_ia32_gatherd_pd256:
3693   case X86::BI__builtin_ia32_gatherq_pd:
3694   case X86::BI__builtin_ia32_gatherq_pd256:
3695   case X86::BI__builtin_ia32_gatherd_ps:
3696   case X86::BI__builtin_ia32_gatherd_ps256:
3697   case X86::BI__builtin_ia32_gatherq_ps:
3698   case X86::BI__builtin_ia32_gatherq_ps256:
3699   case X86::BI__builtin_ia32_gatherd_q:
3700   case X86::BI__builtin_ia32_gatherd_q256:
3701   case X86::BI__builtin_ia32_gatherq_q:
3702   case X86::BI__builtin_ia32_gatherq_q256:
3703   case X86::BI__builtin_ia32_gatherd_d:
3704   case X86::BI__builtin_ia32_gatherd_d256:
3705   case X86::BI__builtin_ia32_gatherq_d:
3706   case X86::BI__builtin_ia32_gatherq_d256:
3707   case X86::BI__builtin_ia32_gather3div2df:
3708   case X86::BI__builtin_ia32_gather3div2di:
3709   case X86::BI__builtin_ia32_gather3div4df:
3710   case X86::BI__builtin_ia32_gather3div4di:
3711   case X86::BI__builtin_ia32_gather3div4sf:
3712   case X86::BI__builtin_ia32_gather3div4si:
3713   case X86::BI__builtin_ia32_gather3div8sf:
3714   case X86::BI__builtin_ia32_gather3div8si:
3715   case X86::BI__builtin_ia32_gather3siv2df:
3716   case X86::BI__builtin_ia32_gather3siv2di:
3717   case X86::BI__builtin_ia32_gather3siv4df:
3718   case X86::BI__builtin_ia32_gather3siv4di:
3719   case X86::BI__builtin_ia32_gather3siv4sf:
3720   case X86::BI__builtin_ia32_gather3siv4si:
3721   case X86::BI__builtin_ia32_gather3siv8sf:
3722   case X86::BI__builtin_ia32_gather3siv8si:
3723   case X86::BI__builtin_ia32_gathersiv8df:
3724   case X86::BI__builtin_ia32_gathersiv16sf:
3725   case X86::BI__builtin_ia32_gatherdiv8df:
3726   case X86::BI__builtin_ia32_gatherdiv16sf:
3727   case X86::BI__builtin_ia32_gathersiv8di:
3728   case X86::BI__builtin_ia32_gathersiv16si:
3729   case X86::BI__builtin_ia32_gatherdiv8di:
3730   case X86::BI__builtin_ia32_gatherdiv16si:
3731   case X86::BI__builtin_ia32_scatterdiv2df:
3732   case X86::BI__builtin_ia32_scatterdiv2di:
3733   case X86::BI__builtin_ia32_scatterdiv4df:
3734   case X86::BI__builtin_ia32_scatterdiv4di:
3735   case X86::BI__builtin_ia32_scatterdiv4sf:
3736   case X86::BI__builtin_ia32_scatterdiv4si:
3737   case X86::BI__builtin_ia32_scatterdiv8sf:
3738   case X86::BI__builtin_ia32_scatterdiv8si:
3739   case X86::BI__builtin_ia32_scattersiv2df:
3740   case X86::BI__builtin_ia32_scattersiv2di:
3741   case X86::BI__builtin_ia32_scattersiv4df:
3742   case X86::BI__builtin_ia32_scattersiv4di:
3743   case X86::BI__builtin_ia32_scattersiv4sf:
3744   case X86::BI__builtin_ia32_scattersiv4si:
3745   case X86::BI__builtin_ia32_scattersiv8sf:
3746   case X86::BI__builtin_ia32_scattersiv8si:
3747   case X86::BI__builtin_ia32_scattersiv8df:
3748   case X86::BI__builtin_ia32_scattersiv16sf:
3749   case X86::BI__builtin_ia32_scatterdiv8df:
3750   case X86::BI__builtin_ia32_scatterdiv16sf:
3751   case X86::BI__builtin_ia32_scattersiv8di:
3752   case X86::BI__builtin_ia32_scattersiv16si:
3753   case X86::BI__builtin_ia32_scatterdiv8di:
3754   case X86::BI__builtin_ia32_scatterdiv16si:
3755     ArgNum = 4;
3756     break;
3757   }
3758 
3759   llvm::APSInt Result;
3760 
3761   // We can't check the value of a dependent argument.
3762   Expr *Arg = TheCall->getArg(ArgNum);
3763   if (Arg->isTypeDependent() || Arg->isValueDependent())
3764     return false;
3765 
3766   // Check constant-ness first.
3767   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3768     return true;
3769 
3770   if (Result == 1 || Result == 2 || Result == 4 || Result == 8)
3771     return false;
3772 
3773   return Diag(TheCall->getBeginLoc(), diag::err_x86_builtin_invalid_scale)
3774          << Arg->getSourceRange();
3775 }
3776 
3777 enum { TileRegLow = 0, TileRegHigh = 7 };
3778 
3779 bool Sema::CheckX86BuiltinTileArgumentsRange(CallExpr *TheCall,
3780                                              ArrayRef<int> ArgNums) {
3781   for (int ArgNum : ArgNums) {
3782     if (SemaBuiltinConstantArgRange(TheCall, ArgNum, TileRegLow, TileRegHigh))
3783       return true;
3784   }
3785   return false;
3786 }
3787 
3788 bool Sema::CheckX86BuiltinTileDuplicate(CallExpr *TheCall,
3789                                         ArrayRef<int> ArgNums) {
3790   // Because the max number of tile register is TileRegHigh + 1, so here we use
3791   // each bit to represent the usage of them in bitset.
3792   std::bitset<TileRegHigh + 1> ArgValues;
3793   for (int ArgNum : ArgNums) {
3794     Expr *Arg = TheCall->getArg(ArgNum);
3795     if (Arg->isTypeDependent() || Arg->isValueDependent())
3796       continue;
3797 
3798     llvm::APSInt Result;
3799     if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
3800       return true;
3801     int ArgExtValue = Result.getExtValue();
3802     assert((ArgExtValue >= TileRegLow || ArgExtValue <= TileRegHigh) &&
3803            "Incorrect tile register num.");
3804     if (ArgValues.test(ArgExtValue))
3805       return Diag(TheCall->getBeginLoc(),
3806                   diag::err_x86_builtin_tile_arg_duplicate)
3807              << TheCall->getArg(ArgNum)->getSourceRange();
3808     ArgValues.set(ArgExtValue);
3809   }
3810   return false;
3811 }
3812 
3813 bool Sema::CheckX86BuiltinTileRangeAndDuplicate(CallExpr *TheCall,
3814                                                 ArrayRef<int> ArgNums) {
3815   return CheckX86BuiltinTileArgumentsRange(TheCall, ArgNums) ||
3816          CheckX86BuiltinTileDuplicate(TheCall, ArgNums);
3817 }
3818 
3819 bool Sema::CheckX86BuiltinTileArguments(unsigned BuiltinID, CallExpr *TheCall) {
3820   switch (BuiltinID) {
3821   default:
3822     return false;
3823   case X86::BI__builtin_ia32_tileloadd64:
3824   case X86::BI__builtin_ia32_tileloaddt164:
3825   case X86::BI__builtin_ia32_tilestored64:
3826   case X86::BI__builtin_ia32_tilezero:
3827     return CheckX86BuiltinTileArgumentsRange(TheCall, 0);
3828   case X86::BI__builtin_ia32_tdpbssd:
3829   case X86::BI__builtin_ia32_tdpbsud:
3830   case X86::BI__builtin_ia32_tdpbusd:
3831   case X86::BI__builtin_ia32_tdpbuud:
3832   case X86::BI__builtin_ia32_tdpbf16ps:
3833     return CheckX86BuiltinTileRangeAndDuplicate(TheCall, {0, 1, 2});
3834   }
3835 }
3836 static bool isX86_32Builtin(unsigned BuiltinID) {
3837   // These builtins only work on x86-32 targets.
3838   switch (BuiltinID) {
3839   case X86::BI__builtin_ia32_readeflags_u32:
3840   case X86::BI__builtin_ia32_writeeflags_u32:
3841     return true;
3842   }
3843 
3844   return false;
3845 }
3846 
3847 bool Sema::CheckX86BuiltinFunctionCall(const TargetInfo &TI, unsigned BuiltinID,
3848                                        CallExpr *TheCall) {
3849   if (BuiltinID == X86::BI__builtin_cpu_supports)
3850     return SemaBuiltinCpuSupports(*this, TI, TheCall);
3851 
3852   if (BuiltinID == X86::BI__builtin_cpu_is)
3853     return SemaBuiltinCpuIs(*this, TI, TheCall);
3854 
3855   // Check for 32-bit only builtins on a 64-bit target.
3856   const llvm::Triple &TT = TI.getTriple();
3857   if (TT.getArch() != llvm::Triple::x86 && isX86_32Builtin(BuiltinID))
3858     return Diag(TheCall->getCallee()->getBeginLoc(),
3859                 diag::err_32_bit_builtin_64_bit_tgt);
3860 
3861   // If the intrinsic has rounding or SAE make sure its valid.
3862   if (CheckX86BuiltinRoundingOrSAE(BuiltinID, TheCall))
3863     return true;
3864 
3865   // If the intrinsic has a gather/scatter scale immediate make sure its valid.
3866   if (CheckX86BuiltinGatherScatterScale(BuiltinID, TheCall))
3867     return true;
3868 
3869   // If the intrinsic has a tile arguments, make sure they are valid.
3870   if (CheckX86BuiltinTileArguments(BuiltinID, TheCall))
3871     return true;
3872 
3873   // For intrinsics which take an immediate value as part of the instruction,
3874   // range check them here.
3875   int i = 0, l = 0, u = 0;
3876   switch (BuiltinID) {
3877   default:
3878     return false;
3879   case X86::BI__builtin_ia32_vec_ext_v2si:
3880   case X86::BI__builtin_ia32_vec_ext_v2di:
3881   case X86::BI__builtin_ia32_vextractf128_pd256:
3882   case X86::BI__builtin_ia32_vextractf128_ps256:
3883   case X86::BI__builtin_ia32_vextractf128_si256:
3884   case X86::BI__builtin_ia32_extract128i256:
3885   case X86::BI__builtin_ia32_extractf64x4_mask:
3886   case X86::BI__builtin_ia32_extracti64x4_mask:
3887   case X86::BI__builtin_ia32_extractf32x8_mask:
3888   case X86::BI__builtin_ia32_extracti32x8_mask:
3889   case X86::BI__builtin_ia32_extractf64x2_256_mask:
3890   case X86::BI__builtin_ia32_extracti64x2_256_mask:
3891   case X86::BI__builtin_ia32_extractf32x4_256_mask:
3892   case X86::BI__builtin_ia32_extracti32x4_256_mask:
3893     i = 1; l = 0; u = 1;
3894     break;
3895   case X86::BI__builtin_ia32_vec_set_v2di:
3896   case X86::BI__builtin_ia32_vinsertf128_pd256:
3897   case X86::BI__builtin_ia32_vinsertf128_ps256:
3898   case X86::BI__builtin_ia32_vinsertf128_si256:
3899   case X86::BI__builtin_ia32_insert128i256:
3900   case X86::BI__builtin_ia32_insertf32x8:
3901   case X86::BI__builtin_ia32_inserti32x8:
3902   case X86::BI__builtin_ia32_insertf64x4:
3903   case X86::BI__builtin_ia32_inserti64x4:
3904   case X86::BI__builtin_ia32_insertf64x2_256:
3905   case X86::BI__builtin_ia32_inserti64x2_256:
3906   case X86::BI__builtin_ia32_insertf32x4_256:
3907   case X86::BI__builtin_ia32_inserti32x4_256:
3908     i = 2; l = 0; u = 1;
3909     break;
3910   case X86::BI__builtin_ia32_vpermilpd:
3911   case X86::BI__builtin_ia32_vec_ext_v4hi:
3912   case X86::BI__builtin_ia32_vec_ext_v4si:
3913   case X86::BI__builtin_ia32_vec_ext_v4sf:
3914   case X86::BI__builtin_ia32_vec_ext_v4di:
3915   case X86::BI__builtin_ia32_extractf32x4_mask:
3916   case X86::BI__builtin_ia32_extracti32x4_mask:
3917   case X86::BI__builtin_ia32_extractf64x2_512_mask:
3918   case X86::BI__builtin_ia32_extracti64x2_512_mask:
3919     i = 1; l = 0; u = 3;
3920     break;
3921   case X86::BI_mm_prefetch:
3922   case X86::BI__builtin_ia32_vec_ext_v8hi:
3923   case X86::BI__builtin_ia32_vec_ext_v8si:
3924     i = 1; l = 0; u = 7;
3925     break;
3926   case X86::BI__builtin_ia32_sha1rnds4:
3927   case X86::BI__builtin_ia32_blendpd:
3928   case X86::BI__builtin_ia32_shufpd:
3929   case X86::BI__builtin_ia32_vec_set_v4hi:
3930   case X86::BI__builtin_ia32_vec_set_v4si:
3931   case X86::BI__builtin_ia32_vec_set_v4di:
3932   case X86::BI__builtin_ia32_shuf_f32x4_256:
3933   case X86::BI__builtin_ia32_shuf_f64x2_256:
3934   case X86::BI__builtin_ia32_shuf_i32x4_256:
3935   case X86::BI__builtin_ia32_shuf_i64x2_256:
3936   case X86::BI__builtin_ia32_insertf64x2_512:
3937   case X86::BI__builtin_ia32_inserti64x2_512:
3938   case X86::BI__builtin_ia32_insertf32x4:
3939   case X86::BI__builtin_ia32_inserti32x4:
3940     i = 2; l = 0; u = 3;
3941     break;
3942   case X86::BI__builtin_ia32_vpermil2pd:
3943   case X86::BI__builtin_ia32_vpermil2pd256:
3944   case X86::BI__builtin_ia32_vpermil2ps:
3945   case X86::BI__builtin_ia32_vpermil2ps256:
3946     i = 3; l = 0; u = 3;
3947     break;
3948   case X86::BI__builtin_ia32_cmpb128_mask:
3949   case X86::BI__builtin_ia32_cmpw128_mask:
3950   case X86::BI__builtin_ia32_cmpd128_mask:
3951   case X86::BI__builtin_ia32_cmpq128_mask:
3952   case X86::BI__builtin_ia32_cmpb256_mask:
3953   case X86::BI__builtin_ia32_cmpw256_mask:
3954   case X86::BI__builtin_ia32_cmpd256_mask:
3955   case X86::BI__builtin_ia32_cmpq256_mask:
3956   case X86::BI__builtin_ia32_cmpb512_mask:
3957   case X86::BI__builtin_ia32_cmpw512_mask:
3958   case X86::BI__builtin_ia32_cmpd512_mask:
3959   case X86::BI__builtin_ia32_cmpq512_mask:
3960   case X86::BI__builtin_ia32_ucmpb128_mask:
3961   case X86::BI__builtin_ia32_ucmpw128_mask:
3962   case X86::BI__builtin_ia32_ucmpd128_mask:
3963   case X86::BI__builtin_ia32_ucmpq128_mask:
3964   case X86::BI__builtin_ia32_ucmpb256_mask:
3965   case X86::BI__builtin_ia32_ucmpw256_mask:
3966   case X86::BI__builtin_ia32_ucmpd256_mask:
3967   case X86::BI__builtin_ia32_ucmpq256_mask:
3968   case X86::BI__builtin_ia32_ucmpb512_mask:
3969   case X86::BI__builtin_ia32_ucmpw512_mask:
3970   case X86::BI__builtin_ia32_ucmpd512_mask:
3971   case X86::BI__builtin_ia32_ucmpq512_mask:
3972   case X86::BI__builtin_ia32_vpcomub:
3973   case X86::BI__builtin_ia32_vpcomuw:
3974   case X86::BI__builtin_ia32_vpcomud:
3975   case X86::BI__builtin_ia32_vpcomuq:
3976   case X86::BI__builtin_ia32_vpcomb:
3977   case X86::BI__builtin_ia32_vpcomw:
3978   case X86::BI__builtin_ia32_vpcomd:
3979   case X86::BI__builtin_ia32_vpcomq:
3980   case X86::BI__builtin_ia32_vec_set_v8hi:
3981   case X86::BI__builtin_ia32_vec_set_v8si:
3982     i = 2; l = 0; u = 7;
3983     break;
3984   case X86::BI__builtin_ia32_vpermilpd256:
3985   case X86::BI__builtin_ia32_roundps:
3986   case X86::BI__builtin_ia32_roundpd:
3987   case X86::BI__builtin_ia32_roundps256:
3988   case X86::BI__builtin_ia32_roundpd256:
3989   case X86::BI__builtin_ia32_getmantpd128_mask:
3990   case X86::BI__builtin_ia32_getmantpd256_mask:
3991   case X86::BI__builtin_ia32_getmantps128_mask:
3992   case X86::BI__builtin_ia32_getmantps256_mask:
3993   case X86::BI__builtin_ia32_getmantpd512_mask:
3994   case X86::BI__builtin_ia32_getmantps512_mask:
3995   case X86::BI__builtin_ia32_vec_ext_v16qi:
3996   case X86::BI__builtin_ia32_vec_ext_v16hi:
3997     i = 1; l = 0; u = 15;
3998     break;
3999   case X86::BI__builtin_ia32_pblendd128:
4000   case X86::BI__builtin_ia32_blendps:
4001   case X86::BI__builtin_ia32_blendpd256:
4002   case X86::BI__builtin_ia32_shufpd256:
4003   case X86::BI__builtin_ia32_roundss:
4004   case X86::BI__builtin_ia32_roundsd:
4005   case X86::BI__builtin_ia32_rangepd128_mask:
4006   case X86::BI__builtin_ia32_rangepd256_mask:
4007   case X86::BI__builtin_ia32_rangepd512_mask:
4008   case X86::BI__builtin_ia32_rangeps128_mask:
4009   case X86::BI__builtin_ia32_rangeps256_mask:
4010   case X86::BI__builtin_ia32_rangeps512_mask:
4011   case X86::BI__builtin_ia32_getmantsd_round_mask:
4012   case X86::BI__builtin_ia32_getmantss_round_mask:
4013   case X86::BI__builtin_ia32_vec_set_v16qi:
4014   case X86::BI__builtin_ia32_vec_set_v16hi:
4015     i = 2; l = 0; u = 15;
4016     break;
4017   case X86::BI__builtin_ia32_vec_ext_v32qi:
4018     i = 1; l = 0; u = 31;
4019     break;
4020   case X86::BI__builtin_ia32_cmpps:
4021   case X86::BI__builtin_ia32_cmpss:
4022   case X86::BI__builtin_ia32_cmppd:
4023   case X86::BI__builtin_ia32_cmpsd:
4024   case X86::BI__builtin_ia32_cmpps256:
4025   case X86::BI__builtin_ia32_cmppd256:
4026   case X86::BI__builtin_ia32_cmpps128_mask:
4027   case X86::BI__builtin_ia32_cmppd128_mask:
4028   case X86::BI__builtin_ia32_cmpps256_mask:
4029   case X86::BI__builtin_ia32_cmppd256_mask:
4030   case X86::BI__builtin_ia32_cmpps512_mask:
4031   case X86::BI__builtin_ia32_cmppd512_mask:
4032   case X86::BI__builtin_ia32_cmpsd_mask:
4033   case X86::BI__builtin_ia32_cmpss_mask:
4034   case X86::BI__builtin_ia32_vec_set_v32qi:
4035     i = 2; l = 0; u = 31;
4036     break;
4037   case X86::BI__builtin_ia32_permdf256:
4038   case X86::BI__builtin_ia32_permdi256:
4039   case X86::BI__builtin_ia32_permdf512:
4040   case X86::BI__builtin_ia32_permdi512:
4041   case X86::BI__builtin_ia32_vpermilps:
4042   case X86::BI__builtin_ia32_vpermilps256:
4043   case X86::BI__builtin_ia32_vpermilpd512:
4044   case X86::BI__builtin_ia32_vpermilps512:
4045   case X86::BI__builtin_ia32_pshufd:
4046   case X86::BI__builtin_ia32_pshufd256:
4047   case X86::BI__builtin_ia32_pshufd512:
4048   case X86::BI__builtin_ia32_pshufhw:
4049   case X86::BI__builtin_ia32_pshufhw256:
4050   case X86::BI__builtin_ia32_pshufhw512:
4051   case X86::BI__builtin_ia32_pshuflw:
4052   case X86::BI__builtin_ia32_pshuflw256:
4053   case X86::BI__builtin_ia32_pshuflw512:
4054   case X86::BI__builtin_ia32_vcvtps2ph:
4055   case X86::BI__builtin_ia32_vcvtps2ph_mask:
4056   case X86::BI__builtin_ia32_vcvtps2ph256:
4057   case X86::BI__builtin_ia32_vcvtps2ph256_mask:
4058   case X86::BI__builtin_ia32_vcvtps2ph512_mask:
4059   case X86::BI__builtin_ia32_rndscaleps_128_mask:
4060   case X86::BI__builtin_ia32_rndscalepd_128_mask:
4061   case X86::BI__builtin_ia32_rndscaleps_256_mask:
4062   case X86::BI__builtin_ia32_rndscalepd_256_mask:
4063   case X86::BI__builtin_ia32_rndscaleps_mask:
4064   case X86::BI__builtin_ia32_rndscalepd_mask:
4065   case X86::BI__builtin_ia32_reducepd128_mask:
4066   case X86::BI__builtin_ia32_reducepd256_mask:
4067   case X86::BI__builtin_ia32_reducepd512_mask:
4068   case X86::BI__builtin_ia32_reduceps128_mask:
4069   case X86::BI__builtin_ia32_reduceps256_mask:
4070   case X86::BI__builtin_ia32_reduceps512_mask:
4071   case X86::BI__builtin_ia32_prold512:
4072   case X86::BI__builtin_ia32_prolq512:
4073   case X86::BI__builtin_ia32_prold128:
4074   case X86::BI__builtin_ia32_prold256:
4075   case X86::BI__builtin_ia32_prolq128:
4076   case X86::BI__builtin_ia32_prolq256:
4077   case X86::BI__builtin_ia32_prord512:
4078   case X86::BI__builtin_ia32_prorq512:
4079   case X86::BI__builtin_ia32_prord128:
4080   case X86::BI__builtin_ia32_prord256:
4081   case X86::BI__builtin_ia32_prorq128:
4082   case X86::BI__builtin_ia32_prorq256:
4083   case X86::BI__builtin_ia32_fpclasspd128_mask:
4084   case X86::BI__builtin_ia32_fpclasspd256_mask:
4085   case X86::BI__builtin_ia32_fpclassps128_mask:
4086   case X86::BI__builtin_ia32_fpclassps256_mask:
4087   case X86::BI__builtin_ia32_fpclassps512_mask:
4088   case X86::BI__builtin_ia32_fpclasspd512_mask:
4089   case X86::BI__builtin_ia32_fpclasssd_mask:
4090   case X86::BI__builtin_ia32_fpclassss_mask:
4091   case X86::BI__builtin_ia32_pslldqi128_byteshift:
4092   case X86::BI__builtin_ia32_pslldqi256_byteshift:
4093   case X86::BI__builtin_ia32_pslldqi512_byteshift:
4094   case X86::BI__builtin_ia32_psrldqi128_byteshift:
4095   case X86::BI__builtin_ia32_psrldqi256_byteshift:
4096   case X86::BI__builtin_ia32_psrldqi512_byteshift:
4097   case X86::BI__builtin_ia32_kshiftliqi:
4098   case X86::BI__builtin_ia32_kshiftlihi:
4099   case X86::BI__builtin_ia32_kshiftlisi:
4100   case X86::BI__builtin_ia32_kshiftlidi:
4101   case X86::BI__builtin_ia32_kshiftriqi:
4102   case X86::BI__builtin_ia32_kshiftrihi:
4103   case X86::BI__builtin_ia32_kshiftrisi:
4104   case X86::BI__builtin_ia32_kshiftridi:
4105     i = 1; l = 0; u = 255;
4106     break;
4107   case X86::BI__builtin_ia32_vperm2f128_pd256:
4108   case X86::BI__builtin_ia32_vperm2f128_ps256:
4109   case X86::BI__builtin_ia32_vperm2f128_si256:
4110   case X86::BI__builtin_ia32_permti256:
4111   case X86::BI__builtin_ia32_pblendw128:
4112   case X86::BI__builtin_ia32_pblendw256:
4113   case X86::BI__builtin_ia32_blendps256:
4114   case X86::BI__builtin_ia32_pblendd256:
4115   case X86::BI__builtin_ia32_palignr128:
4116   case X86::BI__builtin_ia32_palignr256:
4117   case X86::BI__builtin_ia32_palignr512:
4118   case X86::BI__builtin_ia32_alignq512:
4119   case X86::BI__builtin_ia32_alignd512:
4120   case X86::BI__builtin_ia32_alignd128:
4121   case X86::BI__builtin_ia32_alignd256:
4122   case X86::BI__builtin_ia32_alignq128:
4123   case X86::BI__builtin_ia32_alignq256:
4124   case X86::BI__builtin_ia32_vcomisd:
4125   case X86::BI__builtin_ia32_vcomiss:
4126   case X86::BI__builtin_ia32_shuf_f32x4:
4127   case X86::BI__builtin_ia32_shuf_f64x2:
4128   case X86::BI__builtin_ia32_shuf_i32x4:
4129   case X86::BI__builtin_ia32_shuf_i64x2:
4130   case X86::BI__builtin_ia32_shufpd512:
4131   case X86::BI__builtin_ia32_shufps:
4132   case X86::BI__builtin_ia32_shufps256:
4133   case X86::BI__builtin_ia32_shufps512:
4134   case X86::BI__builtin_ia32_dbpsadbw128:
4135   case X86::BI__builtin_ia32_dbpsadbw256:
4136   case X86::BI__builtin_ia32_dbpsadbw512:
4137   case X86::BI__builtin_ia32_vpshldd128:
4138   case X86::BI__builtin_ia32_vpshldd256:
4139   case X86::BI__builtin_ia32_vpshldd512:
4140   case X86::BI__builtin_ia32_vpshldq128:
4141   case X86::BI__builtin_ia32_vpshldq256:
4142   case X86::BI__builtin_ia32_vpshldq512:
4143   case X86::BI__builtin_ia32_vpshldw128:
4144   case X86::BI__builtin_ia32_vpshldw256:
4145   case X86::BI__builtin_ia32_vpshldw512:
4146   case X86::BI__builtin_ia32_vpshrdd128:
4147   case X86::BI__builtin_ia32_vpshrdd256:
4148   case X86::BI__builtin_ia32_vpshrdd512:
4149   case X86::BI__builtin_ia32_vpshrdq128:
4150   case X86::BI__builtin_ia32_vpshrdq256:
4151   case X86::BI__builtin_ia32_vpshrdq512:
4152   case X86::BI__builtin_ia32_vpshrdw128:
4153   case X86::BI__builtin_ia32_vpshrdw256:
4154   case X86::BI__builtin_ia32_vpshrdw512:
4155     i = 2; l = 0; u = 255;
4156     break;
4157   case X86::BI__builtin_ia32_fixupimmpd512_mask:
4158   case X86::BI__builtin_ia32_fixupimmpd512_maskz:
4159   case X86::BI__builtin_ia32_fixupimmps512_mask:
4160   case X86::BI__builtin_ia32_fixupimmps512_maskz:
4161   case X86::BI__builtin_ia32_fixupimmsd_mask:
4162   case X86::BI__builtin_ia32_fixupimmsd_maskz:
4163   case X86::BI__builtin_ia32_fixupimmss_mask:
4164   case X86::BI__builtin_ia32_fixupimmss_maskz:
4165   case X86::BI__builtin_ia32_fixupimmpd128_mask:
4166   case X86::BI__builtin_ia32_fixupimmpd128_maskz:
4167   case X86::BI__builtin_ia32_fixupimmpd256_mask:
4168   case X86::BI__builtin_ia32_fixupimmpd256_maskz:
4169   case X86::BI__builtin_ia32_fixupimmps128_mask:
4170   case X86::BI__builtin_ia32_fixupimmps128_maskz:
4171   case X86::BI__builtin_ia32_fixupimmps256_mask:
4172   case X86::BI__builtin_ia32_fixupimmps256_maskz:
4173   case X86::BI__builtin_ia32_pternlogd512_mask:
4174   case X86::BI__builtin_ia32_pternlogd512_maskz:
4175   case X86::BI__builtin_ia32_pternlogq512_mask:
4176   case X86::BI__builtin_ia32_pternlogq512_maskz:
4177   case X86::BI__builtin_ia32_pternlogd128_mask:
4178   case X86::BI__builtin_ia32_pternlogd128_maskz:
4179   case X86::BI__builtin_ia32_pternlogd256_mask:
4180   case X86::BI__builtin_ia32_pternlogd256_maskz:
4181   case X86::BI__builtin_ia32_pternlogq128_mask:
4182   case X86::BI__builtin_ia32_pternlogq128_maskz:
4183   case X86::BI__builtin_ia32_pternlogq256_mask:
4184   case X86::BI__builtin_ia32_pternlogq256_maskz:
4185     i = 3; l = 0; u = 255;
4186     break;
4187   case X86::BI__builtin_ia32_gatherpfdpd:
4188   case X86::BI__builtin_ia32_gatherpfdps:
4189   case X86::BI__builtin_ia32_gatherpfqpd:
4190   case X86::BI__builtin_ia32_gatherpfqps:
4191   case X86::BI__builtin_ia32_scatterpfdpd:
4192   case X86::BI__builtin_ia32_scatterpfdps:
4193   case X86::BI__builtin_ia32_scatterpfqpd:
4194   case X86::BI__builtin_ia32_scatterpfqps:
4195     i = 4; l = 2; u = 3;
4196     break;
4197   case X86::BI__builtin_ia32_reducesd_mask:
4198   case X86::BI__builtin_ia32_reducess_mask:
4199   case X86::BI__builtin_ia32_rndscalesd_round_mask:
4200   case X86::BI__builtin_ia32_rndscaless_round_mask:
4201     i = 4; l = 0; u = 255;
4202     break;
4203   }
4204 
4205   // Note that we don't force a hard error on the range check here, allowing
4206   // template-generated or macro-generated dead code to potentially have out-of-
4207   // range values. These need to code generate, but don't need to necessarily
4208   // make any sense. We use a warning that defaults to an error.
4209   return SemaBuiltinConstantArgRange(TheCall, i, l, u, /*RangeIsError*/ false);
4210 }
4211 
4212 /// Given a FunctionDecl's FormatAttr, attempts to populate the FomatStringInfo
4213 /// parameter with the FormatAttr's correct format_idx and firstDataArg.
4214 /// Returns true when the format fits the function and the FormatStringInfo has
4215 /// been populated.
4216 bool Sema::getFormatStringInfo(const FormatAttr *Format, bool IsCXXMember,
4217                                FormatStringInfo *FSI) {
4218   FSI->HasVAListArg = Format->getFirstArg() == 0;
4219   FSI->FormatIdx = Format->getFormatIdx() - 1;
4220   FSI->FirstDataArg = FSI->HasVAListArg ? 0 : Format->getFirstArg() - 1;
4221 
4222   // The way the format attribute works in GCC, the implicit this argument
4223   // of member functions is counted. However, it doesn't appear in our own
4224   // lists, so decrement format_idx in that case.
4225   if (IsCXXMember) {
4226     if(FSI->FormatIdx == 0)
4227       return false;
4228     --FSI->FormatIdx;
4229     if (FSI->FirstDataArg != 0)
4230       --FSI->FirstDataArg;
4231   }
4232   return true;
4233 }
4234 
4235 /// Checks if a the given expression evaluates to null.
4236 ///
4237 /// Returns true if the value evaluates to null.
4238 static bool CheckNonNullExpr(Sema &S, const Expr *Expr) {
4239   // If the expression has non-null type, it doesn't evaluate to null.
4240   if (auto nullability
4241         = Expr->IgnoreImplicit()->getType()->getNullability(S.Context)) {
4242     if (*nullability == NullabilityKind::NonNull)
4243       return false;
4244   }
4245 
4246   // As a special case, transparent unions initialized with zero are
4247   // considered null for the purposes of the nonnull attribute.
4248   if (const RecordType *UT = Expr->getType()->getAsUnionType()) {
4249     if (UT->getDecl()->hasAttr<TransparentUnionAttr>())
4250       if (const CompoundLiteralExpr *CLE =
4251           dyn_cast<CompoundLiteralExpr>(Expr))
4252         if (const InitListExpr *ILE =
4253             dyn_cast<InitListExpr>(CLE->getInitializer()))
4254           Expr = ILE->getInit(0);
4255   }
4256 
4257   bool Result;
4258   return (!Expr->isValueDependent() &&
4259           Expr->EvaluateAsBooleanCondition(Result, S.Context) &&
4260           !Result);
4261 }
4262 
4263 static void CheckNonNullArgument(Sema &S,
4264                                  const Expr *ArgExpr,
4265                                  SourceLocation CallSiteLoc) {
4266   if (CheckNonNullExpr(S, ArgExpr))
4267     S.DiagRuntimeBehavior(CallSiteLoc, ArgExpr,
4268                           S.PDiag(diag::warn_null_arg)
4269                               << ArgExpr->getSourceRange());
4270 }
4271 
4272 bool Sema::GetFormatNSStringIdx(const FormatAttr *Format, unsigned &Idx) {
4273   FormatStringInfo FSI;
4274   if ((GetFormatStringType(Format) == FST_NSString) &&
4275       getFormatStringInfo(Format, false, &FSI)) {
4276     Idx = FSI.FormatIdx;
4277     return true;
4278   }
4279   return false;
4280 }
4281 
4282 /// Diagnose use of %s directive in an NSString which is being passed
4283 /// as formatting string to formatting method.
4284 static void
4285 DiagnoseCStringFormatDirectiveInCFAPI(Sema &S,
4286                                         const NamedDecl *FDecl,
4287                                         Expr **Args,
4288                                         unsigned NumArgs) {
4289   unsigned Idx = 0;
4290   bool Format = false;
4291   ObjCStringFormatFamily SFFamily = FDecl->getObjCFStringFormattingFamily();
4292   if (SFFamily == ObjCStringFormatFamily::SFF_CFString) {
4293     Idx = 2;
4294     Format = true;
4295   }
4296   else
4297     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4298       if (S.GetFormatNSStringIdx(I, Idx)) {
4299         Format = true;
4300         break;
4301       }
4302     }
4303   if (!Format || NumArgs <= Idx)
4304     return;
4305   const Expr *FormatExpr = Args[Idx];
4306   if (const CStyleCastExpr *CSCE = dyn_cast<CStyleCastExpr>(FormatExpr))
4307     FormatExpr = CSCE->getSubExpr();
4308   const StringLiteral *FormatString;
4309   if (const ObjCStringLiteral *OSL =
4310       dyn_cast<ObjCStringLiteral>(FormatExpr->IgnoreParenImpCasts()))
4311     FormatString = OSL->getString();
4312   else
4313     FormatString = dyn_cast<StringLiteral>(FormatExpr->IgnoreParenImpCasts());
4314   if (!FormatString)
4315     return;
4316   if (S.FormatStringHasSArg(FormatString)) {
4317     S.Diag(FormatExpr->getExprLoc(), diag::warn_objc_cdirective_format_string)
4318       << "%s" << 1 << 1;
4319     S.Diag(FDecl->getLocation(), diag::note_entity_declared_at)
4320       << FDecl->getDeclName();
4321   }
4322 }
4323 
4324 /// Determine whether the given type has a non-null nullability annotation.
4325 static bool isNonNullType(ASTContext &ctx, QualType type) {
4326   if (auto nullability = type->getNullability(ctx))
4327     return *nullability == NullabilityKind::NonNull;
4328 
4329   return false;
4330 }
4331 
4332 static void CheckNonNullArguments(Sema &S,
4333                                   const NamedDecl *FDecl,
4334                                   const FunctionProtoType *Proto,
4335                                   ArrayRef<const Expr *> Args,
4336                                   SourceLocation CallSiteLoc) {
4337   assert((FDecl || Proto) && "Need a function declaration or prototype");
4338 
4339   // Already checked by by constant evaluator.
4340   if (S.isConstantEvaluated())
4341     return;
4342   // Check the attributes attached to the method/function itself.
4343   llvm::SmallBitVector NonNullArgs;
4344   if (FDecl) {
4345     // Handle the nonnull attribute on the function/method declaration itself.
4346     for (const auto *NonNull : FDecl->specific_attrs<NonNullAttr>()) {
4347       if (!NonNull->args_size()) {
4348         // Easy case: all pointer arguments are nonnull.
4349         for (const auto *Arg : Args)
4350           if (S.isValidPointerAttrType(Arg->getType()))
4351             CheckNonNullArgument(S, Arg, CallSiteLoc);
4352         return;
4353       }
4354 
4355       for (const ParamIdx &Idx : NonNull->args()) {
4356         unsigned IdxAST = Idx.getASTIndex();
4357         if (IdxAST >= Args.size())
4358           continue;
4359         if (NonNullArgs.empty())
4360           NonNullArgs.resize(Args.size());
4361         NonNullArgs.set(IdxAST);
4362       }
4363     }
4364   }
4365 
4366   if (FDecl && (isa<FunctionDecl>(FDecl) || isa<ObjCMethodDecl>(FDecl))) {
4367     // Handle the nonnull attribute on the parameters of the
4368     // function/method.
4369     ArrayRef<ParmVarDecl*> parms;
4370     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(FDecl))
4371       parms = FD->parameters();
4372     else
4373       parms = cast<ObjCMethodDecl>(FDecl)->parameters();
4374 
4375     unsigned ParamIndex = 0;
4376     for (ArrayRef<ParmVarDecl*>::iterator I = parms.begin(), E = parms.end();
4377          I != E; ++I, ++ParamIndex) {
4378       const ParmVarDecl *PVD = *I;
4379       if (PVD->hasAttr<NonNullAttr>() ||
4380           isNonNullType(S.Context, PVD->getType())) {
4381         if (NonNullArgs.empty())
4382           NonNullArgs.resize(Args.size());
4383 
4384         NonNullArgs.set(ParamIndex);
4385       }
4386     }
4387   } else {
4388     // If we have a non-function, non-method declaration but no
4389     // function prototype, try to dig out the function prototype.
4390     if (!Proto) {
4391       if (const ValueDecl *VD = dyn_cast<ValueDecl>(FDecl)) {
4392         QualType type = VD->getType().getNonReferenceType();
4393         if (auto pointerType = type->getAs<PointerType>())
4394           type = pointerType->getPointeeType();
4395         else if (auto blockType = type->getAs<BlockPointerType>())
4396           type = blockType->getPointeeType();
4397         // FIXME: data member pointers?
4398 
4399         // Dig out the function prototype, if there is one.
4400         Proto = type->getAs<FunctionProtoType>();
4401       }
4402     }
4403 
4404     // Fill in non-null argument information from the nullability
4405     // information on the parameter types (if we have them).
4406     if (Proto) {
4407       unsigned Index = 0;
4408       for (auto paramType : Proto->getParamTypes()) {
4409         if (isNonNullType(S.Context, paramType)) {
4410           if (NonNullArgs.empty())
4411             NonNullArgs.resize(Args.size());
4412 
4413           NonNullArgs.set(Index);
4414         }
4415 
4416         ++Index;
4417       }
4418     }
4419   }
4420 
4421   // Check for non-null arguments.
4422   for (unsigned ArgIndex = 0, ArgIndexEnd = NonNullArgs.size();
4423        ArgIndex != ArgIndexEnd; ++ArgIndex) {
4424     if (NonNullArgs[ArgIndex])
4425       CheckNonNullArgument(S, Args[ArgIndex], CallSiteLoc);
4426   }
4427 }
4428 
4429 /// Handles the checks for format strings, non-POD arguments to vararg
4430 /// functions, NULL arguments passed to non-NULL parameters, and diagnose_if
4431 /// attributes.
4432 void Sema::checkCall(NamedDecl *FDecl, const FunctionProtoType *Proto,
4433                      const Expr *ThisArg, ArrayRef<const Expr *> Args,
4434                      bool IsMemberFunction, SourceLocation Loc,
4435                      SourceRange Range, VariadicCallType CallType) {
4436   // FIXME: We should check as much as we can in the template definition.
4437   if (CurContext->isDependentContext())
4438     return;
4439 
4440   // Printf and scanf checking.
4441   llvm::SmallBitVector CheckedVarArgs;
4442   if (FDecl) {
4443     for (const auto *I : FDecl->specific_attrs<FormatAttr>()) {
4444       // Only create vector if there are format attributes.
4445       CheckedVarArgs.resize(Args.size());
4446 
4447       CheckFormatArguments(I, Args, IsMemberFunction, CallType, Loc, Range,
4448                            CheckedVarArgs);
4449     }
4450   }
4451 
4452   // Refuse POD arguments that weren't caught by the format string
4453   // checks above.
4454   auto *FD = dyn_cast_or_null<FunctionDecl>(FDecl);
4455   if (CallType != VariadicDoesNotApply &&
4456       (!FD || FD->getBuiltinID() != Builtin::BI__noop)) {
4457     unsigned NumParams = Proto ? Proto->getNumParams()
4458                        : FDecl && isa<FunctionDecl>(FDecl)
4459                            ? cast<FunctionDecl>(FDecl)->getNumParams()
4460                        : FDecl && isa<ObjCMethodDecl>(FDecl)
4461                            ? cast<ObjCMethodDecl>(FDecl)->param_size()
4462                        : 0;
4463 
4464     for (unsigned ArgIdx = NumParams; ArgIdx < Args.size(); ++ArgIdx) {
4465       // Args[ArgIdx] can be null in malformed code.
4466       if (const Expr *Arg = Args[ArgIdx]) {
4467         if (CheckedVarArgs.empty() || !CheckedVarArgs[ArgIdx])
4468           checkVariadicArgument(Arg, CallType);
4469       }
4470     }
4471   }
4472 
4473   if (FDecl || Proto) {
4474     CheckNonNullArguments(*this, FDecl, Proto, Args, Loc);
4475 
4476     // Type safety checking.
4477     if (FDecl) {
4478       for (const auto *I : FDecl->specific_attrs<ArgumentWithTypeTagAttr>())
4479         CheckArgumentWithTypeTag(I, Args, Loc);
4480     }
4481   }
4482 
4483   if (FDecl && FDecl->hasAttr<AllocAlignAttr>()) {
4484     auto *AA = FDecl->getAttr<AllocAlignAttr>();
4485     const Expr *Arg = Args[AA->getParamIndex().getASTIndex()];
4486     if (!Arg->isValueDependent()) {
4487       Expr::EvalResult Align;
4488       if (Arg->EvaluateAsInt(Align, Context)) {
4489         const llvm::APSInt &I = Align.Val.getInt();
4490         if (!I.isPowerOf2())
4491           Diag(Arg->getExprLoc(), diag::warn_alignment_not_power_of_two)
4492               << Arg->getSourceRange();
4493 
4494         if (I > Sema::MaximumAlignment)
4495           Diag(Arg->getExprLoc(), diag::warn_assume_aligned_too_great)
4496               << Arg->getSourceRange() << Sema::MaximumAlignment;
4497       }
4498     }
4499   }
4500 
4501   if (FD)
4502     diagnoseArgDependentDiagnoseIfAttrs(FD, ThisArg, Args, Loc);
4503 }
4504 
4505 /// CheckConstructorCall - Check a constructor call for correctness and safety
4506 /// properties not enforced by the C type system.
4507 void Sema::CheckConstructorCall(FunctionDecl *FDecl,
4508                                 ArrayRef<const Expr *> Args,
4509                                 const FunctionProtoType *Proto,
4510                                 SourceLocation Loc) {
4511   VariadicCallType CallType =
4512     Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
4513   checkCall(FDecl, Proto, /*ThisArg=*/nullptr, Args, /*IsMemberFunction=*/true,
4514             Loc, SourceRange(), CallType);
4515 }
4516 
4517 /// CheckFunctionCall - Check a direct function call for various correctness
4518 /// and safety properties not strictly enforced by the C type system.
4519 bool Sema::CheckFunctionCall(FunctionDecl *FDecl, CallExpr *TheCall,
4520                              const FunctionProtoType *Proto) {
4521   bool IsMemberOperatorCall = isa<CXXOperatorCallExpr>(TheCall) &&
4522                               isa<CXXMethodDecl>(FDecl);
4523   bool IsMemberFunction = isa<CXXMemberCallExpr>(TheCall) ||
4524                           IsMemberOperatorCall;
4525   VariadicCallType CallType = getVariadicCallType(FDecl, Proto,
4526                                                   TheCall->getCallee());
4527   Expr** Args = TheCall->getArgs();
4528   unsigned NumArgs = TheCall->getNumArgs();
4529 
4530   Expr *ImplicitThis = nullptr;
4531   if (IsMemberOperatorCall) {
4532     // If this is a call to a member operator, hide the first argument
4533     // from checkCall.
4534     // FIXME: Our choice of AST representation here is less than ideal.
4535     ImplicitThis = Args[0];
4536     ++Args;
4537     --NumArgs;
4538   } else if (IsMemberFunction)
4539     ImplicitThis =
4540         cast<CXXMemberCallExpr>(TheCall)->getImplicitObjectArgument();
4541 
4542   checkCall(FDecl, Proto, ImplicitThis, llvm::makeArrayRef(Args, NumArgs),
4543             IsMemberFunction, TheCall->getRParenLoc(),
4544             TheCall->getCallee()->getSourceRange(), CallType);
4545 
4546   IdentifierInfo *FnInfo = FDecl->getIdentifier();
4547   // None of the checks below are needed for functions that don't have
4548   // simple names (e.g., C++ conversion functions).
4549   if (!FnInfo)
4550     return false;
4551 
4552   CheckAbsoluteValueFunction(TheCall, FDecl);
4553   CheckMaxUnsignedZero(TheCall, FDecl);
4554 
4555   if (getLangOpts().ObjC)
4556     DiagnoseCStringFormatDirectiveInCFAPI(*this, FDecl, Args, NumArgs);
4557 
4558   unsigned CMId = FDecl->getMemoryFunctionKind();
4559 
4560   // Handle memory setting and copying functions.
4561   switch (CMId) {
4562   case 0:
4563     return false;
4564   case Builtin::BIstrlcpy: // fallthrough
4565   case Builtin::BIstrlcat:
4566     CheckStrlcpycatArguments(TheCall, FnInfo);
4567     break;
4568   case Builtin::BIstrncat:
4569     CheckStrncatArguments(TheCall, FnInfo);
4570     break;
4571   case Builtin::BIfree:
4572     CheckFreeArguments(TheCall);
4573     break;
4574   default:
4575     CheckMemaccessArguments(TheCall, CMId, FnInfo);
4576   }
4577 
4578   return false;
4579 }
4580 
4581 bool Sema::CheckObjCMethodCall(ObjCMethodDecl *Method, SourceLocation lbrac,
4582                                ArrayRef<const Expr *> Args) {
4583   VariadicCallType CallType =
4584       Method->isVariadic() ? VariadicMethod : VariadicDoesNotApply;
4585 
4586   checkCall(Method, nullptr, /*ThisArg=*/nullptr, Args,
4587             /*IsMemberFunction=*/false, lbrac, Method->getSourceRange(),
4588             CallType);
4589 
4590   return false;
4591 }
4592 
4593 bool Sema::CheckPointerCall(NamedDecl *NDecl, CallExpr *TheCall,
4594                             const FunctionProtoType *Proto) {
4595   QualType Ty;
4596   if (const auto *V = dyn_cast<VarDecl>(NDecl))
4597     Ty = V->getType().getNonReferenceType();
4598   else if (const auto *F = dyn_cast<FieldDecl>(NDecl))
4599     Ty = F->getType().getNonReferenceType();
4600   else
4601     return false;
4602 
4603   if (!Ty->isBlockPointerType() && !Ty->isFunctionPointerType() &&
4604       !Ty->isFunctionProtoType())
4605     return false;
4606 
4607   VariadicCallType CallType;
4608   if (!Proto || !Proto->isVariadic()) {
4609     CallType = VariadicDoesNotApply;
4610   } else if (Ty->isBlockPointerType()) {
4611     CallType = VariadicBlock;
4612   } else { // Ty->isFunctionPointerType()
4613     CallType = VariadicFunction;
4614   }
4615 
4616   checkCall(NDecl, Proto, /*ThisArg=*/nullptr,
4617             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4618             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4619             TheCall->getCallee()->getSourceRange(), CallType);
4620 
4621   return false;
4622 }
4623 
4624 /// Checks function calls when a FunctionDecl or a NamedDecl is not available,
4625 /// such as function pointers returned from functions.
4626 bool Sema::CheckOtherCall(CallExpr *TheCall, const FunctionProtoType *Proto) {
4627   VariadicCallType CallType = getVariadicCallType(/*FDecl=*/nullptr, Proto,
4628                                                   TheCall->getCallee());
4629   checkCall(/*FDecl=*/nullptr, Proto, /*ThisArg=*/nullptr,
4630             llvm::makeArrayRef(TheCall->getArgs(), TheCall->getNumArgs()),
4631             /*IsMemberFunction=*/false, TheCall->getRParenLoc(),
4632             TheCall->getCallee()->getSourceRange(), CallType);
4633 
4634   return false;
4635 }
4636 
4637 static bool isValidOrderingForOp(int64_t Ordering, AtomicExpr::AtomicOp Op) {
4638   if (!llvm::isValidAtomicOrderingCABI(Ordering))
4639     return false;
4640 
4641   auto OrderingCABI = (llvm::AtomicOrderingCABI)Ordering;
4642   switch (Op) {
4643   case AtomicExpr::AO__c11_atomic_init:
4644   case AtomicExpr::AO__opencl_atomic_init:
4645     llvm_unreachable("There is no ordering argument for an init");
4646 
4647   case AtomicExpr::AO__c11_atomic_load:
4648   case AtomicExpr::AO__opencl_atomic_load:
4649   case AtomicExpr::AO__atomic_load_n:
4650   case AtomicExpr::AO__atomic_load:
4651     return OrderingCABI != llvm::AtomicOrderingCABI::release &&
4652            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4653 
4654   case AtomicExpr::AO__c11_atomic_store:
4655   case AtomicExpr::AO__opencl_atomic_store:
4656   case AtomicExpr::AO__atomic_store:
4657   case AtomicExpr::AO__atomic_store_n:
4658     return OrderingCABI != llvm::AtomicOrderingCABI::consume &&
4659            OrderingCABI != llvm::AtomicOrderingCABI::acquire &&
4660            OrderingCABI != llvm::AtomicOrderingCABI::acq_rel;
4661 
4662   default:
4663     return true;
4664   }
4665 }
4666 
4667 ExprResult Sema::SemaAtomicOpsOverloaded(ExprResult TheCallResult,
4668                                          AtomicExpr::AtomicOp Op) {
4669   CallExpr *TheCall = cast<CallExpr>(TheCallResult.get());
4670   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
4671   MultiExprArg Args{TheCall->getArgs(), TheCall->getNumArgs()};
4672   return BuildAtomicExpr({TheCall->getBeginLoc(), TheCall->getEndLoc()},
4673                          DRE->getSourceRange(), TheCall->getRParenLoc(), Args,
4674                          Op);
4675 }
4676 
4677 ExprResult Sema::BuildAtomicExpr(SourceRange CallRange, SourceRange ExprRange,
4678                                  SourceLocation RParenLoc, MultiExprArg Args,
4679                                  AtomicExpr::AtomicOp Op,
4680                                  AtomicArgumentOrder ArgOrder) {
4681   // All the non-OpenCL operations take one of the following forms.
4682   // The OpenCL operations take the __c11 forms with one extra argument for
4683   // synchronization scope.
4684   enum {
4685     // C    __c11_atomic_init(A *, C)
4686     Init,
4687 
4688     // C    __c11_atomic_load(A *, int)
4689     Load,
4690 
4691     // void __atomic_load(A *, CP, int)
4692     LoadCopy,
4693 
4694     // void __atomic_store(A *, CP, int)
4695     Copy,
4696 
4697     // C    __c11_atomic_add(A *, M, int)
4698     Arithmetic,
4699 
4700     // C    __atomic_exchange_n(A *, CP, int)
4701     Xchg,
4702 
4703     // void __atomic_exchange(A *, C *, CP, int)
4704     GNUXchg,
4705 
4706     // bool __c11_atomic_compare_exchange_strong(A *, C *, CP, int, int)
4707     C11CmpXchg,
4708 
4709     // bool __atomic_compare_exchange(A *, C *, CP, bool, int, int)
4710     GNUCmpXchg
4711   } Form = Init;
4712 
4713   const unsigned NumForm = GNUCmpXchg + 1;
4714   const unsigned NumArgs[] = { 2, 2, 3, 3, 3, 3, 4, 5, 6 };
4715   const unsigned NumVals[] = { 1, 0, 1, 1, 1, 1, 2, 2, 3 };
4716   // where:
4717   //   C is an appropriate type,
4718   //   A is volatile _Atomic(C) for __c11 builtins and is C for GNU builtins,
4719   //   CP is C for __c11 builtins and GNU _n builtins and is C * otherwise,
4720   //   M is C if C is an integer, and ptrdiff_t if C is a pointer, and
4721   //   the int parameters are for orderings.
4722 
4723   static_assert(sizeof(NumArgs)/sizeof(NumArgs[0]) == NumForm
4724       && sizeof(NumVals)/sizeof(NumVals[0]) == NumForm,
4725       "need to update code for modified forms");
4726   static_assert(AtomicExpr::AO__c11_atomic_init == 0 &&
4727                     AtomicExpr::AO__c11_atomic_fetch_min + 1 ==
4728                         AtomicExpr::AO__atomic_load,
4729                 "need to update code for modified C11 atomics");
4730   bool IsOpenCL = Op >= AtomicExpr::AO__opencl_atomic_init &&
4731                   Op <= AtomicExpr::AO__opencl_atomic_fetch_max;
4732   bool IsC11 = (Op >= AtomicExpr::AO__c11_atomic_init &&
4733                Op <= AtomicExpr::AO__c11_atomic_fetch_min) ||
4734                IsOpenCL;
4735   bool IsN = Op == AtomicExpr::AO__atomic_load_n ||
4736              Op == AtomicExpr::AO__atomic_store_n ||
4737              Op == AtomicExpr::AO__atomic_exchange_n ||
4738              Op == AtomicExpr::AO__atomic_compare_exchange_n;
4739   bool IsAddSub = false;
4740 
4741   switch (Op) {
4742   case AtomicExpr::AO__c11_atomic_init:
4743   case AtomicExpr::AO__opencl_atomic_init:
4744     Form = Init;
4745     break;
4746 
4747   case AtomicExpr::AO__c11_atomic_load:
4748   case AtomicExpr::AO__opencl_atomic_load:
4749   case AtomicExpr::AO__atomic_load_n:
4750     Form = Load;
4751     break;
4752 
4753   case AtomicExpr::AO__atomic_load:
4754     Form = LoadCopy;
4755     break;
4756 
4757   case AtomicExpr::AO__c11_atomic_store:
4758   case AtomicExpr::AO__opencl_atomic_store:
4759   case AtomicExpr::AO__atomic_store:
4760   case AtomicExpr::AO__atomic_store_n:
4761     Form = Copy;
4762     break;
4763 
4764   case AtomicExpr::AO__c11_atomic_fetch_add:
4765   case AtomicExpr::AO__c11_atomic_fetch_sub:
4766   case AtomicExpr::AO__opencl_atomic_fetch_add:
4767   case AtomicExpr::AO__opencl_atomic_fetch_sub:
4768   case AtomicExpr::AO__atomic_fetch_add:
4769   case AtomicExpr::AO__atomic_fetch_sub:
4770   case AtomicExpr::AO__atomic_add_fetch:
4771   case AtomicExpr::AO__atomic_sub_fetch:
4772     IsAddSub = true;
4773     LLVM_FALLTHROUGH;
4774   case AtomicExpr::AO__c11_atomic_fetch_and:
4775   case AtomicExpr::AO__c11_atomic_fetch_or:
4776   case AtomicExpr::AO__c11_atomic_fetch_xor:
4777   case AtomicExpr::AO__opencl_atomic_fetch_and:
4778   case AtomicExpr::AO__opencl_atomic_fetch_or:
4779   case AtomicExpr::AO__opencl_atomic_fetch_xor:
4780   case AtomicExpr::AO__atomic_fetch_and:
4781   case AtomicExpr::AO__atomic_fetch_or:
4782   case AtomicExpr::AO__atomic_fetch_xor:
4783   case AtomicExpr::AO__atomic_fetch_nand:
4784   case AtomicExpr::AO__atomic_and_fetch:
4785   case AtomicExpr::AO__atomic_or_fetch:
4786   case AtomicExpr::AO__atomic_xor_fetch:
4787   case AtomicExpr::AO__atomic_nand_fetch:
4788   case AtomicExpr::AO__c11_atomic_fetch_min:
4789   case AtomicExpr::AO__c11_atomic_fetch_max:
4790   case AtomicExpr::AO__opencl_atomic_fetch_min:
4791   case AtomicExpr::AO__opencl_atomic_fetch_max:
4792   case AtomicExpr::AO__atomic_min_fetch:
4793   case AtomicExpr::AO__atomic_max_fetch:
4794   case AtomicExpr::AO__atomic_fetch_min:
4795   case AtomicExpr::AO__atomic_fetch_max:
4796     Form = Arithmetic;
4797     break;
4798 
4799   case AtomicExpr::AO__c11_atomic_exchange:
4800   case AtomicExpr::AO__opencl_atomic_exchange:
4801   case AtomicExpr::AO__atomic_exchange_n:
4802     Form = Xchg;
4803     break;
4804 
4805   case AtomicExpr::AO__atomic_exchange:
4806     Form = GNUXchg;
4807     break;
4808 
4809   case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
4810   case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
4811   case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
4812   case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
4813     Form = C11CmpXchg;
4814     break;
4815 
4816   case AtomicExpr::AO__atomic_compare_exchange:
4817   case AtomicExpr::AO__atomic_compare_exchange_n:
4818     Form = GNUCmpXchg;
4819     break;
4820   }
4821 
4822   unsigned AdjustedNumArgs = NumArgs[Form];
4823   if (IsOpenCL && Op != AtomicExpr::AO__opencl_atomic_init)
4824     ++AdjustedNumArgs;
4825   // Check we have the right number of arguments.
4826   if (Args.size() < AdjustedNumArgs) {
4827     Diag(CallRange.getEnd(), diag::err_typecheck_call_too_few_args)
4828         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4829         << ExprRange;
4830     return ExprError();
4831   } else if (Args.size() > AdjustedNumArgs) {
4832     Diag(Args[AdjustedNumArgs]->getBeginLoc(),
4833          diag::err_typecheck_call_too_many_args)
4834         << 0 << AdjustedNumArgs << static_cast<unsigned>(Args.size())
4835         << ExprRange;
4836     return ExprError();
4837   }
4838 
4839   // Inspect the first argument of the atomic operation.
4840   Expr *Ptr = Args[0];
4841   ExprResult ConvertedPtr = DefaultFunctionArrayLvalueConversion(Ptr);
4842   if (ConvertedPtr.isInvalid())
4843     return ExprError();
4844 
4845   Ptr = ConvertedPtr.get();
4846   const PointerType *pointerType = Ptr->getType()->getAs<PointerType>();
4847   if (!pointerType) {
4848     Diag(ExprRange.getBegin(), diag::err_atomic_builtin_must_be_pointer)
4849         << Ptr->getType() << Ptr->getSourceRange();
4850     return ExprError();
4851   }
4852 
4853   // For a __c11 builtin, this should be a pointer to an _Atomic type.
4854   QualType AtomTy = pointerType->getPointeeType(); // 'A'
4855   QualType ValType = AtomTy; // 'C'
4856   if (IsC11) {
4857     if (!AtomTy->isAtomicType()) {
4858       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic)
4859           << Ptr->getType() << Ptr->getSourceRange();
4860       return ExprError();
4861     }
4862     if ((Form != Load && Form != LoadCopy && AtomTy.isConstQualified()) ||
4863         AtomTy.getAddressSpace() == LangAS::opencl_constant) {
4864       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_atomic)
4865           << (AtomTy.isConstQualified() ? 0 : 1) << Ptr->getType()
4866           << Ptr->getSourceRange();
4867       return ExprError();
4868     }
4869     ValType = AtomTy->castAs<AtomicType>()->getValueType();
4870   } else if (Form != Load && Form != LoadCopy) {
4871     if (ValType.isConstQualified()) {
4872       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_non_const_pointer)
4873           << Ptr->getType() << Ptr->getSourceRange();
4874       return ExprError();
4875     }
4876   }
4877 
4878   // For an arithmetic operation, the implied arithmetic must be well-formed.
4879   if (Form == Arithmetic) {
4880     // gcc does not enforce these rules for GNU atomics, but we do so for sanity.
4881     if (IsAddSub && !ValType->isIntegerType()
4882         && !ValType->isPointerType()) {
4883       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4884           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4885       return ExprError();
4886     }
4887     if (!IsAddSub && !ValType->isIntegerType()) {
4888       Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int)
4889           << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4890       return ExprError();
4891     }
4892     if (IsC11 && ValType->isPointerType() &&
4893         RequireCompleteType(Ptr->getBeginLoc(), ValType->getPointeeType(),
4894                             diag::err_incomplete_type)) {
4895       return ExprError();
4896     }
4897   } else if (IsN && !ValType->isIntegerType() && !ValType->isPointerType()) {
4898     // For __atomic_*_n operations, the value type must be a scalar integral or
4899     // pointer type which is 1, 2, 4, 8 or 16 bytes in length.
4900     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_atomic_int_or_ptr)
4901         << IsC11 << Ptr->getType() << Ptr->getSourceRange();
4902     return ExprError();
4903   }
4904 
4905   if (!IsC11 && !AtomTy.isTriviallyCopyableType(Context) &&
4906       !AtomTy->isScalarType()) {
4907     // For GNU atomics, require a trivially-copyable type. This is not part of
4908     // the GNU atomics specification, but we enforce it for sanity.
4909     Diag(ExprRange.getBegin(), diag::err_atomic_op_needs_trivial_copy)
4910         << Ptr->getType() << Ptr->getSourceRange();
4911     return ExprError();
4912   }
4913 
4914   switch (ValType.getObjCLifetime()) {
4915   case Qualifiers::OCL_None:
4916   case Qualifiers::OCL_ExplicitNone:
4917     // okay
4918     break;
4919 
4920   case Qualifiers::OCL_Weak:
4921   case Qualifiers::OCL_Strong:
4922   case Qualifiers::OCL_Autoreleasing:
4923     // FIXME: Can this happen? By this point, ValType should be known
4924     // to be trivially copyable.
4925     Diag(ExprRange.getBegin(), diag::err_arc_atomic_ownership)
4926         << ValType << Ptr->getSourceRange();
4927     return ExprError();
4928   }
4929 
4930   // All atomic operations have an overload which takes a pointer to a volatile
4931   // 'A'.  We shouldn't let the volatile-ness of the pointee-type inject itself
4932   // into the result or the other operands. Similarly atomic_load takes a
4933   // pointer to a const 'A'.
4934   ValType.removeLocalVolatile();
4935   ValType.removeLocalConst();
4936   QualType ResultType = ValType;
4937   if (Form == Copy || Form == LoadCopy || Form == GNUXchg ||
4938       Form == Init)
4939     ResultType = Context.VoidTy;
4940   else if (Form == C11CmpXchg || Form == GNUCmpXchg)
4941     ResultType = Context.BoolTy;
4942 
4943   // The type of a parameter passed 'by value'. In the GNU atomics, such
4944   // arguments are actually passed as pointers.
4945   QualType ByValType = ValType; // 'CP'
4946   bool IsPassedByAddress = false;
4947   if (!IsC11 && !IsN) {
4948     ByValType = Ptr->getType();
4949     IsPassedByAddress = true;
4950   }
4951 
4952   SmallVector<Expr *, 5> APIOrderedArgs;
4953   if (ArgOrder == Sema::AtomicArgumentOrder::AST) {
4954     APIOrderedArgs.push_back(Args[0]);
4955     switch (Form) {
4956     case Init:
4957     case Load:
4958       APIOrderedArgs.push_back(Args[1]); // Val1/Order
4959       break;
4960     case LoadCopy:
4961     case Copy:
4962     case Arithmetic:
4963     case Xchg:
4964       APIOrderedArgs.push_back(Args[2]); // Val1
4965       APIOrderedArgs.push_back(Args[1]); // Order
4966       break;
4967     case GNUXchg:
4968       APIOrderedArgs.push_back(Args[2]); // Val1
4969       APIOrderedArgs.push_back(Args[3]); // Val2
4970       APIOrderedArgs.push_back(Args[1]); // Order
4971       break;
4972     case C11CmpXchg:
4973       APIOrderedArgs.push_back(Args[2]); // Val1
4974       APIOrderedArgs.push_back(Args[4]); // Val2
4975       APIOrderedArgs.push_back(Args[1]); // Order
4976       APIOrderedArgs.push_back(Args[3]); // OrderFail
4977       break;
4978     case GNUCmpXchg:
4979       APIOrderedArgs.push_back(Args[2]); // Val1
4980       APIOrderedArgs.push_back(Args[4]); // Val2
4981       APIOrderedArgs.push_back(Args[5]); // Weak
4982       APIOrderedArgs.push_back(Args[1]); // Order
4983       APIOrderedArgs.push_back(Args[3]); // OrderFail
4984       break;
4985     }
4986   } else
4987     APIOrderedArgs.append(Args.begin(), Args.end());
4988 
4989   // The first argument's non-CV pointer type is used to deduce the type of
4990   // subsequent arguments, except for:
4991   //  - weak flag (always converted to bool)
4992   //  - memory order (always converted to int)
4993   //  - scope  (always converted to int)
4994   for (unsigned i = 0; i != APIOrderedArgs.size(); ++i) {
4995     QualType Ty;
4996     if (i < NumVals[Form] + 1) {
4997       switch (i) {
4998       case 0:
4999         // The first argument is always a pointer. It has a fixed type.
5000         // It is always dereferenced, a nullptr is undefined.
5001         CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5002         // Nothing else to do: we already know all we want about this pointer.
5003         continue;
5004       case 1:
5005         // The second argument is the non-atomic operand. For arithmetic, this
5006         // is always passed by value, and for a compare_exchange it is always
5007         // passed by address. For the rest, GNU uses by-address and C11 uses
5008         // by-value.
5009         assert(Form != Load);
5010         if (Form == Init || (Form == Arithmetic && ValType->isIntegerType()))
5011           Ty = ValType;
5012         else if (Form == Copy || Form == Xchg) {
5013           if (IsPassedByAddress) {
5014             // The value pointer is always dereferenced, a nullptr is undefined.
5015             CheckNonNullArgument(*this, APIOrderedArgs[i],
5016                                  ExprRange.getBegin());
5017           }
5018           Ty = ByValType;
5019         } else if (Form == Arithmetic)
5020           Ty = Context.getPointerDiffType();
5021         else {
5022           Expr *ValArg = APIOrderedArgs[i];
5023           // The value pointer is always dereferenced, a nullptr is undefined.
5024           CheckNonNullArgument(*this, ValArg, ExprRange.getBegin());
5025           LangAS AS = LangAS::Default;
5026           // Keep address space of non-atomic pointer type.
5027           if (const PointerType *PtrTy =
5028                   ValArg->getType()->getAs<PointerType>()) {
5029             AS = PtrTy->getPointeeType().getAddressSpace();
5030           }
5031           Ty = Context.getPointerType(
5032               Context.getAddrSpaceQualType(ValType.getUnqualifiedType(), AS));
5033         }
5034         break;
5035       case 2:
5036         // The third argument to compare_exchange / GNU exchange is the desired
5037         // value, either by-value (for the C11 and *_n variant) or as a pointer.
5038         if (IsPassedByAddress)
5039           CheckNonNullArgument(*this, APIOrderedArgs[i], ExprRange.getBegin());
5040         Ty = ByValType;
5041         break;
5042       case 3:
5043         // The fourth argument to GNU compare_exchange is a 'weak' flag.
5044         Ty = Context.BoolTy;
5045         break;
5046       }
5047     } else {
5048       // The order(s) and scope are always converted to int.
5049       Ty = Context.IntTy;
5050     }
5051 
5052     InitializedEntity Entity =
5053         InitializedEntity::InitializeParameter(Context, Ty, false);
5054     ExprResult Arg = APIOrderedArgs[i];
5055     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5056     if (Arg.isInvalid())
5057       return true;
5058     APIOrderedArgs[i] = Arg.get();
5059   }
5060 
5061   // Permute the arguments into a 'consistent' order.
5062   SmallVector<Expr*, 5> SubExprs;
5063   SubExprs.push_back(Ptr);
5064   switch (Form) {
5065   case Init:
5066     // Note, AtomicExpr::getVal1() has a special case for this atomic.
5067     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5068     break;
5069   case Load:
5070     SubExprs.push_back(APIOrderedArgs[1]); // Order
5071     break;
5072   case LoadCopy:
5073   case Copy:
5074   case Arithmetic:
5075   case Xchg:
5076     SubExprs.push_back(APIOrderedArgs[2]); // Order
5077     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5078     break;
5079   case GNUXchg:
5080     // Note, AtomicExpr::getVal2() has a special case for this atomic.
5081     SubExprs.push_back(APIOrderedArgs[3]); // Order
5082     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5083     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5084     break;
5085   case C11CmpXchg:
5086     SubExprs.push_back(APIOrderedArgs[3]); // Order
5087     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5088     SubExprs.push_back(APIOrderedArgs[4]); // OrderFail
5089     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5090     break;
5091   case GNUCmpXchg:
5092     SubExprs.push_back(APIOrderedArgs[4]); // Order
5093     SubExprs.push_back(APIOrderedArgs[1]); // Val1
5094     SubExprs.push_back(APIOrderedArgs[5]); // OrderFail
5095     SubExprs.push_back(APIOrderedArgs[2]); // Val2
5096     SubExprs.push_back(APIOrderedArgs[3]); // Weak
5097     break;
5098   }
5099 
5100   if (SubExprs.size() >= 2 && Form != Init) {
5101     if (Optional<llvm::APSInt> Result =
5102             SubExprs[1]->getIntegerConstantExpr(Context))
5103       if (!isValidOrderingForOp(Result->getSExtValue(), Op))
5104         Diag(SubExprs[1]->getBeginLoc(),
5105              diag::warn_atomic_op_has_invalid_memory_order)
5106             << SubExprs[1]->getSourceRange();
5107   }
5108 
5109   if (auto ScopeModel = AtomicExpr::getScopeModel(Op)) {
5110     auto *Scope = Args[Args.size() - 1];
5111     if (Optional<llvm::APSInt> Result =
5112             Scope->getIntegerConstantExpr(Context)) {
5113       if (!ScopeModel->isValid(Result->getZExtValue()))
5114         Diag(Scope->getBeginLoc(), diag::err_atomic_op_has_invalid_synch_scope)
5115             << Scope->getSourceRange();
5116     }
5117     SubExprs.push_back(Scope);
5118   }
5119 
5120   AtomicExpr *AE = new (Context)
5121       AtomicExpr(ExprRange.getBegin(), SubExprs, ResultType, Op, RParenLoc);
5122 
5123   if ((Op == AtomicExpr::AO__c11_atomic_load ||
5124        Op == AtomicExpr::AO__c11_atomic_store ||
5125        Op == AtomicExpr::AO__opencl_atomic_load ||
5126        Op == AtomicExpr::AO__opencl_atomic_store ) &&
5127       Context.AtomicUsesUnsupportedLibcall(AE))
5128     Diag(AE->getBeginLoc(), diag::err_atomic_load_store_uses_lib)
5129         << ((Op == AtomicExpr::AO__c11_atomic_load ||
5130              Op == AtomicExpr::AO__opencl_atomic_load)
5131                 ? 0
5132                 : 1);
5133 
5134   if (ValType->isExtIntType()) {
5135     Diag(Ptr->getExprLoc(), diag::err_atomic_builtin_ext_int_prohibit);
5136     return ExprError();
5137   }
5138 
5139   return AE;
5140 }
5141 
5142 /// checkBuiltinArgument - Given a call to a builtin function, perform
5143 /// normal type-checking on the given argument, updating the call in
5144 /// place.  This is useful when a builtin function requires custom
5145 /// type-checking for some of its arguments but not necessarily all of
5146 /// them.
5147 ///
5148 /// Returns true on error.
5149 static bool checkBuiltinArgument(Sema &S, CallExpr *E, unsigned ArgIndex) {
5150   FunctionDecl *Fn = E->getDirectCallee();
5151   assert(Fn && "builtin call without direct callee!");
5152 
5153   ParmVarDecl *Param = Fn->getParamDecl(ArgIndex);
5154   InitializedEntity Entity =
5155     InitializedEntity::InitializeParameter(S.Context, Param);
5156 
5157   ExprResult Arg = E->getArg(0);
5158   Arg = S.PerformCopyInitialization(Entity, SourceLocation(), Arg);
5159   if (Arg.isInvalid())
5160     return true;
5161 
5162   E->setArg(ArgIndex, Arg.get());
5163   return false;
5164 }
5165 
5166 /// We have a call to a function like __sync_fetch_and_add, which is an
5167 /// overloaded function based on the pointer type of its first argument.
5168 /// The main BuildCallExpr routines have already promoted the types of
5169 /// arguments because all of these calls are prototyped as void(...).
5170 ///
5171 /// This function goes through and does final semantic checking for these
5172 /// builtins, as well as generating any warnings.
5173 ExprResult
5174 Sema::SemaBuiltinAtomicOverloaded(ExprResult TheCallResult) {
5175   CallExpr *TheCall = static_cast<CallExpr *>(TheCallResult.get());
5176   Expr *Callee = TheCall->getCallee();
5177   DeclRefExpr *DRE = cast<DeclRefExpr>(Callee->IgnoreParenCasts());
5178   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5179 
5180   // Ensure that we have at least one argument to do type inference from.
5181   if (TheCall->getNumArgs() < 1) {
5182     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5183         << 0 << 1 << TheCall->getNumArgs() << Callee->getSourceRange();
5184     return ExprError();
5185   }
5186 
5187   // Inspect the first argument of the atomic builtin.  This should always be
5188   // a pointer type, whose element is an integral scalar or pointer type.
5189   // Because it is a pointer type, we don't have to worry about any implicit
5190   // casts here.
5191   // FIXME: We don't allow floating point scalars as input.
5192   Expr *FirstArg = TheCall->getArg(0);
5193   ExprResult FirstArgResult = DefaultFunctionArrayLvalueConversion(FirstArg);
5194   if (FirstArgResult.isInvalid())
5195     return ExprError();
5196   FirstArg = FirstArgResult.get();
5197   TheCall->setArg(0, FirstArg);
5198 
5199   const PointerType *pointerType = FirstArg->getType()->getAs<PointerType>();
5200   if (!pointerType) {
5201     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer)
5202         << FirstArg->getType() << FirstArg->getSourceRange();
5203     return ExprError();
5204   }
5205 
5206   QualType ValType = pointerType->getPointeeType();
5207   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5208       !ValType->isBlockPointerType()) {
5209     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_must_be_pointer_intptr)
5210         << FirstArg->getType() << FirstArg->getSourceRange();
5211     return ExprError();
5212   }
5213 
5214   if (ValType.isConstQualified()) {
5215     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_cannot_be_const)
5216         << FirstArg->getType() << FirstArg->getSourceRange();
5217     return ExprError();
5218   }
5219 
5220   switch (ValType.getObjCLifetime()) {
5221   case Qualifiers::OCL_None:
5222   case Qualifiers::OCL_ExplicitNone:
5223     // okay
5224     break;
5225 
5226   case Qualifiers::OCL_Weak:
5227   case Qualifiers::OCL_Strong:
5228   case Qualifiers::OCL_Autoreleasing:
5229     Diag(DRE->getBeginLoc(), diag::err_arc_atomic_ownership)
5230         << ValType << FirstArg->getSourceRange();
5231     return ExprError();
5232   }
5233 
5234   // Strip any qualifiers off ValType.
5235   ValType = ValType.getUnqualifiedType();
5236 
5237   // The majority of builtins return a value, but a few have special return
5238   // types, so allow them to override appropriately below.
5239   QualType ResultType = ValType;
5240 
5241   // We need to figure out which concrete builtin this maps onto.  For example,
5242   // __sync_fetch_and_add with a 2 byte object turns into
5243   // __sync_fetch_and_add_2.
5244 #define BUILTIN_ROW(x) \
5245   { Builtin::BI##x##_1, Builtin::BI##x##_2, Builtin::BI##x##_4, \
5246     Builtin::BI##x##_8, Builtin::BI##x##_16 }
5247 
5248   static const unsigned BuiltinIndices[][5] = {
5249     BUILTIN_ROW(__sync_fetch_and_add),
5250     BUILTIN_ROW(__sync_fetch_and_sub),
5251     BUILTIN_ROW(__sync_fetch_and_or),
5252     BUILTIN_ROW(__sync_fetch_and_and),
5253     BUILTIN_ROW(__sync_fetch_and_xor),
5254     BUILTIN_ROW(__sync_fetch_and_nand),
5255 
5256     BUILTIN_ROW(__sync_add_and_fetch),
5257     BUILTIN_ROW(__sync_sub_and_fetch),
5258     BUILTIN_ROW(__sync_and_and_fetch),
5259     BUILTIN_ROW(__sync_or_and_fetch),
5260     BUILTIN_ROW(__sync_xor_and_fetch),
5261     BUILTIN_ROW(__sync_nand_and_fetch),
5262 
5263     BUILTIN_ROW(__sync_val_compare_and_swap),
5264     BUILTIN_ROW(__sync_bool_compare_and_swap),
5265     BUILTIN_ROW(__sync_lock_test_and_set),
5266     BUILTIN_ROW(__sync_lock_release),
5267     BUILTIN_ROW(__sync_swap)
5268   };
5269 #undef BUILTIN_ROW
5270 
5271   // Determine the index of the size.
5272   unsigned SizeIndex;
5273   switch (Context.getTypeSizeInChars(ValType).getQuantity()) {
5274   case 1: SizeIndex = 0; break;
5275   case 2: SizeIndex = 1; break;
5276   case 4: SizeIndex = 2; break;
5277   case 8: SizeIndex = 3; break;
5278   case 16: SizeIndex = 4; break;
5279   default:
5280     Diag(DRE->getBeginLoc(), diag::err_atomic_builtin_pointer_size)
5281         << FirstArg->getType() << FirstArg->getSourceRange();
5282     return ExprError();
5283   }
5284 
5285   // Each of these builtins has one pointer argument, followed by some number of
5286   // values (0, 1 or 2) followed by a potentially empty varags list of stuff
5287   // that we ignore.  Find out which row of BuiltinIndices to read from as well
5288   // as the number of fixed args.
5289   unsigned BuiltinID = FDecl->getBuiltinID();
5290   unsigned BuiltinIndex, NumFixed = 1;
5291   bool WarnAboutSemanticsChange = false;
5292   switch (BuiltinID) {
5293   default: llvm_unreachable("Unknown overloaded atomic builtin!");
5294   case Builtin::BI__sync_fetch_and_add:
5295   case Builtin::BI__sync_fetch_and_add_1:
5296   case Builtin::BI__sync_fetch_and_add_2:
5297   case Builtin::BI__sync_fetch_and_add_4:
5298   case Builtin::BI__sync_fetch_and_add_8:
5299   case Builtin::BI__sync_fetch_and_add_16:
5300     BuiltinIndex = 0;
5301     break;
5302 
5303   case Builtin::BI__sync_fetch_and_sub:
5304   case Builtin::BI__sync_fetch_and_sub_1:
5305   case Builtin::BI__sync_fetch_and_sub_2:
5306   case Builtin::BI__sync_fetch_and_sub_4:
5307   case Builtin::BI__sync_fetch_and_sub_8:
5308   case Builtin::BI__sync_fetch_and_sub_16:
5309     BuiltinIndex = 1;
5310     break;
5311 
5312   case Builtin::BI__sync_fetch_and_or:
5313   case Builtin::BI__sync_fetch_and_or_1:
5314   case Builtin::BI__sync_fetch_and_or_2:
5315   case Builtin::BI__sync_fetch_and_or_4:
5316   case Builtin::BI__sync_fetch_and_or_8:
5317   case Builtin::BI__sync_fetch_and_or_16:
5318     BuiltinIndex = 2;
5319     break;
5320 
5321   case Builtin::BI__sync_fetch_and_and:
5322   case Builtin::BI__sync_fetch_and_and_1:
5323   case Builtin::BI__sync_fetch_and_and_2:
5324   case Builtin::BI__sync_fetch_and_and_4:
5325   case Builtin::BI__sync_fetch_and_and_8:
5326   case Builtin::BI__sync_fetch_and_and_16:
5327     BuiltinIndex = 3;
5328     break;
5329 
5330   case Builtin::BI__sync_fetch_and_xor:
5331   case Builtin::BI__sync_fetch_and_xor_1:
5332   case Builtin::BI__sync_fetch_and_xor_2:
5333   case Builtin::BI__sync_fetch_and_xor_4:
5334   case Builtin::BI__sync_fetch_and_xor_8:
5335   case Builtin::BI__sync_fetch_and_xor_16:
5336     BuiltinIndex = 4;
5337     break;
5338 
5339   case Builtin::BI__sync_fetch_and_nand:
5340   case Builtin::BI__sync_fetch_and_nand_1:
5341   case Builtin::BI__sync_fetch_and_nand_2:
5342   case Builtin::BI__sync_fetch_and_nand_4:
5343   case Builtin::BI__sync_fetch_and_nand_8:
5344   case Builtin::BI__sync_fetch_and_nand_16:
5345     BuiltinIndex = 5;
5346     WarnAboutSemanticsChange = true;
5347     break;
5348 
5349   case Builtin::BI__sync_add_and_fetch:
5350   case Builtin::BI__sync_add_and_fetch_1:
5351   case Builtin::BI__sync_add_and_fetch_2:
5352   case Builtin::BI__sync_add_and_fetch_4:
5353   case Builtin::BI__sync_add_and_fetch_8:
5354   case Builtin::BI__sync_add_and_fetch_16:
5355     BuiltinIndex = 6;
5356     break;
5357 
5358   case Builtin::BI__sync_sub_and_fetch:
5359   case Builtin::BI__sync_sub_and_fetch_1:
5360   case Builtin::BI__sync_sub_and_fetch_2:
5361   case Builtin::BI__sync_sub_and_fetch_4:
5362   case Builtin::BI__sync_sub_and_fetch_8:
5363   case Builtin::BI__sync_sub_and_fetch_16:
5364     BuiltinIndex = 7;
5365     break;
5366 
5367   case Builtin::BI__sync_and_and_fetch:
5368   case Builtin::BI__sync_and_and_fetch_1:
5369   case Builtin::BI__sync_and_and_fetch_2:
5370   case Builtin::BI__sync_and_and_fetch_4:
5371   case Builtin::BI__sync_and_and_fetch_8:
5372   case Builtin::BI__sync_and_and_fetch_16:
5373     BuiltinIndex = 8;
5374     break;
5375 
5376   case Builtin::BI__sync_or_and_fetch:
5377   case Builtin::BI__sync_or_and_fetch_1:
5378   case Builtin::BI__sync_or_and_fetch_2:
5379   case Builtin::BI__sync_or_and_fetch_4:
5380   case Builtin::BI__sync_or_and_fetch_8:
5381   case Builtin::BI__sync_or_and_fetch_16:
5382     BuiltinIndex = 9;
5383     break;
5384 
5385   case Builtin::BI__sync_xor_and_fetch:
5386   case Builtin::BI__sync_xor_and_fetch_1:
5387   case Builtin::BI__sync_xor_and_fetch_2:
5388   case Builtin::BI__sync_xor_and_fetch_4:
5389   case Builtin::BI__sync_xor_and_fetch_8:
5390   case Builtin::BI__sync_xor_and_fetch_16:
5391     BuiltinIndex = 10;
5392     break;
5393 
5394   case Builtin::BI__sync_nand_and_fetch:
5395   case Builtin::BI__sync_nand_and_fetch_1:
5396   case Builtin::BI__sync_nand_and_fetch_2:
5397   case Builtin::BI__sync_nand_and_fetch_4:
5398   case Builtin::BI__sync_nand_and_fetch_8:
5399   case Builtin::BI__sync_nand_and_fetch_16:
5400     BuiltinIndex = 11;
5401     WarnAboutSemanticsChange = true;
5402     break;
5403 
5404   case Builtin::BI__sync_val_compare_and_swap:
5405   case Builtin::BI__sync_val_compare_and_swap_1:
5406   case Builtin::BI__sync_val_compare_and_swap_2:
5407   case Builtin::BI__sync_val_compare_and_swap_4:
5408   case Builtin::BI__sync_val_compare_and_swap_8:
5409   case Builtin::BI__sync_val_compare_and_swap_16:
5410     BuiltinIndex = 12;
5411     NumFixed = 2;
5412     break;
5413 
5414   case Builtin::BI__sync_bool_compare_and_swap:
5415   case Builtin::BI__sync_bool_compare_and_swap_1:
5416   case Builtin::BI__sync_bool_compare_and_swap_2:
5417   case Builtin::BI__sync_bool_compare_and_swap_4:
5418   case Builtin::BI__sync_bool_compare_and_swap_8:
5419   case Builtin::BI__sync_bool_compare_and_swap_16:
5420     BuiltinIndex = 13;
5421     NumFixed = 2;
5422     ResultType = Context.BoolTy;
5423     break;
5424 
5425   case Builtin::BI__sync_lock_test_and_set:
5426   case Builtin::BI__sync_lock_test_and_set_1:
5427   case Builtin::BI__sync_lock_test_and_set_2:
5428   case Builtin::BI__sync_lock_test_and_set_4:
5429   case Builtin::BI__sync_lock_test_and_set_8:
5430   case Builtin::BI__sync_lock_test_and_set_16:
5431     BuiltinIndex = 14;
5432     break;
5433 
5434   case Builtin::BI__sync_lock_release:
5435   case Builtin::BI__sync_lock_release_1:
5436   case Builtin::BI__sync_lock_release_2:
5437   case Builtin::BI__sync_lock_release_4:
5438   case Builtin::BI__sync_lock_release_8:
5439   case Builtin::BI__sync_lock_release_16:
5440     BuiltinIndex = 15;
5441     NumFixed = 0;
5442     ResultType = Context.VoidTy;
5443     break;
5444 
5445   case Builtin::BI__sync_swap:
5446   case Builtin::BI__sync_swap_1:
5447   case Builtin::BI__sync_swap_2:
5448   case Builtin::BI__sync_swap_4:
5449   case Builtin::BI__sync_swap_8:
5450   case Builtin::BI__sync_swap_16:
5451     BuiltinIndex = 16;
5452     break;
5453   }
5454 
5455   // Now that we know how many fixed arguments we expect, first check that we
5456   // have at least that many.
5457   if (TheCall->getNumArgs() < 1+NumFixed) {
5458     Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args_at_least)
5459         << 0 << 1 + NumFixed << TheCall->getNumArgs()
5460         << Callee->getSourceRange();
5461     return ExprError();
5462   }
5463 
5464   Diag(TheCall->getEndLoc(), diag::warn_atomic_implicit_seq_cst)
5465       << Callee->getSourceRange();
5466 
5467   if (WarnAboutSemanticsChange) {
5468     Diag(TheCall->getEndLoc(), diag::warn_sync_fetch_and_nand_semantics_change)
5469         << Callee->getSourceRange();
5470   }
5471 
5472   // Get the decl for the concrete builtin from this, we can tell what the
5473   // concrete integer type we should convert to is.
5474   unsigned NewBuiltinID = BuiltinIndices[BuiltinIndex][SizeIndex];
5475   const char *NewBuiltinName = Context.BuiltinInfo.getName(NewBuiltinID);
5476   FunctionDecl *NewBuiltinDecl;
5477   if (NewBuiltinID == BuiltinID)
5478     NewBuiltinDecl = FDecl;
5479   else {
5480     // Perform builtin lookup to avoid redeclaring it.
5481     DeclarationName DN(&Context.Idents.get(NewBuiltinName));
5482     LookupResult Res(*this, DN, DRE->getBeginLoc(), LookupOrdinaryName);
5483     LookupName(Res, TUScope, /*AllowBuiltinCreation=*/true);
5484     assert(Res.getFoundDecl());
5485     NewBuiltinDecl = dyn_cast<FunctionDecl>(Res.getFoundDecl());
5486     if (!NewBuiltinDecl)
5487       return ExprError();
5488   }
5489 
5490   // The first argument --- the pointer --- has a fixed type; we
5491   // deduce the types of the rest of the arguments accordingly.  Walk
5492   // the remaining arguments, converting them to the deduced value type.
5493   for (unsigned i = 0; i != NumFixed; ++i) {
5494     ExprResult Arg = TheCall->getArg(i+1);
5495 
5496     // GCC does an implicit conversion to the pointer or integer ValType.  This
5497     // can fail in some cases (1i -> int**), check for this error case now.
5498     // Initialize the argument.
5499     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
5500                                                    ValType, /*consume*/ false);
5501     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
5502     if (Arg.isInvalid())
5503       return ExprError();
5504 
5505     // Okay, we have something that *can* be converted to the right type.  Check
5506     // to see if there is a potentially weird extension going on here.  This can
5507     // happen when you do an atomic operation on something like an char* and
5508     // pass in 42.  The 42 gets converted to char.  This is even more strange
5509     // for things like 45.123 -> char, etc.
5510     // FIXME: Do this check.
5511     TheCall->setArg(i+1, Arg.get());
5512   }
5513 
5514   // Create a new DeclRefExpr to refer to the new decl.
5515   DeclRefExpr *NewDRE = DeclRefExpr::Create(
5516       Context, DRE->getQualifierLoc(), SourceLocation(), NewBuiltinDecl,
5517       /*enclosing*/ false, DRE->getLocation(), Context.BuiltinFnTy,
5518       DRE->getValueKind(), nullptr, nullptr, DRE->isNonOdrUse());
5519 
5520   // Set the callee in the CallExpr.
5521   // FIXME: This loses syntactic information.
5522   QualType CalleePtrTy = Context.getPointerType(NewBuiltinDecl->getType());
5523   ExprResult PromotedCall = ImpCastExprToType(NewDRE, CalleePtrTy,
5524                                               CK_BuiltinFnToFnPtr);
5525   TheCall->setCallee(PromotedCall.get());
5526 
5527   // Change the result type of the call to match the original value type. This
5528   // is arbitrary, but the codegen for these builtins ins design to handle it
5529   // gracefully.
5530   TheCall->setType(ResultType);
5531 
5532   // Prohibit use of _ExtInt with atomic builtins.
5533   // The arguments would have already been converted to the first argument's
5534   // type, so only need to check the first argument.
5535   const auto *ExtIntValType = ValType->getAs<ExtIntType>();
5536   if (ExtIntValType && !llvm::isPowerOf2_64(ExtIntValType->getNumBits())) {
5537     Diag(FirstArg->getExprLoc(), diag::err_atomic_builtin_ext_int_size);
5538     return ExprError();
5539   }
5540 
5541   return TheCallResult;
5542 }
5543 
5544 /// SemaBuiltinNontemporalOverloaded - We have a call to
5545 /// __builtin_nontemporal_store or __builtin_nontemporal_load, which is an
5546 /// overloaded function based on the pointer type of its last argument.
5547 ///
5548 /// This function goes through and does final semantic checking for these
5549 /// builtins.
5550 ExprResult Sema::SemaBuiltinNontemporalOverloaded(ExprResult TheCallResult) {
5551   CallExpr *TheCall = (CallExpr *)TheCallResult.get();
5552   DeclRefExpr *DRE =
5553       cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
5554   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
5555   unsigned BuiltinID = FDecl->getBuiltinID();
5556   assert((BuiltinID == Builtin::BI__builtin_nontemporal_store ||
5557           BuiltinID == Builtin::BI__builtin_nontemporal_load) &&
5558          "Unexpected nontemporal load/store builtin!");
5559   bool isStore = BuiltinID == Builtin::BI__builtin_nontemporal_store;
5560   unsigned numArgs = isStore ? 2 : 1;
5561 
5562   // Ensure that we have the proper number of arguments.
5563   if (checkArgCount(*this, TheCall, numArgs))
5564     return ExprError();
5565 
5566   // Inspect the last argument of the nontemporal builtin.  This should always
5567   // be a pointer type, from which we imply the type of the memory access.
5568   // Because it is a pointer type, we don't have to worry about any implicit
5569   // casts here.
5570   Expr *PointerArg = TheCall->getArg(numArgs - 1);
5571   ExprResult PointerArgResult =
5572       DefaultFunctionArrayLvalueConversion(PointerArg);
5573 
5574   if (PointerArgResult.isInvalid())
5575     return ExprError();
5576   PointerArg = PointerArgResult.get();
5577   TheCall->setArg(numArgs - 1, PointerArg);
5578 
5579   const PointerType *pointerType = PointerArg->getType()->getAs<PointerType>();
5580   if (!pointerType) {
5581     Diag(DRE->getBeginLoc(), diag::err_nontemporal_builtin_must_be_pointer)
5582         << PointerArg->getType() << PointerArg->getSourceRange();
5583     return ExprError();
5584   }
5585 
5586   QualType ValType = pointerType->getPointeeType();
5587 
5588   // Strip any qualifiers off ValType.
5589   ValType = ValType.getUnqualifiedType();
5590   if (!ValType->isIntegerType() && !ValType->isAnyPointerType() &&
5591       !ValType->isBlockPointerType() && !ValType->isFloatingType() &&
5592       !ValType->isVectorType()) {
5593     Diag(DRE->getBeginLoc(),
5594          diag::err_nontemporal_builtin_must_be_pointer_intfltptr_or_vector)
5595         << PointerArg->getType() << PointerArg->getSourceRange();
5596     return ExprError();
5597   }
5598 
5599   if (!isStore) {
5600     TheCall->setType(ValType);
5601     return TheCallResult;
5602   }
5603 
5604   ExprResult ValArg = TheCall->getArg(0);
5605   InitializedEntity Entity = InitializedEntity::InitializeParameter(
5606       Context, ValType, /*consume*/ false);
5607   ValArg = PerformCopyInitialization(Entity, SourceLocation(), ValArg);
5608   if (ValArg.isInvalid())
5609     return ExprError();
5610 
5611   TheCall->setArg(0, ValArg.get());
5612   TheCall->setType(Context.VoidTy);
5613   return TheCallResult;
5614 }
5615 
5616 /// CheckObjCString - Checks that the argument to the builtin
5617 /// CFString constructor is correct
5618 /// Note: It might also make sense to do the UTF-16 conversion here (would
5619 /// simplify the backend).
5620 bool Sema::CheckObjCString(Expr *Arg) {
5621   Arg = Arg->IgnoreParenCasts();
5622   StringLiteral *Literal = dyn_cast<StringLiteral>(Arg);
5623 
5624   if (!Literal || !Literal->isAscii()) {
5625     Diag(Arg->getBeginLoc(), diag::err_cfstring_literal_not_string_constant)
5626         << Arg->getSourceRange();
5627     return true;
5628   }
5629 
5630   if (Literal->containsNonAsciiOrNull()) {
5631     StringRef String = Literal->getString();
5632     unsigned NumBytes = String.size();
5633     SmallVector<llvm::UTF16, 128> ToBuf(NumBytes);
5634     const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)String.data();
5635     llvm::UTF16 *ToPtr = &ToBuf[0];
5636 
5637     llvm::ConversionResult Result =
5638         llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes, &ToPtr,
5639                                  ToPtr + NumBytes, llvm::strictConversion);
5640     // Check for conversion failure.
5641     if (Result != llvm::conversionOK)
5642       Diag(Arg->getBeginLoc(), diag::warn_cfstring_truncated)
5643           << Arg->getSourceRange();
5644   }
5645   return false;
5646 }
5647 
5648 /// CheckObjCString - Checks that the format string argument to the os_log()
5649 /// and os_trace() functions is correct, and converts it to const char *.
5650 ExprResult Sema::CheckOSLogFormatStringArg(Expr *Arg) {
5651   Arg = Arg->IgnoreParenCasts();
5652   auto *Literal = dyn_cast<StringLiteral>(Arg);
5653   if (!Literal) {
5654     if (auto *ObjcLiteral = dyn_cast<ObjCStringLiteral>(Arg)) {
5655       Literal = ObjcLiteral->getString();
5656     }
5657   }
5658 
5659   if (!Literal || (!Literal->isAscii() && !Literal->isUTF8())) {
5660     return ExprError(
5661         Diag(Arg->getBeginLoc(), diag::err_os_log_format_not_string_constant)
5662         << Arg->getSourceRange());
5663   }
5664 
5665   ExprResult Result(Literal);
5666   QualType ResultTy = Context.getPointerType(Context.CharTy.withConst());
5667   InitializedEntity Entity =
5668       InitializedEntity::InitializeParameter(Context, ResultTy, false);
5669   Result = PerformCopyInitialization(Entity, SourceLocation(), Result);
5670   return Result;
5671 }
5672 
5673 /// Check that the user is calling the appropriate va_start builtin for the
5674 /// target and calling convention.
5675 static bool checkVAStartABI(Sema &S, unsigned BuiltinID, Expr *Fn) {
5676   const llvm::Triple &TT = S.Context.getTargetInfo().getTriple();
5677   bool IsX64 = TT.getArch() == llvm::Triple::x86_64;
5678   bool IsAArch64 = (TT.getArch() == llvm::Triple::aarch64 ||
5679                     TT.getArch() == llvm::Triple::aarch64_32);
5680   bool IsWindows = TT.isOSWindows();
5681   bool IsMSVAStart = BuiltinID == Builtin::BI__builtin_ms_va_start;
5682   if (IsX64 || IsAArch64) {
5683     CallingConv CC = CC_C;
5684     if (const FunctionDecl *FD = S.getCurFunctionDecl())
5685       CC = FD->getType()->castAs<FunctionType>()->getCallConv();
5686     if (IsMSVAStart) {
5687       // Don't allow this in System V ABI functions.
5688       if (CC == CC_X86_64SysV || (!IsWindows && CC != CC_Win64))
5689         return S.Diag(Fn->getBeginLoc(),
5690                       diag::err_ms_va_start_used_in_sysv_function);
5691     } else {
5692       // On x86-64/AArch64 Unix, don't allow this in Win64 ABI functions.
5693       // On x64 Windows, don't allow this in System V ABI functions.
5694       // (Yes, that means there's no corresponding way to support variadic
5695       // System V ABI functions on Windows.)
5696       if ((IsWindows && CC == CC_X86_64SysV) ||
5697           (!IsWindows && CC == CC_Win64))
5698         return S.Diag(Fn->getBeginLoc(),
5699                       diag::err_va_start_used_in_wrong_abi_function)
5700                << !IsWindows;
5701     }
5702     return false;
5703   }
5704 
5705   if (IsMSVAStart)
5706     return S.Diag(Fn->getBeginLoc(), diag::err_builtin_x64_aarch64_only);
5707   return false;
5708 }
5709 
5710 static bool checkVAStartIsInVariadicFunction(Sema &S, Expr *Fn,
5711                                              ParmVarDecl **LastParam = nullptr) {
5712   // Determine whether the current function, block, or obj-c method is variadic
5713   // and get its parameter list.
5714   bool IsVariadic = false;
5715   ArrayRef<ParmVarDecl *> Params;
5716   DeclContext *Caller = S.CurContext;
5717   if (auto *Block = dyn_cast<BlockDecl>(Caller)) {
5718     IsVariadic = Block->isVariadic();
5719     Params = Block->parameters();
5720   } else if (auto *FD = dyn_cast<FunctionDecl>(Caller)) {
5721     IsVariadic = FD->isVariadic();
5722     Params = FD->parameters();
5723   } else if (auto *MD = dyn_cast<ObjCMethodDecl>(Caller)) {
5724     IsVariadic = MD->isVariadic();
5725     // FIXME: This isn't correct for methods (results in bogus warning).
5726     Params = MD->parameters();
5727   } else if (isa<CapturedDecl>(Caller)) {
5728     // We don't support va_start in a CapturedDecl.
5729     S.Diag(Fn->getBeginLoc(), diag::err_va_start_captured_stmt);
5730     return true;
5731   } else {
5732     // This must be some other declcontext that parses exprs.
5733     S.Diag(Fn->getBeginLoc(), diag::err_va_start_outside_function);
5734     return true;
5735   }
5736 
5737   if (!IsVariadic) {
5738     S.Diag(Fn->getBeginLoc(), diag::err_va_start_fixed_function);
5739     return true;
5740   }
5741 
5742   if (LastParam)
5743     *LastParam = Params.empty() ? nullptr : Params.back();
5744 
5745   return false;
5746 }
5747 
5748 /// Check the arguments to '__builtin_va_start' or '__builtin_ms_va_start'
5749 /// for validity.  Emit an error and return true on failure; return false
5750 /// on success.
5751 bool Sema::SemaBuiltinVAStart(unsigned BuiltinID, CallExpr *TheCall) {
5752   Expr *Fn = TheCall->getCallee();
5753 
5754   if (checkVAStartABI(*this, BuiltinID, Fn))
5755     return true;
5756 
5757   if (checkArgCount(*this, TheCall, 2))
5758     return true;
5759 
5760   // Type-check the first argument normally.
5761   if (checkBuiltinArgument(*this, TheCall, 0))
5762     return true;
5763 
5764   // Check that the current function is variadic, and get its last parameter.
5765   ParmVarDecl *LastParam;
5766   if (checkVAStartIsInVariadicFunction(*this, Fn, &LastParam))
5767     return true;
5768 
5769   // Verify that the second argument to the builtin is the last argument of the
5770   // current function or method.
5771   bool SecondArgIsLastNamedArgument = false;
5772   const Expr *Arg = TheCall->getArg(1)->IgnoreParenCasts();
5773 
5774   // These are valid if SecondArgIsLastNamedArgument is false after the next
5775   // block.
5776   QualType Type;
5777   SourceLocation ParamLoc;
5778   bool IsCRegister = false;
5779 
5780   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Arg)) {
5781     if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(DR->getDecl())) {
5782       SecondArgIsLastNamedArgument = PV == LastParam;
5783 
5784       Type = PV->getType();
5785       ParamLoc = PV->getLocation();
5786       IsCRegister =
5787           PV->getStorageClass() == SC_Register && !getLangOpts().CPlusPlus;
5788     }
5789   }
5790 
5791   if (!SecondArgIsLastNamedArgument)
5792     Diag(TheCall->getArg(1)->getBeginLoc(),
5793          diag::warn_second_arg_of_va_start_not_last_named_param);
5794   else if (IsCRegister || Type->isReferenceType() ||
5795            Type->isSpecificBuiltinType(BuiltinType::Float) || [=] {
5796              // Promotable integers are UB, but enumerations need a bit of
5797              // extra checking to see what their promotable type actually is.
5798              if (!Type->isPromotableIntegerType())
5799                return false;
5800              if (!Type->isEnumeralType())
5801                return true;
5802              const EnumDecl *ED = Type->castAs<EnumType>()->getDecl();
5803              return !(ED &&
5804                       Context.typesAreCompatible(ED->getPromotionType(), Type));
5805            }()) {
5806     unsigned Reason = 0;
5807     if (Type->isReferenceType())  Reason = 1;
5808     else if (IsCRegister)         Reason = 2;
5809     Diag(Arg->getBeginLoc(), diag::warn_va_start_type_is_undefined) << Reason;
5810     Diag(ParamLoc, diag::note_parameter_type) << Type;
5811   }
5812 
5813   TheCall->setType(Context.VoidTy);
5814   return false;
5815 }
5816 
5817 bool Sema::SemaBuiltinVAStartARMMicrosoft(CallExpr *Call) {
5818   // void __va_start(va_list *ap, const char *named_addr, size_t slot_size,
5819   //                 const char *named_addr);
5820 
5821   Expr *Func = Call->getCallee();
5822 
5823   if (Call->getNumArgs() < 3)
5824     return Diag(Call->getEndLoc(),
5825                 diag::err_typecheck_call_too_few_args_at_least)
5826            << 0 /*function call*/ << 3 << Call->getNumArgs();
5827 
5828   // Type-check the first argument normally.
5829   if (checkBuiltinArgument(*this, Call, 0))
5830     return true;
5831 
5832   // Check that the current function is variadic.
5833   if (checkVAStartIsInVariadicFunction(*this, Func))
5834     return true;
5835 
5836   // __va_start on Windows does not validate the parameter qualifiers
5837 
5838   const Expr *Arg1 = Call->getArg(1)->IgnoreParens();
5839   const Type *Arg1Ty = Arg1->getType().getCanonicalType().getTypePtr();
5840 
5841   const Expr *Arg2 = Call->getArg(2)->IgnoreParens();
5842   const Type *Arg2Ty = Arg2->getType().getCanonicalType().getTypePtr();
5843 
5844   const QualType &ConstCharPtrTy =
5845       Context.getPointerType(Context.CharTy.withConst());
5846   if (!Arg1Ty->isPointerType() ||
5847       Arg1Ty->getPointeeType().withoutLocalFastQualifiers() != Context.CharTy)
5848     Diag(Arg1->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5849         << Arg1->getType() << ConstCharPtrTy << 1 /* different class */
5850         << 0                                      /* qualifier difference */
5851         << 3                                      /* parameter mismatch */
5852         << 2 << Arg1->getType() << ConstCharPtrTy;
5853 
5854   const QualType SizeTy = Context.getSizeType();
5855   if (Arg2Ty->getCanonicalTypeInternal().withoutLocalFastQualifiers() != SizeTy)
5856     Diag(Arg2->getBeginLoc(), diag::err_typecheck_convert_incompatible)
5857         << Arg2->getType() << SizeTy << 1 /* different class */
5858         << 0                              /* qualifier difference */
5859         << 3                              /* parameter mismatch */
5860         << 3 << Arg2->getType() << SizeTy;
5861 
5862   return false;
5863 }
5864 
5865 /// SemaBuiltinUnorderedCompare - Handle functions like __builtin_isgreater and
5866 /// friends.  This is declared to take (...), so we have to check everything.
5867 bool Sema::SemaBuiltinUnorderedCompare(CallExpr *TheCall) {
5868   if (checkArgCount(*this, TheCall, 2))
5869     return true;
5870 
5871   ExprResult OrigArg0 = TheCall->getArg(0);
5872   ExprResult OrigArg1 = TheCall->getArg(1);
5873 
5874   // Do standard promotions between the two arguments, returning their common
5875   // type.
5876   QualType Res = UsualArithmeticConversions(
5877       OrigArg0, OrigArg1, TheCall->getExprLoc(), ACK_Comparison);
5878   if (OrigArg0.isInvalid() || OrigArg1.isInvalid())
5879     return true;
5880 
5881   // Make sure any conversions are pushed back into the call; this is
5882   // type safe since unordered compare builtins are declared as "_Bool
5883   // foo(...)".
5884   TheCall->setArg(0, OrigArg0.get());
5885   TheCall->setArg(1, OrigArg1.get());
5886 
5887   if (OrigArg0.get()->isTypeDependent() || OrigArg1.get()->isTypeDependent())
5888     return false;
5889 
5890   // If the common type isn't a real floating type, then the arguments were
5891   // invalid for this operation.
5892   if (Res.isNull() || !Res->isRealFloatingType())
5893     return Diag(OrigArg0.get()->getBeginLoc(),
5894                 diag::err_typecheck_call_invalid_ordered_compare)
5895            << OrigArg0.get()->getType() << OrigArg1.get()->getType()
5896            << SourceRange(OrigArg0.get()->getBeginLoc(),
5897                           OrigArg1.get()->getEndLoc());
5898 
5899   return false;
5900 }
5901 
5902 /// SemaBuiltinSemaBuiltinFPClassification - Handle functions like
5903 /// __builtin_isnan and friends.  This is declared to take (...), so we have
5904 /// to check everything. We expect the last argument to be a floating point
5905 /// value.
5906 bool Sema::SemaBuiltinFPClassification(CallExpr *TheCall, unsigned NumArgs) {
5907   if (checkArgCount(*this, TheCall, NumArgs))
5908     return true;
5909 
5910   // __builtin_fpclassify is the only case where NumArgs != 1, so we can count
5911   // on all preceding parameters just being int.  Try all of those.
5912   for (unsigned i = 0; i < NumArgs - 1; ++i) {
5913     Expr *Arg = TheCall->getArg(i);
5914 
5915     if (Arg->isTypeDependent())
5916       return false;
5917 
5918     ExprResult Res = PerformImplicitConversion(Arg, Context.IntTy, AA_Passing);
5919 
5920     if (Res.isInvalid())
5921       return true;
5922     TheCall->setArg(i, Res.get());
5923   }
5924 
5925   Expr *OrigArg = TheCall->getArg(NumArgs-1);
5926 
5927   if (OrigArg->isTypeDependent())
5928     return false;
5929 
5930   // Usual Unary Conversions will convert half to float, which we want for
5931   // machines that use fp16 conversion intrinsics. Else, we wnat to leave the
5932   // type how it is, but do normal L->Rvalue conversions.
5933   if (Context.getTargetInfo().useFP16ConversionIntrinsics())
5934     OrigArg = UsualUnaryConversions(OrigArg).get();
5935   else
5936     OrigArg = DefaultFunctionArrayLvalueConversion(OrigArg).get();
5937   TheCall->setArg(NumArgs - 1, OrigArg);
5938 
5939   // This operation requires a non-_Complex floating-point number.
5940   if (!OrigArg->getType()->isRealFloatingType())
5941     return Diag(OrigArg->getBeginLoc(),
5942                 diag::err_typecheck_call_invalid_unary_fp)
5943            << OrigArg->getType() << OrigArg->getSourceRange();
5944 
5945   return false;
5946 }
5947 
5948 /// Perform semantic analysis for a call to __builtin_complex.
5949 bool Sema::SemaBuiltinComplex(CallExpr *TheCall) {
5950   if (checkArgCount(*this, TheCall, 2))
5951     return true;
5952 
5953   bool Dependent = false;
5954   for (unsigned I = 0; I != 2; ++I) {
5955     Expr *Arg = TheCall->getArg(I);
5956     QualType T = Arg->getType();
5957     if (T->isDependentType()) {
5958       Dependent = true;
5959       continue;
5960     }
5961 
5962     // Despite supporting _Complex int, GCC requires a real floating point type
5963     // for the operands of __builtin_complex.
5964     if (!T->isRealFloatingType()) {
5965       return Diag(Arg->getBeginLoc(), diag::err_typecheck_call_requires_real_fp)
5966              << Arg->getType() << Arg->getSourceRange();
5967     }
5968 
5969     ExprResult Converted = DefaultLvalueConversion(Arg);
5970     if (Converted.isInvalid())
5971       return true;
5972     TheCall->setArg(I, Converted.get());
5973   }
5974 
5975   if (Dependent) {
5976     TheCall->setType(Context.DependentTy);
5977     return false;
5978   }
5979 
5980   Expr *Real = TheCall->getArg(0);
5981   Expr *Imag = TheCall->getArg(1);
5982   if (!Context.hasSameType(Real->getType(), Imag->getType())) {
5983     return Diag(Real->getBeginLoc(),
5984                 diag::err_typecheck_call_different_arg_types)
5985            << Real->getType() << Imag->getType()
5986            << Real->getSourceRange() << Imag->getSourceRange();
5987   }
5988 
5989   // We don't allow _Complex _Float16 nor _Complex __fp16 as type specifiers;
5990   // don't allow this builtin to form those types either.
5991   // FIXME: Should we allow these types?
5992   if (Real->getType()->isFloat16Type())
5993     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5994            << "_Float16";
5995   if (Real->getType()->isHalfType())
5996     return Diag(TheCall->getBeginLoc(), diag::err_invalid_complex_spec)
5997            << "half";
5998 
5999   TheCall->setType(Context.getComplexType(Real->getType()));
6000   return false;
6001 }
6002 
6003 // Customized Sema Checking for VSX builtins that have the following signature:
6004 // vector [...] builtinName(vector [...], vector [...], const int);
6005 // Which takes the same type of vectors (any legal vector type) for the first
6006 // two arguments and takes compile time constant for the third argument.
6007 // Example builtins are :
6008 // vector double vec_xxpermdi(vector double, vector double, int);
6009 // vector short vec_xxsldwi(vector short, vector short, int);
6010 bool Sema::SemaBuiltinVSX(CallExpr *TheCall) {
6011   unsigned ExpectedNumArgs = 3;
6012   if (checkArgCount(*this, TheCall, ExpectedNumArgs))
6013     return true;
6014 
6015   // Check the third argument is a compile time constant
6016   if (!TheCall->getArg(2)->isIntegerConstantExpr(Context))
6017     return Diag(TheCall->getBeginLoc(),
6018                 diag::err_vsx_builtin_nonconstant_argument)
6019            << 3 /* argument index */ << TheCall->getDirectCallee()
6020            << SourceRange(TheCall->getArg(2)->getBeginLoc(),
6021                           TheCall->getArg(2)->getEndLoc());
6022 
6023   QualType Arg1Ty = TheCall->getArg(0)->getType();
6024   QualType Arg2Ty = TheCall->getArg(1)->getType();
6025 
6026   // Check the type of argument 1 and argument 2 are vectors.
6027   SourceLocation BuiltinLoc = TheCall->getBeginLoc();
6028   if ((!Arg1Ty->isVectorType() && !Arg1Ty->isDependentType()) ||
6029       (!Arg2Ty->isVectorType() && !Arg2Ty->isDependentType())) {
6030     return Diag(BuiltinLoc, diag::err_vec_builtin_non_vector)
6031            << TheCall->getDirectCallee()
6032            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6033                           TheCall->getArg(1)->getEndLoc());
6034   }
6035 
6036   // Check the first two arguments are the same type.
6037   if (!Context.hasSameUnqualifiedType(Arg1Ty, Arg2Ty)) {
6038     return Diag(BuiltinLoc, diag::err_vec_builtin_incompatible_vector)
6039            << TheCall->getDirectCallee()
6040            << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6041                           TheCall->getArg(1)->getEndLoc());
6042   }
6043 
6044   // When default clang type checking is turned off and the customized type
6045   // checking is used, the returning type of the function must be explicitly
6046   // set. Otherwise it is _Bool by default.
6047   TheCall->setType(Arg1Ty);
6048 
6049   return false;
6050 }
6051 
6052 /// SemaBuiltinShuffleVector - Handle __builtin_shufflevector.
6053 // This is declared to take (...), so we have to check everything.
6054 ExprResult Sema::SemaBuiltinShuffleVector(CallExpr *TheCall) {
6055   if (TheCall->getNumArgs() < 2)
6056     return ExprError(Diag(TheCall->getEndLoc(),
6057                           diag::err_typecheck_call_too_few_args_at_least)
6058                      << 0 /*function call*/ << 2 << TheCall->getNumArgs()
6059                      << TheCall->getSourceRange());
6060 
6061   // Determine which of the following types of shufflevector we're checking:
6062   // 1) unary, vector mask: (lhs, mask)
6063   // 2) binary, scalar mask: (lhs, rhs, index, ..., index)
6064   QualType resType = TheCall->getArg(0)->getType();
6065   unsigned numElements = 0;
6066 
6067   if (!TheCall->getArg(0)->isTypeDependent() &&
6068       !TheCall->getArg(1)->isTypeDependent()) {
6069     QualType LHSType = TheCall->getArg(0)->getType();
6070     QualType RHSType = TheCall->getArg(1)->getType();
6071 
6072     if (!LHSType->isVectorType() || !RHSType->isVectorType())
6073       return ExprError(
6074           Diag(TheCall->getBeginLoc(), diag::err_vec_builtin_non_vector)
6075           << TheCall->getDirectCallee()
6076           << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6077                          TheCall->getArg(1)->getEndLoc()));
6078 
6079     numElements = LHSType->castAs<VectorType>()->getNumElements();
6080     unsigned numResElements = TheCall->getNumArgs() - 2;
6081 
6082     // Check to see if we have a call with 2 vector arguments, the unary shuffle
6083     // with mask.  If so, verify that RHS is an integer vector type with the
6084     // same number of elts as lhs.
6085     if (TheCall->getNumArgs() == 2) {
6086       if (!RHSType->hasIntegerRepresentation() ||
6087           RHSType->castAs<VectorType>()->getNumElements() != numElements)
6088         return ExprError(Diag(TheCall->getBeginLoc(),
6089                               diag::err_vec_builtin_incompatible_vector)
6090                          << TheCall->getDirectCallee()
6091                          << SourceRange(TheCall->getArg(1)->getBeginLoc(),
6092                                         TheCall->getArg(1)->getEndLoc()));
6093     } else if (!Context.hasSameUnqualifiedType(LHSType, RHSType)) {
6094       return ExprError(Diag(TheCall->getBeginLoc(),
6095                             diag::err_vec_builtin_incompatible_vector)
6096                        << TheCall->getDirectCallee()
6097                        << SourceRange(TheCall->getArg(0)->getBeginLoc(),
6098                                       TheCall->getArg(1)->getEndLoc()));
6099     } else if (numElements != numResElements) {
6100       QualType eltType = LHSType->castAs<VectorType>()->getElementType();
6101       resType = Context.getVectorType(eltType, numResElements,
6102                                       VectorType::GenericVector);
6103     }
6104   }
6105 
6106   for (unsigned i = 2; i < TheCall->getNumArgs(); i++) {
6107     if (TheCall->getArg(i)->isTypeDependent() ||
6108         TheCall->getArg(i)->isValueDependent())
6109       continue;
6110 
6111     Optional<llvm::APSInt> Result;
6112     if (!(Result = TheCall->getArg(i)->getIntegerConstantExpr(Context)))
6113       return ExprError(Diag(TheCall->getBeginLoc(),
6114                             diag::err_shufflevector_nonconstant_argument)
6115                        << TheCall->getArg(i)->getSourceRange());
6116 
6117     // Allow -1 which will be translated to undef in the IR.
6118     if (Result->isSigned() && Result->isAllOnesValue())
6119       continue;
6120 
6121     if (Result->getActiveBits() > 64 ||
6122         Result->getZExtValue() >= numElements * 2)
6123       return ExprError(Diag(TheCall->getBeginLoc(),
6124                             diag::err_shufflevector_argument_too_large)
6125                        << TheCall->getArg(i)->getSourceRange());
6126   }
6127 
6128   SmallVector<Expr*, 32> exprs;
6129 
6130   for (unsigned i = 0, e = TheCall->getNumArgs(); i != e; i++) {
6131     exprs.push_back(TheCall->getArg(i));
6132     TheCall->setArg(i, nullptr);
6133   }
6134 
6135   return new (Context) ShuffleVectorExpr(Context, exprs, resType,
6136                                          TheCall->getCallee()->getBeginLoc(),
6137                                          TheCall->getRParenLoc());
6138 }
6139 
6140 /// SemaConvertVectorExpr - Handle __builtin_convertvector
6141 ExprResult Sema::SemaConvertVectorExpr(Expr *E, TypeSourceInfo *TInfo,
6142                                        SourceLocation BuiltinLoc,
6143                                        SourceLocation RParenLoc) {
6144   ExprValueKind VK = VK_RValue;
6145   ExprObjectKind OK = OK_Ordinary;
6146   QualType DstTy = TInfo->getType();
6147   QualType SrcTy = E->getType();
6148 
6149   if (!SrcTy->isVectorType() && !SrcTy->isDependentType())
6150     return ExprError(Diag(BuiltinLoc,
6151                           diag::err_convertvector_non_vector)
6152                      << E->getSourceRange());
6153   if (!DstTy->isVectorType() && !DstTy->isDependentType())
6154     return ExprError(Diag(BuiltinLoc,
6155                           diag::err_convertvector_non_vector_type));
6156 
6157   if (!SrcTy->isDependentType() && !DstTy->isDependentType()) {
6158     unsigned SrcElts = SrcTy->castAs<VectorType>()->getNumElements();
6159     unsigned DstElts = DstTy->castAs<VectorType>()->getNumElements();
6160     if (SrcElts != DstElts)
6161       return ExprError(Diag(BuiltinLoc,
6162                             diag::err_convertvector_incompatible_vector)
6163                        << E->getSourceRange());
6164   }
6165 
6166   return new (Context)
6167       ConvertVectorExpr(E, TInfo, DstTy, VK, OK, BuiltinLoc, RParenLoc);
6168 }
6169 
6170 /// SemaBuiltinPrefetch - Handle __builtin_prefetch.
6171 // This is declared to take (const void*, ...) and can take two
6172 // optional constant int args.
6173 bool Sema::SemaBuiltinPrefetch(CallExpr *TheCall) {
6174   unsigned NumArgs = TheCall->getNumArgs();
6175 
6176   if (NumArgs > 3)
6177     return Diag(TheCall->getEndLoc(),
6178                 diag::err_typecheck_call_too_many_args_at_most)
6179            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6180 
6181   // Argument 0 is checked for us and the remaining arguments must be
6182   // constant integers.
6183   for (unsigned i = 1; i != NumArgs; ++i)
6184     if (SemaBuiltinConstantArgRange(TheCall, i, 0, i == 1 ? 1 : 3))
6185       return true;
6186 
6187   return false;
6188 }
6189 
6190 /// SemaBuiltinAssume - Handle __assume (MS Extension).
6191 // __assume does not evaluate its arguments, and should warn if its argument
6192 // has side effects.
6193 bool Sema::SemaBuiltinAssume(CallExpr *TheCall) {
6194   Expr *Arg = TheCall->getArg(0);
6195   if (Arg->isInstantiationDependent()) return false;
6196 
6197   if (Arg->HasSideEffects(Context))
6198     Diag(Arg->getBeginLoc(), diag::warn_assume_side_effects)
6199         << Arg->getSourceRange()
6200         << cast<FunctionDecl>(TheCall->getCalleeDecl())->getIdentifier();
6201 
6202   return false;
6203 }
6204 
6205 /// Handle __builtin_alloca_with_align. This is declared
6206 /// as (size_t, size_t) where the second size_t must be a power of 2 greater
6207 /// than 8.
6208 bool Sema::SemaBuiltinAllocaWithAlign(CallExpr *TheCall) {
6209   // The alignment must be a constant integer.
6210   Expr *Arg = TheCall->getArg(1);
6211 
6212   // We can't check the value of a dependent argument.
6213   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6214     if (const auto *UE =
6215             dyn_cast<UnaryExprOrTypeTraitExpr>(Arg->IgnoreParenImpCasts()))
6216       if (UE->getKind() == UETT_AlignOf ||
6217           UE->getKind() == UETT_PreferredAlignOf)
6218         Diag(TheCall->getBeginLoc(), diag::warn_alloca_align_alignof)
6219             << Arg->getSourceRange();
6220 
6221     llvm::APSInt Result = Arg->EvaluateKnownConstInt(Context);
6222 
6223     if (!Result.isPowerOf2())
6224       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6225              << Arg->getSourceRange();
6226 
6227     if (Result < Context.getCharWidth())
6228       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_small)
6229              << (unsigned)Context.getCharWidth() << Arg->getSourceRange();
6230 
6231     if (Result > std::numeric_limits<int32_t>::max())
6232       return Diag(TheCall->getBeginLoc(), diag::err_alignment_too_big)
6233              << std::numeric_limits<int32_t>::max() << Arg->getSourceRange();
6234   }
6235 
6236   return false;
6237 }
6238 
6239 /// Handle __builtin_assume_aligned. This is declared
6240 /// as (const void*, size_t, ...) and can take one optional constant int arg.
6241 bool Sema::SemaBuiltinAssumeAligned(CallExpr *TheCall) {
6242   unsigned NumArgs = TheCall->getNumArgs();
6243 
6244   if (NumArgs > 3)
6245     return Diag(TheCall->getEndLoc(),
6246                 diag::err_typecheck_call_too_many_args_at_most)
6247            << 0 /*function call*/ << 3 << NumArgs << TheCall->getSourceRange();
6248 
6249   // The alignment must be a constant integer.
6250   Expr *Arg = TheCall->getArg(1);
6251 
6252   // We can't check the value of a dependent argument.
6253   if (!Arg->isTypeDependent() && !Arg->isValueDependent()) {
6254     llvm::APSInt Result;
6255     if (SemaBuiltinConstantArg(TheCall, 1, Result))
6256       return true;
6257 
6258     if (!Result.isPowerOf2())
6259       return Diag(TheCall->getBeginLoc(), diag::err_alignment_not_power_of_two)
6260              << Arg->getSourceRange();
6261 
6262     if (Result > Sema::MaximumAlignment)
6263       Diag(TheCall->getBeginLoc(), diag::warn_assume_aligned_too_great)
6264           << Arg->getSourceRange() << Sema::MaximumAlignment;
6265   }
6266 
6267   if (NumArgs > 2) {
6268     ExprResult Arg(TheCall->getArg(2));
6269     InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
6270       Context.getSizeType(), false);
6271     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6272     if (Arg.isInvalid()) return true;
6273     TheCall->setArg(2, Arg.get());
6274   }
6275 
6276   return false;
6277 }
6278 
6279 bool Sema::SemaBuiltinOSLogFormat(CallExpr *TheCall) {
6280   unsigned BuiltinID =
6281       cast<FunctionDecl>(TheCall->getCalleeDecl())->getBuiltinID();
6282   bool IsSizeCall = BuiltinID == Builtin::BI__builtin_os_log_format_buffer_size;
6283 
6284   unsigned NumArgs = TheCall->getNumArgs();
6285   unsigned NumRequiredArgs = IsSizeCall ? 1 : 2;
6286   if (NumArgs < NumRequiredArgs) {
6287     return Diag(TheCall->getEndLoc(), diag::err_typecheck_call_too_few_args)
6288            << 0 /* function call */ << NumRequiredArgs << NumArgs
6289            << TheCall->getSourceRange();
6290   }
6291   if (NumArgs >= NumRequiredArgs + 0x100) {
6292     return Diag(TheCall->getEndLoc(),
6293                 diag::err_typecheck_call_too_many_args_at_most)
6294            << 0 /* function call */ << (NumRequiredArgs + 0xff) << NumArgs
6295            << TheCall->getSourceRange();
6296   }
6297   unsigned i = 0;
6298 
6299   // For formatting call, check buffer arg.
6300   if (!IsSizeCall) {
6301     ExprResult Arg(TheCall->getArg(i));
6302     InitializedEntity Entity = InitializedEntity::InitializeParameter(
6303         Context, Context.VoidPtrTy, false);
6304     Arg = PerformCopyInitialization(Entity, SourceLocation(), Arg);
6305     if (Arg.isInvalid())
6306       return true;
6307     TheCall->setArg(i, Arg.get());
6308     i++;
6309   }
6310 
6311   // Check string literal arg.
6312   unsigned FormatIdx = i;
6313   {
6314     ExprResult Arg = CheckOSLogFormatStringArg(TheCall->getArg(i));
6315     if (Arg.isInvalid())
6316       return true;
6317     TheCall->setArg(i, Arg.get());
6318     i++;
6319   }
6320 
6321   // Make sure variadic args are scalar.
6322   unsigned FirstDataArg = i;
6323   while (i < NumArgs) {
6324     ExprResult Arg = DefaultVariadicArgumentPromotion(
6325         TheCall->getArg(i), VariadicFunction, nullptr);
6326     if (Arg.isInvalid())
6327       return true;
6328     CharUnits ArgSize = Context.getTypeSizeInChars(Arg.get()->getType());
6329     if (ArgSize.getQuantity() >= 0x100) {
6330       return Diag(Arg.get()->getEndLoc(), diag::err_os_log_argument_too_big)
6331              << i << (int)ArgSize.getQuantity() << 0xff
6332              << TheCall->getSourceRange();
6333     }
6334     TheCall->setArg(i, Arg.get());
6335     i++;
6336   }
6337 
6338   // Check formatting specifiers. NOTE: We're only doing this for the non-size
6339   // call to avoid duplicate diagnostics.
6340   if (!IsSizeCall) {
6341     llvm::SmallBitVector CheckedVarArgs(NumArgs, false);
6342     ArrayRef<const Expr *> Args(TheCall->getArgs(), TheCall->getNumArgs());
6343     bool Success = CheckFormatArguments(
6344         Args, /*HasVAListArg*/ false, FormatIdx, FirstDataArg, FST_OSLog,
6345         VariadicFunction, TheCall->getBeginLoc(), SourceRange(),
6346         CheckedVarArgs);
6347     if (!Success)
6348       return true;
6349   }
6350 
6351   if (IsSizeCall) {
6352     TheCall->setType(Context.getSizeType());
6353   } else {
6354     TheCall->setType(Context.VoidPtrTy);
6355   }
6356   return false;
6357 }
6358 
6359 /// SemaBuiltinConstantArg - Handle a check if argument ArgNum of CallExpr
6360 /// TheCall is a constant expression.
6361 bool Sema::SemaBuiltinConstantArg(CallExpr *TheCall, int ArgNum,
6362                                   llvm::APSInt &Result) {
6363   Expr *Arg = TheCall->getArg(ArgNum);
6364   DeclRefExpr *DRE =cast<DeclRefExpr>(TheCall->getCallee()->IgnoreParenCasts());
6365   FunctionDecl *FDecl = cast<FunctionDecl>(DRE->getDecl());
6366 
6367   if (Arg->isTypeDependent() || Arg->isValueDependent()) return false;
6368 
6369   Optional<llvm::APSInt> R;
6370   if (!(R = Arg->getIntegerConstantExpr(Context)))
6371     return Diag(TheCall->getBeginLoc(), diag::err_constant_integer_arg_type)
6372            << FDecl->getDeclName() << Arg->getSourceRange();
6373   Result = *R;
6374   return false;
6375 }
6376 
6377 /// SemaBuiltinConstantArgRange - Handle a check if argument ArgNum of CallExpr
6378 /// TheCall is a constant expression in the range [Low, High].
6379 bool Sema::SemaBuiltinConstantArgRange(CallExpr *TheCall, int ArgNum,
6380                                        int Low, int High, bool RangeIsError) {
6381   if (isConstantEvaluated())
6382     return false;
6383   llvm::APSInt Result;
6384 
6385   // We can't check the value of a dependent argument.
6386   Expr *Arg = TheCall->getArg(ArgNum);
6387   if (Arg->isTypeDependent() || Arg->isValueDependent())
6388     return false;
6389 
6390   // Check constant-ness first.
6391   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6392     return true;
6393 
6394   if (Result.getSExtValue() < Low || Result.getSExtValue() > High) {
6395     if (RangeIsError)
6396       return Diag(TheCall->getBeginLoc(), diag::err_argument_invalid_range)
6397              << Result.toString(10) << Low << High << Arg->getSourceRange();
6398     else
6399       // Defer the warning until we know if the code will be emitted so that
6400       // dead code can ignore this.
6401       DiagRuntimeBehavior(TheCall->getBeginLoc(), TheCall,
6402                           PDiag(diag::warn_argument_invalid_range)
6403                               << Result.toString(10) << Low << High
6404                               << Arg->getSourceRange());
6405   }
6406 
6407   return false;
6408 }
6409 
6410 /// SemaBuiltinConstantArgMultiple - Handle a check if argument ArgNum of CallExpr
6411 /// TheCall is a constant expression is a multiple of Num..
6412 bool Sema::SemaBuiltinConstantArgMultiple(CallExpr *TheCall, int ArgNum,
6413                                           unsigned Num) {
6414   llvm::APSInt Result;
6415 
6416   // We can't check the value of a dependent argument.
6417   Expr *Arg = TheCall->getArg(ArgNum);
6418   if (Arg->isTypeDependent() || Arg->isValueDependent())
6419     return false;
6420 
6421   // Check constant-ness first.
6422   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6423     return true;
6424 
6425   if (Result.getSExtValue() % Num != 0)
6426     return Diag(TheCall->getBeginLoc(), diag::err_argument_not_multiple)
6427            << Num << Arg->getSourceRange();
6428 
6429   return false;
6430 }
6431 
6432 /// SemaBuiltinConstantArgPower2 - Check if argument ArgNum of TheCall is a
6433 /// constant expression representing a power of 2.
6434 bool Sema::SemaBuiltinConstantArgPower2(CallExpr *TheCall, int ArgNum) {
6435   llvm::APSInt Result;
6436 
6437   // We can't check the value of a dependent argument.
6438   Expr *Arg = TheCall->getArg(ArgNum);
6439   if (Arg->isTypeDependent() || Arg->isValueDependent())
6440     return false;
6441 
6442   // Check constant-ness first.
6443   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6444     return true;
6445 
6446   // Bit-twiddling to test for a power of 2: for x > 0, x & (x-1) is zero if
6447   // and only if x is a power of 2.
6448   if (Result.isStrictlyPositive() && (Result & (Result - 1)) == 0)
6449     return false;
6450 
6451   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_power_of_2)
6452          << Arg->getSourceRange();
6453 }
6454 
6455 static bool IsShiftedByte(llvm::APSInt Value) {
6456   if (Value.isNegative())
6457     return false;
6458 
6459   // Check if it's a shifted byte, by shifting it down
6460   while (true) {
6461     // If the value fits in the bottom byte, the check passes.
6462     if (Value < 0x100)
6463       return true;
6464 
6465     // Otherwise, if the value has _any_ bits in the bottom byte, the check
6466     // fails.
6467     if ((Value & 0xFF) != 0)
6468       return false;
6469 
6470     // If the bottom 8 bits are all 0, but something above that is nonzero,
6471     // then shifting the value right by 8 bits won't affect whether it's a
6472     // shifted byte or not. So do that, and go round again.
6473     Value >>= 8;
6474   }
6475 }
6476 
6477 /// SemaBuiltinConstantArgShiftedByte - Check if argument ArgNum of TheCall is
6478 /// a constant expression representing an arbitrary byte value shifted left by
6479 /// a multiple of 8 bits.
6480 bool Sema::SemaBuiltinConstantArgShiftedByte(CallExpr *TheCall, int ArgNum,
6481                                              unsigned ArgBits) {
6482   llvm::APSInt Result;
6483 
6484   // We can't check the value of a dependent argument.
6485   Expr *Arg = TheCall->getArg(ArgNum);
6486   if (Arg->isTypeDependent() || Arg->isValueDependent())
6487     return false;
6488 
6489   // Check constant-ness first.
6490   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6491     return true;
6492 
6493   // Truncate to the given size.
6494   Result = Result.getLoBits(ArgBits);
6495   Result.setIsUnsigned(true);
6496 
6497   if (IsShiftedByte(Result))
6498     return false;
6499 
6500   return Diag(TheCall->getBeginLoc(), diag::err_argument_not_shifted_byte)
6501          << Arg->getSourceRange();
6502 }
6503 
6504 /// SemaBuiltinConstantArgShiftedByteOr0xFF - Check if argument ArgNum of
6505 /// TheCall is a constant expression representing either a shifted byte value,
6506 /// or a value of the form 0x??FF (i.e. a member of the arithmetic progression
6507 /// 0x00FF, 0x01FF, ..., 0xFFFF). This strange range check is needed for some
6508 /// Arm MVE intrinsics.
6509 bool Sema::SemaBuiltinConstantArgShiftedByteOrXXFF(CallExpr *TheCall,
6510                                                    int ArgNum,
6511                                                    unsigned ArgBits) {
6512   llvm::APSInt Result;
6513 
6514   // We can't check the value of a dependent argument.
6515   Expr *Arg = TheCall->getArg(ArgNum);
6516   if (Arg->isTypeDependent() || Arg->isValueDependent())
6517     return false;
6518 
6519   // Check constant-ness first.
6520   if (SemaBuiltinConstantArg(TheCall, ArgNum, Result))
6521     return true;
6522 
6523   // Truncate to the given size.
6524   Result = Result.getLoBits(ArgBits);
6525   Result.setIsUnsigned(true);
6526 
6527   // Check to see if it's in either of the required forms.
6528   if (IsShiftedByte(Result) ||
6529       (Result > 0 && Result < 0x10000 && (Result & 0xFF) == 0xFF))
6530     return false;
6531 
6532   return Diag(TheCall->getBeginLoc(),
6533               diag::err_argument_not_shifted_byte_or_xxff)
6534          << Arg->getSourceRange();
6535 }
6536 
6537 /// SemaBuiltinARMMemoryTaggingCall - Handle calls of memory tagging extensions
6538 bool Sema::SemaBuiltinARMMemoryTaggingCall(unsigned BuiltinID, CallExpr *TheCall) {
6539   if (BuiltinID == AArch64::BI__builtin_arm_irg) {
6540     if (checkArgCount(*this, TheCall, 2))
6541       return true;
6542     Expr *Arg0 = TheCall->getArg(0);
6543     Expr *Arg1 = TheCall->getArg(1);
6544 
6545     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6546     if (FirstArg.isInvalid())
6547       return true;
6548     QualType FirstArgType = FirstArg.get()->getType();
6549     if (!FirstArgType->isAnyPointerType())
6550       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6551                << "first" << FirstArgType << Arg0->getSourceRange();
6552     TheCall->setArg(0, FirstArg.get());
6553 
6554     ExprResult SecArg = DefaultLvalueConversion(Arg1);
6555     if (SecArg.isInvalid())
6556       return true;
6557     QualType SecArgType = SecArg.get()->getType();
6558     if (!SecArgType->isIntegerType())
6559       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6560                << "second" << SecArgType << Arg1->getSourceRange();
6561 
6562     // Derive the return type from the pointer argument.
6563     TheCall->setType(FirstArgType);
6564     return false;
6565   }
6566 
6567   if (BuiltinID == AArch64::BI__builtin_arm_addg) {
6568     if (checkArgCount(*this, TheCall, 2))
6569       return true;
6570 
6571     Expr *Arg0 = TheCall->getArg(0);
6572     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6573     if (FirstArg.isInvalid())
6574       return true;
6575     QualType FirstArgType = FirstArg.get()->getType();
6576     if (!FirstArgType->isAnyPointerType())
6577       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6578                << "first" << FirstArgType << Arg0->getSourceRange();
6579     TheCall->setArg(0, FirstArg.get());
6580 
6581     // Derive the return type from the pointer argument.
6582     TheCall->setType(FirstArgType);
6583 
6584     // Second arg must be an constant in range [0,15]
6585     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6586   }
6587 
6588   if (BuiltinID == AArch64::BI__builtin_arm_gmi) {
6589     if (checkArgCount(*this, TheCall, 2))
6590       return true;
6591     Expr *Arg0 = TheCall->getArg(0);
6592     Expr *Arg1 = TheCall->getArg(1);
6593 
6594     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6595     if (FirstArg.isInvalid())
6596       return true;
6597     QualType FirstArgType = FirstArg.get()->getType();
6598     if (!FirstArgType->isAnyPointerType())
6599       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6600                << "first" << FirstArgType << Arg0->getSourceRange();
6601 
6602     QualType SecArgType = Arg1->getType();
6603     if (!SecArgType->isIntegerType())
6604       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_integer)
6605                << "second" << SecArgType << Arg1->getSourceRange();
6606     TheCall->setType(Context.IntTy);
6607     return false;
6608   }
6609 
6610   if (BuiltinID == AArch64::BI__builtin_arm_ldg ||
6611       BuiltinID == AArch64::BI__builtin_arm_stg) {
6612     if (checkArgCount(*this, TheCall, 1))
6613       return true;
6614     Expr *Arg0 = TheCall->getArg(0);
6615     ExprResult FirstArg = DefaultFunctionArrayLvalueConversion(Arg0);
6616     if (FirstArg.isInvalid())
6617       return true;
6618 
6619     QualType FirstArgType = FirstArg.get()->getType();
6620     if (!FirstArgType->isAnyPointerType())
6621       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_must_be_pointer)
6622                << "first" << FirstArgType << Arg0->getSourceRange();
6623     TheCall->setArg(0, FirstArg.get());
6624 
6625     // Derive the return type from the pointer argument.
6626     if (BuiltinID == AArch64::BI__builtin_arm_ldg)
6627       TheCall->setType(FirstArgType);
6628     return false;
6629   }
6630 
6631   if (BuiltinID == AArch64::BI__builtin_arm_subp) {
6632     Expr *ArgA = TheCall->getArg(0);
6633     Expr *ArgB = TheCall->getArg(1);
6634 
6635     ExprResult ArgExprA = DefaultFunctionArrayLvalueConversion(ArgA);
6636     ExprResult ArgExprB = DefaultFunctionArrayLvalueConversion(ArgB);
6637 
6638     if (ArgExprA.isInvalid() || ArgExprB.isInvalid())
6639       return true;
6640 
6641     QualType ArgTypeA = ArgExprA.get()->getType();
6642     QualType ArgTypeB = ArgExprB.get()->getType();
6643 
6644     auto isNull = [&] (Expr *E) -> bool {
6645       return E->isNullPointerConstant(
6646                         Context, Expr::NPC_ValueDependentIsNotNull); };
6647 
6648     // argument should be either a pointer or null
6649     if (!ArgTypeA->isAnyPointerType() && !isNull(ArgA))
6650       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6651         << "first" << ArgTypeA << ArgA->getSourceRange();
6652 
6653     if (!ArgTypeB->isAnyPointerType() && !isNull(ArgB))
6654       return Diag(TheCall->getBeginLoc(), diag::err_memtag_arg_null_or_pointer)
6655         << "second" << ArgTypeB << ArgB->getSourceRange();
6656 
6657     // Ensure Pointee types are compatible
6658     if (ArgTypeA->isAnyPointerType() && !isNull(ArgA) &&
6659         ArgTypeB->isAnyPointerType() && !isNull(ArgB)) {
6660       QualType pointeeA = ArgTypeA->getPointeeType();
6661       QualType pointeeB = ArgTypeB->getPointeeType();
6662       if (!Context.typesAreCompatible(
6663              Context.getCanonicalType(pointeeA).getUnqualifiedType(),
6664              Context.getCanonicalType(pointeeB).getUnqualifiedType())) {
6665         return Diag(TheCall->getBeginLoc(), diag::err_typecheck_sub_ptr_compatible)
6666           << ArgTypeA <<  ArgTypeB << ArgA->getSourceRange()
6667           << ArgB->getSourceRange();
6668       }
6669     }
6670 
6671     // at least one argument should be pointer type
6672     if (!ArgTypeA->isAnyPointerType() && !ArgTypeB->isAnyPointerType())
6673       return Diag(TheCall->getBeginLoc(), diag::err_memtag_any2arg_pointer)
6674         <<  ArgTypeA << ArgTypeB << ArgA->getSourceRange();
6675 
6676     if (isNull(ArgA)) // adopt type of the other pointer
6677       ArgExprA = ImpCastExprToType(ArgExprA.get(), ArgTypeB, CK_NullToPointer);
6678 
6679     if (isNull(ArgB))
6680       ArgExprB = ImpCastExprToType(ArgExprB.get(), ArgTypeA, CK_NullToPointer);
6681 
6682     TheCall->setArg(0, ArgExprA.get());
6683     TheCall->setArg(1, ArgExprB.get());
6684     TheCall->setType(Context.LongLongTy);
6685     return false;
6686   }
6687   assert(false && "Unhandled ARM MTE intrinsic");
6688   return true;
6689 }
6690 
6691 /// SemaBuiltinARMSpecialReg - Handle a check if argument ArgNum of CallExpr
6692 /// TheCall is an ARM/AArch64 special register string literal.
6693 bool Sema::SemaBuiltinARMSpecialReg(unsigned BuiltinID, CallExpr *TheCall,
6694                                     int ArgNum, unsigned ExpectedFieldNum,
6695                                     bool AllowName) {
6696   bool IsARMBuiltin = BuiltinID == ARM::BI__builtin_arm_rsr64 ||
6697                       BuiltinID == ARM::BI__builtin_arm_wsr64 ||
6698                       BuiltinID == ARM::BI__builtin_arm_rsr ||
6699                       BuiltinID == ARM::BI__builtin_arm_rsrp ||
6700                       BuiltinID == ARM::BI__builtin_arm_wsr ||
6701                       BuiltinID == ARM::BI__builtin_arm_wsrp;
6702   bool IsAArch64Builtin = BuiltinID == AArch64::BI__builtin_arm_rsr64 ||
6703                           BuiltinID == AArch64::BI__builtin_arm_wsr64 ||
6704                           BuiltinID == AArch64::BI__builtin_arm_rsr ||
6705                           BuiltinID == AArch64::BI__builtin_arm_rsrp ||
6706                           BuiltinID == AArch64::BI__builtin_arm_wsr ||
6707                           BuiltinID == AArch64::BI__builtin_arm_wsrp;
6708   assert((IsARMBuiltin || IsAArch64Builtin) && "Unexpected ARM builtin.");
6709 
6710   // We can't check the value of a dependent argument.
6711   Expr *Arg = TheCall->getArg(ArgNum);
6712   if (Arg->isTypeDependent() || Arg->isValueDependent())
6713     return false;
6714 
6715   // Check if the argument is a string literal.
6716   if (!isa<StringLiteral>(Arg->IgnoreParenImpCasts()))
6717     return Diag(TheCall->getBeginLoc(), diag::err_expr_not_string_literal)
6718            << Arg->getSourceRange();
6719 
6720   // Check the type of special register given.
6721   StringRef Reg = cast<StringLiteral>(Arg->IgnoreParenImpCasts())->getString();
6722   SmallVector<StringRef, 6> Fields;
6723   Reg.split(Fields, ":");
6724 
6725   if (Fields.size() != ExpectedFieldNum && !(AllowName && Fields.size() == 1))
6726     return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6727            << Arg->getSourceRange();
6728 
6729   // If the string is the name of a register then we cannot check that it is
6730   // valid here but if the string is of one the forms described in ACLE then we
6731   // can check that the supplied fields are integers and within the valid
6732   // ranges.
6733   if (Fields.size() > 1) {
6734     bool FiveFields = Fields.size() == 5;
6735 
6736     bool ValidString = true;
6737     if (IsARMBuiltin) {
6738       ValidString &= Fields[0].startswith_lower("cp") ||
6739                      Fields[0].startswith_lower("p");
6740       if (ValidString)
6741         Fields[0] =
6742           Fields[0].drop_front(Fields[0].startswith_lower("cp") ? 2 : 1);
6743 
6744       ValidString &= Fields[2].startswith_lower("c");
6745       if (ValidString)
6746         Fields[2] = Fields[2].drop_front(1);
6747 
6748       if (FiveFields) {
6749         ValidString &= Fields[3].startswith_lower("c");
6750         if (ValidString)
6751           Fields[3] = Fields[3].drop_front(1);
6752       }
6753     }
6754 
6755     SmallVector<int, 5> Ranges;
6756     if (FiveFields)
6757       Ranges.append({IsAArch64Builtin ? 1 : 15, 7, 15, 15, 7});
6758     else
6759       Ranges.append({15, 7, 15});
6760 
6761     for (unsigned i=0; i<Fields.size(); ++i) {
6762       int IntField;
6763       ValidString &= !Fields[i].getAsInteger(10, IntField);
6764       ValidString &= (IntField >= 0 && IntField <= Ranges[i]);
6765     }
6766 
6767     if (!ValidString)
6768       return Diag(TheCall->getBeginLoc(), diag::err_arm_invalid_specialreg)
6769              << Arg->getSourceRange();
6770   } else if (IsAArch64Builtin && Fields.size() == 1) {
6771     // If the register name is one of those that appear in the condition below
6772     // and the special register builtin being used is one of the write builtins,
6773     // then we require that the argument provided for writing to the register
6774     // is an integer constant expression. This is because it will be lowered to
6775     // an MSR (immediate) instruction, so we need to know the immediate at
6776     // compile time.
6777     if (TheCall->getNumArgs() != 2)
6778       return false;
6779 
6780     std::string RegLower = Reg.lower();
6781     if (RegLower != "spsel" && RegLower != "daifset" && RegLower != "daifclr" &&
6782         RegLower != "pan" && RegLower != "uao")
6783       return false;
6784 
6785     return SemaBuiltinConstantArgRange(TheCall, 1, 0, 15);
6786   }
6787 
6788   return false;
6789 }
6790 
6791 /// SemaBuiltinPPCMMACall - Check the call to a PPC MMA builtin for validity.
6792 /// Emit an error and return true on failure; return false on success.
6793 /// TypeStr is a string containing the type descriptor of the value returned by
6794 /// the builtin and the descriptors of the expected type of the arguments.
6795 bool Sema::SemaBuiltinPPCMMACall(CallExpr *TheCall, const char *TypeStr) {
6796 
6797   assert((TypeStr[0] != '\0') &&
6798          "Invalid types in PPC MMA builtin declaration");
6799 
6800   unsigned Mask = 0;
6801   unsigned ArgNum = 0;
6802 
6803   // The first type in TypeStr is the type of the value returned by the
6804   // builtin. So we first read that type and change the type of TheCall.
6805   QualType type = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6806   TheCall->setType(type);
6807 
6808   while (*TypeStr != '\0') {
6809     Mask = 0;
6810     QualType ExpectedType = DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6811     if (ArgNum >= TheCall->getNumArgs()) {
6812       ArgNum++;
6813       break;
6814     }
6815 
6816     Expr *Arg = TheCall->getArg(ArgNum);
6817     QualType ArgType = Arg->getType();
6818 
6819     if ((ExpectedType->isVoidPointerType() && !ArgType->isPointerType()) ||
6820         (!ExpectedType->isVoidPointerType() &&
6821            ArgType.getCanonicalType() != ExpectedType))
6822       return Diag(Arg->getBeginLoc(), diag::err_typecheck_convert_incompatible)
6823              << ArgType << ExpectedType << 1 << 0 << 0;
6824 
6825     // If the value of the Mask is not 0, we have a constraint in the size of
6826     // the integer argument so here we ensure the argument is a constant that
6827     // is in the valid range.
6828     if (Mask != 0 &&
6829         SemaBuiltinConstantArgRange(TheCall, ArgNum, 0, Mask, true))
6830       return true;
6831 
6832     ArgNum++;
6833   }
6834 
6835   // In case we exited early from the previous loop, there are other types to
6836   // read from TypeStr. So we need to read them all to ensure we have the right
6837   // number of arguments in TheCall and if it is not the case, to display a
6838   // better error message.
6839   while (*TypeStr != '\0') {
6840     (void) DecodePPCMMATypeFromStr(Context, TypeStr, Mask);
6841     ArgNum++;
6842   }
6843   if (checkArgCount(*this, TheCall, ArgNum))
6844     return true;
6845 
6846   return false;
6847 }
6848 
6849 /// SemaBuiltinLongjmp - Handle __builtin_longjmp(void *env[5], int val).
6850 /// This checks that the target supports __builtin_longjmp and
6851 /// that val is a constant 1.
6852 bool Sema::SemaBuiltinLongjmp(CallExpr *TheCall) {
6853   if (!Context.getTargetInfo().hasSjLjLowering())
6854     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_unsupported)
6855            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6856 
6857   Expr *Arg = TheCall->getArg(1);
6858   llvm::APSInt Result;
6859 
6860   // TODO: This is less than ideal. Overload this to take a value.
6861   if (SemaBuiltinConstantArg(TheCall, 1, Result))
6862     return true;
6863 
6864   if (Result != 1)
6865     return Diag(TheCall->getBeginLoc(), diag::err_builtin_longjmp_invalid_val)
6866            << SourceRange(Arg->getBeginLoc(), Arg->getEndLoc());
6867 
6868   return false;
6869 }
6870 
6871 /// SemaBuiltinSetjmp - Handle __builtin_setjmp(void *env[5]).
6872 /// This checks that the target supports __builtin_setjmp.
6873 bool Sema::SemaBuiltinSetjmp(CallExpr *TheCall) {
6874   if (!Context.getTargetInfo().hasSjLjLowering())
6875     return Diag(TheCall->getBeginLoc(), diag::err_builtin_setjmp_unsupported)
6876            << SourceRange(TheCall->getBeginLoc(), TheCall->getEndLoc());
6877   return false;
6878 }
6879 
6880 namespace {
6881 
6882 class UncoveredArgHandler {
6883   enum { Unknown = -1, AllCovered = -2 };
6884 
6885   signed FirstUncoveredArg = Unknown;
6886   SmallVector<const Expr *, 4> DiagnosticExprs;
6887 
6888 public:
6889   UncoveredArgHandler() = default;
6890 
6891   bool hasUncoveredArg() const {
6892     return (FirstUncoveredArg >= 0);
6893   }
6894 
6895   unsigned getUncoveredArg() const {
6896     assert(hasUncoveredArg() && "no uncovered argument");
6897     return FirstUncoveredArg;
6898   }
6899 
6900   void setAllCovered() {
6901     // A string has been found with all arguments covered, so clear out
6902     // the diagnostics.
6903     DiagnosticExprs.clear();
6904     FirstUncoveredArg = AllCovered;
6905   }
6906 
6907   void Update(signed NewFirstUncoveredArg, const Expr *StrExpr) {
6908     assert(NewFirstUncoveredArg >= 0 && "Outside range");
6909 
6910     // Don't update if a previous string covers all arguments.
6911     if (FirstUncoveredArg == AllCovered)
6912       return;
6913 
6914     // UncoveredArgHandler tracks the highest uncovered argument index
6915     // and with it all the strings that match this index.
6916     if (NewFirstUncoveredArg == FirstUncoveredArg)
6917       DiagnosticExprs.push_back(StrExpr);
6918     else if (NewFirstUncoveredArg > FirstUncoveredArg) {
6919       DiagnosticExprs.clear();
6920       DiagnosticExprs.push_back(StrExpr);
6921       FirstUncoveredArg = NewFirstUncoveredArg;
6922     }
6923   }
6924 
6925   void Diagnose(Sema &S, bool IsFunctionCall, const Expr *ArgExpr);
6926 };
6927 
6928 enum StringLiteralCheckType {
6929   SLCT_NotALiteral,
6930   SLCT_UncheckedLiteral,
6931   SLCT_CheckedLiteral
6932 };
6933 
6934 } // namespace
6935 
6936 static void sumOffsets(llvm::APSInt &Offset, llvm::APSInt Addend,
6937                                      BinaryOperatorKind BinOpKind,
6938                                      bool AddendIsRight) {
6939   unsigned BitWidth = Offset.getBitWidth();
6940   unsigned AddendBitWidth = Addend.getBitWidth();
6941   // There might be negative interim results.
6942   if (Addend.isUnsigned()) {
6943     Addend = Addend.zext(++AddendBitWidth);
6944     Addend.setIsSigned(true);
6945   }
6946   // Adjust the bit width of the APSInts.
6947   if (AddendBitWidth > BitWidth) {
6948     Offset = Offset.sext(AddendBitWidth);
6949     BitWidth = AddendBitWidth;
6950   } else if (BitWidth > AddendBitWidth) {
6951     Addend = Addend.sext(BitWidth);
6952   }
6953 
6954   bool Ov = false;
6955   llvm::APSInt ResOffset = Offset;
6956   if (BinOpKind == BO_Add)
6957     ResOffset = Offset.sadd_ov(Addend, Ov);
6958   else {
6959     assert(AddendIsRight && BinOpKind == BO_Sub &&
6960            "operator must be add or sub with addend on the right");
6961     ResOffset = Offset.ssub_ov(Addend, Ov);
6962   }
6963 
6964   // We add an offset to a pointer here so we should support an offset as big as
6965   // possible.
6966   if (Ov) {
6967     assert(BitWidth <= std::numeric_limits<unsigned>::max() / 2 &&
6968            "index (intermediate) result too big");
6969     Offset = Offset.sext(2 * BitWidth);
6970     sumOffsets(Offset, Addend, BinOpKind, AddendIsRight);
6971     return;
6972   }
6973 
6974   Offset = ResOffset;
6975 }
6976 
6977 namespace {
6978 
6979 // This is a wrapper class around StringLiteral to support offsetted string
6980 // literals as format strings. It takes the offset into account when returning
6981 // the string and its length or the source locations to display notes correctly.
6982 class FormatStringLiteral {
6983   const StringLiteral *FExpr;
6984   int64_t Offset;
6985 
6986  public:
6987   FormatStringLiteral(const StringLiteral *fexpr, int64_t Offset = 0)
6988       : FExpr(fexpr), Offset(Offset) {}
6989 
6990   StringRef getString() const {
6991     return FExpr->getString().drop_front(Offset);
6992   }
6993 
6994   unsigned getByteLength() const {
6995     return FExpr->getByteLength() - getCharByteWidth() * Offset;
6996   }
6997 
6998   unsigned getLength() const { return FExpr->getLength() - Offset; }
6999   unsigned getCharByteWidth() const { return FExpr->getCharByteWidth(); }
7000 
7001   StringLiteral::StringKind getKind() const { return FExpr->getKind(); }
7002 
7003   QualType getType() const { return FExpr->getType(); }
7004 
7005   bool isAscii() const { return FExpr->isAscii(); }
7006   bool isWide() const { return FExpr->isWide(); }
7007   bool isUTF8() const { return FExpr->isUTF8(); }
7008   bool isUTF16() const { return FExpr->isUTF16(); }
7009   bool isUTF32() const { return FExpr->isUTF32(); }
7010   bool isPascal() const { return FExpr->isPascal(); }
7011 
7012   SourceLocation getLocationOfByte(
7013       unsigned ByteNo, const SourceManager &SM, const LangOptions &Features,
7014       const TargetInfo &Target, unsigned *StartToken = nullptr,
7015       unsigned *StartTokenByteOffset = nullptr) const {
7016     return FExpr->getLocationOfByte(ByteNo + Offset, SM, Features, Target,
7017                                     StartToken, StartTokenByteOffset);
7018   }
7019 
7020   SourceLocation getBeginLoc() const LLVM_READONLY {
7021     return FExpr->getBeginLoc().getLocWithOffset(Offset);
7022   }
7023 
7024   SourceLocation getEndLoc() const LLVM_READONLY { return FExpr->getEndLoc(); }
7025 };
7026 
7027 }  // namespace
7028 
7029 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
7030                               const Expr *OrigFormatExpr,
7031                               ArrayRef<const Expr *> Args,
7032                               bool HasVAListArg, unsigned format_idx,
7033                               unsigned firstDataArg,
7034                               Sema::FormatStringType Type,
7035                               bool inFunctionCall,
7036                               Sema::VariadicCallType CallType,
7037                               llvm::SmallBitVector &CheckedVarArgs,
7038                               UncoveredArgHandler &UncoveredArg,
7039                               bool IgnoreStringsWithoutSpecifiers);
7040 
7041 // Determine if an expression is a string literal or constant string.
7042 // If this function returns false on the arguments to a function expecting a
7043 // format string, we will usually need to emit a warning.
7044 // True string literals are then checked by CheckFormatString.
7045 static StringLiteralCheckType
7046 checkFormatStringExpr(Sema &S, const Expr *E, ArrayRef<const Expr *> Args,
7047                       bool HasVAListArg, unsigned format_idx,
7048                       unsigned firstDataArg, Sema::FormatStringType Type,
7049                       Sema::VariadicCallType CallType, bool InFunctionCall,
7050                       llvm::SmallBitVector &CheckedVarArgs,
7051                       UncoveredArgHandler &UncoveredArg,
7052                       llvm::APSInt Offset,
7053                       bool IgnoreStringsWithoutSpecifiers = false) {
7054   if (S.isConstantEvaluated())
7055     return SLCT_NotALiteral;
7056  tryAgain:
7057   assert(Offset.isSigned() && "invalid offset");
7058 
7059   if (E->isTypeDependent() || E->isValueDependent())
7060     return SLCT_NotALiteral;
7061 
7062   E = E->IgnoreParenCasts();
7063 
7064   if (E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull))
7065     // Technically -Wformat-nonliteral does not warn about this case.
7066     // The behavior of printf and friends in this case is implementation
7067     // dependent.  Ideally if the format string cannot be null then
7068     // it should have a 'nonnull' attribute in the function prototype.
7069     return SLCT_UncheckedLiteral;
7070 
7071   switch (E->getStmtClass()) {
7072   case Stmt::BinaryConditionalOperatorClass:
7073   case Stmt::ConditionalOperatorClass: {
7074     // The expression is a literal if both sub-expressions were, and it was
7075     // completely checked only if both sub-expressions were checked.
7076     const AbstractConditionalOperator *C =
7077         cast<AbstractConditionalOperator>(E);
7078 
7079     // Determine whether it is necessary to check both sub-expressions, for
7080     // example, because the condition expression is a constant that can be
7081     // evaluated at compile time.
7082     bool CheckLeft = true, CheckRight = true;
7083 
7084     bool Cond;
7085     if (C->getCond()->EvaluateAsBooleanCondition(Cond, S.getASTContext(),
7086                                                  S.isConstantEvaluated())) {
7087       if (Cond)
7088         CheckRight = false;
7089       else
7090         CheckLeft = false;
7091     }
7092 
7093     // We need to maintain the offsets for the right and the left hand side
7094     // separately to check if every possible indexed expression is a valid
7095     // string literal. They might have different offsets for different string
7096     // literals in the end.
7097     StringLiteralCheckType Left;
7098     if (!CheckLeft)
7099       Left = SLCT_UncheckedLiteral;
7100     else {
7101       Left = checkFormatStringExpr(S, C->getTrueExpr(), Args,
7102                                    HasVAListArg, format_idx, firstDataArg,
7103                                    Type, CallType, InFunctionCall,
7104                                    CheckedVarArgs, UncoveredArg, Offset,
7105                                    IgnoreStringsWithoutSpecifiers);
7106       if (Left == SLCT_NotALiteral || !CheckRight) {
7107         return Left;
7108       }
7109     }
7110 
7111     StringLiteralCheckType Right = checkFormatStringExpr(
7112         S, C->getFalseExpr(), Args, HasVAListArg, format_idx, firstDataArg,
7113         Type, CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7114         IgnoreStringsWithoutSpecifiers);
7115 
7116     return (CheckLeft && Left < Right) ? Left : Right;
7117   }
7118 
7119   case Stmt::ImplicitCastExprClass:
7120     E = cast<ImplicitCastExpr>(E)->getSubExpr();
7121     goto tryAgain;
7122 
7123   case Stmt::OpaqueValueExprClass:
7124     if (const Expr *src = cast<OpaqueValueExpr>(E)->getSourceExpr()) {
7125       E = src;
7126       goto tryAgain;
7127     }
7128     return SLCT_NotALiteral;
7129 
7130   case Stmt::PredefinedExprClass:
7131     // While __func__, etc., are technically not string literals, they
7132     // cannot contain format specifiers and thus are not a security
7133     // liability.
7134     return SLCT_UncheckedLiteral;
7135 
7136   case Stmt::DeclRefExprClass: {
7137     const DeclRefExpr *DR = cast<DeclRefExpr>(E);
7138 
7139     // As an exception, do not flag errors for variables binding to
7140     // const string literals.
7141     if (const VarDecl *VD = dyn_cast<VarDecl>(DR->getDecl())) {
7142       bool isConstant = false;
7143       QualType T = DR->getType();
7144 
7145       if (const ArrayType *AT = S.Context.getAsArrayType(T)) {
7146         isConstant = AT->getElementType().isConstant(S.Context);
7147       } else if (const PointerType *PT = T->getAs<PointerType>()) {
7148         isConstant = T.isConstant(S.Context) &&
7149                      PT->getPointeeType().isConstant(S.Context);
7150       } else if (T->isObjCObjectPointerType()) {
7151         // In ObjC, there is usually no "const ObjectPointer" type,
7152         // so don't check if the pointee type is constant.
7153         isConstant = T.isConstant(S.Context);
7154       }
7155 
7156       if (isConstant) {
7157         if (const Expr *Init = VD->getAnyInitializer()) {
7158           // Look through initializers like const char c[] = { "foo" }
7159           if (const InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
7160             if (InitList->isStringLiteralInit())
7161               Init = InitList->getInit(0)->IgnoreParenImpCasts();
7162           }
7163           return checkFormatStringExpr(S, Init, Args,
7164                                        HasVAListArg, format_idx,
7165                                        firstDataArg, Type, CallType,
7166                                        /*InFunctionCall*/ false, CheckedVarArgs,
7167                                        UncoveredArg, Offset);
7168         }
7169       }
7170 
7171       // For vprintf* functions (i.e., HasVAListArg==true), we add a
7172       // special check to see if the format string is a function parameter
7173       // of the function calling the printf function.  If the function
7174       // has an attribute indicating it is a printf-like function, then we
7175       // should suppress warnings concerning non-literals being used in a call
7176       // to a vprintf function.  For example:
7177       //
7178       // void
7179       // logmessage(char const *fmt __attribute__ (format (printf, 1, 2)), ...){
7180       //      va_list ap;
7181       //      va_start(ap, fmt);
7182       //      vprintf(fmt, ap);  // Do NOT emit a warning about "fmt".
7183       //      ...
7184       // }
7185       if (HasVAListArg) {
7186         if (const ParmVarDecl *PV = dyn_cast<ParmVarDecl>(VD)) {
7187           if (const NamedDecl *ND = dyn_cast<NamedDecl>(PV->getDeclContext())) {
7188             int PVIndex = PV->getFunctionScopeIndex() + 1;
7189             for (const auto *PVFormat : ND->specific_attrs<FormatAttr>()) {
7190               // adjust for implicit parameter
7191               if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7192                 if (MD->isInstance())
7193                   ++PVIndex;
7194               // We also check if the formats are compatible.
7195               // We can't pass a 'scanf' string to a 'printf' function.
7196               if (PVIndex == PVFormat->getFormatIdx() &&
7197                   Type == S.GetFormatStringType(PVFormat))
7198                 return SLCT_UncheckedLiteral;
7199             }
7200           }
7201         }
7202       }
7203     }
7204 
7205     return SLCT_NotALiteral;
7206   }
7207 
7208   case Stmt::CallExprClass:
7209   case Stmt::CXXMemberCallExprClass: {
7210     const CallExpr *CE = cast<CallExpr>(E);
7211     if (const NamedDecl *ND = dyn_cast_or_null<NamedDecl>(CE->getCalleeDecl())) {
7212       bool IsFirst = true;
7213       StringLiteralCheckType CommonResult;
7214       for (const auto *FA : ND->specific_attrs<FormatArgAttr>()) {
7215         const Expr *Arg = CE->getArg(FA->getFormatIdx().getASTIndex());
7216         StringLiteralCheckType Result = checkFormatStringExpr(
7217             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7218             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7219             IgnoreStringsWithoutSpecifiers);
7220         if (IsFirst) {
7221           CommonResult = Result;
7222           IsFirst = false;
7223         }
7224       }
7225       if (!IsFirst)
7226         return CommonResult;
7227 
7228       if (const auto *FD = dyn_cast<FunctionDecl>(ND)) {
7229         unsigned BuiltinID = FD->getBuiltinID();
7230         if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
7231             BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString) {
7232           const Expr *Arg = CE->getArg(0);
7233           return checkFormatStringExpr(S, Arg, Args,
7234                                        HasVAListArg, format_idx,
7235                                        firstDataArg, Type, CallType,
7236                                        InFunctionCall, CheckedVarArgs,
7237                                        UncoveredArg, Offset,
7238                                        IgnoreStringsWithoutSpecifiers);
7239         }
7240       }
7241     }
7242 
7243     return SLCT_NotALiteral;
7244   }
7245   case Stmt::ObjCMessageExprClass: {
7246     const auto *ME = cast<ObjCMessageExpr>(E);
7247     if (const auto *MD = ME->getMethodDecl()) {
7248       if (const auto *FA = MD->getAttr<FormatArgAttr>()) {
7249         // As a special case heuristic, if we're using the method -[NSBundle
7250         // localizedStringForKey:value:table:], ignore any key strings that lack
7251         // format specifiers. The idea is that if the key doesn't have any
7252         // format specifiers then its probably just a key to map to the
7253         // localized strings. If it does have format specifiers though, then its
7254         // likely that the text of the key is the format string in the
7255         // programmer's language, and should be checked.
7256         const ObjCInterfaceDecl *IFace;
7257         if (MD->isInstanceMethod() && (IFace = MD->getClassInterface()) &&
7258             IFace->getIdentifier()->isStr("NSBundle") &&
7259             MD->getSelector().isKeywordSelector(
7260                 {"localizedStringForKey", "value", "table"})) {
7261           IgnoreStringsWithoutSpecifiers = true;
7262         }
7263 
7264         const Expr *Arg = ME->getArg(FA->getFormatIdx().getASTIndex());
7265         return checkFormatStringExpr(
7266             S, Arg, Args, HasVAListArg, format_idx, firstDataArg, Type,
7267             CallType, InFunctionCall, CheckedVarArgs, UncoveredArg, Offset,
7268             IgnoreStringsWithoutSpecifiers);
7269       }
7270     }
7271 
7272     return SLCT_NotALiteral;
7273   }
7274   case Stmt::ObjCStringLiteralClass:
7275   case Stmt::StringLiteralClass: {
7276     const StringLiteral *StrE = nullptr;
7277 
7278     if (const ObjCStringLiteral *ObjCFExpr = dyn_cast<ObjCStringLiteral>(E))
7279       StrE = ObjCFExpr->getString();
7280     else
7281       StrE = cast<StringLiteral>(E);
7282 
7283     if (StrE) {
7284       if (Offset.isNegative() || Offset > StrE->getLength()) {
7285         // TODO: It would be better to have an explicit warning for out of
7286         // bounds literals.
7287         return SLCT_NotALiteral;
7288       }
7289       FormatStringLiteral FStr(StrE, Offset.sextOrTrunc(64).getSExtValue());
7290       CheckFormatString(S, &FStr, E, Args, HasVAListArg, format_idx,
7291                         firstDataArg, Type, InFunctionCall, CallType,
7292                         CheckedVarArgs, UncoveredArg,
7293                         IgnoreStringsWithoutSpecifiers);
7294       return SLCT_CheckedLiteral;
7295     }
7296 
7297     return SLCT_NotALiteral;
7298   }
7299   case Stmt::BinaryOperatorClass: {
7300     const BinaryOperator *BinOp = cast<BinaryOperator>(E);
7301 
7302     // A string literal + an int offset is still a string literal.
7303     if (BinOp->isAdditiveOp()) {
7304       Expr::EvalResult LResult, RResult;
7305 
7306       bool LIsInt = BinOp->getLHS()->EvaluateAsInt(
7307           LResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7308       bool RIsInt = BinOp->getRHS()->EvaluateAsInt(
7309           RResult, S.Context, Expr::SE_NoSideEffects, S.isConstantEvaluated());
7310 
7311       if (LIsInt != RIsInt) {
7312         BinaryOperatorKind BinOpKind = BinOp->getOpcode();
7313 
7314         if (LIsInt) {
7315           if (BinOpKind == BO_Add) {
7316             sumOffsets(Offset, LResult.Val.getInt(), BinOpKind, RIsInt);
7317             E = BinOp->getRHS();
7318             goto tryAgain;
7319           }
7320         } else {
7321           sumOffsets(Offset, RResult.Val.getInt(), BinOpKind, RIsInt);
7322           E = BinOp->getLHS();
7323           goto tryAgain;
7324         }
7325       }
7326     }
7327 
7328     return SLCT_NotALiteral;
7329   }
7330   case Stmt::UnaryOperatorClass: {
7331     const UnaryOperator *UnaOp = cast<UnaryOperator>(E);
7332     auto ASE = dyn_cast<ArraySubscriptExpr>(UnaOp->getSubExpr());
7333     if (UnaOp->getOpcode() == UO_AddrOf && ASE) {
7334       Expr::EvalResult IndexResult;
7335       if (ASE->getRHS()->EvaluateAsInt(IndexResult, S.Context,
7336                                        Expr::SE_NoSideEffects,
7337                                        S.isConstantEvaluated())) {
7338         sumOffsets(Offset, IndexResult.Val.getInt(), BO_Add,
7339                    /*RHS is int*/ true);
7340         E = ASE->getBase();
7341         goto tryAgain;
7342       }
7343     }
7344 
7345     return SLCT_NotALiteral;
7346   }
7347 
7348   default:
7349     return SLCT_NotALiteral;
7350   }
7351 }
7352 
7353 Sema::FormatStringType Sema::GetFormatStringType(const FormatAttr *Format) {
7354   return llvm::StringSwitch<FormatStringType>(Format->getType()->getName())
7355       .Case("scanf", FST_Scanf)
7356       .Cases("printf", "printf0", FST_Printf)
7357       .Cases("NSString", "CFString", FST_NSString)
7358       .Case("strftime", FST_Strftime)
7359       .Case("strfmon", FST_Strfmon)
7360       .Cases("kprintf", "cmn_err", "vcmn_err", "zcmn_err", FST_Kprintf)
7361       .Case("freebsd_kprintf", FST_FreeBSDKPrintf)
7362       .Case("os_trace", FST_OSLog)
7363       .Case("os_log", FST_OSLog)
7364       .Default(FST_Unknown);
7365 }
7366 
7367 /// CheckFormatArguments - Check calls to printf and scanf (and similar
7368 /// functions) for correct use of format strings.
7369 /// Returns true if a format string has been fully checked.
7370 bool Sema::CheckFormatArguments(const FormatAttr *Format,
7371                                 ArrayRef<const Expr *> Args,
7372                                 bool IsCXXMember,
7373                                 VariadicCallType CallType,
7374                                 SourceLocation Loc, SourceRange Range,
7375                                 llvm::SmallBitVector &CheckedVarArgs) {
7376   FormatStringInfo FSI;
7377   if (getFormatStringInfo(Format, IsCXXMember, &FSI))
7378     return CheckFormatArguments(Args, FSI.HasVAListArg, FSI.FormatIdx,
7379                                 FSI.FirstDataArg, GetFormatStringType(Format),
7380                                 CallType, Loc, Range, CheckedVarArgs);
7381   return false;
7382 }
7383 
7384 bool Sema::CheckFormatArguments(ArrayRef<const Expr *> Args,
7385                                 bool HasVAListArg, unsigned format_idx,
7386                                 unsigned firstDataArg, FormatStringType Type,
7387                                 VariadicCallType CallType,
7388                                 SourceLocation Loc, SourceRange Range,
7389                                 llvm::SmallBitVector &CheckedVarArgs) {
7390   // CHECK: printf/scanf-like function is called with no format string.
7391   if (format_idx >= Args.size()) {
7392     Diag(Loc, diag::warn_missing_format_string) << Range;
7393     return false;
7394   }
7395 
7396   const Expr *OrigFormatExpr = Args[format_idx]->IgnoreParenCasts();
7397 
7398   // CHECK: format string is not a string literal.
7399   //
7400   // Dynamically generated format strings are difficult to
7401   // automatically vet at compile time.  Requiring that format strings
7402   // are string literals: (1) permits the checking of format strings by
7403   // the compiler and thereby (2) can practically remove the source of
7404   // many format string exploits.
7405 
7406   // Format string can be either ObjC string (e.g. @"%d") or
7407   // C string (e.g. "%d")
7408   // ObjC string uses the same format specifiers as C string, so we can use
7409   // the same format string checking logic for both ObjC and C strings.
7410   UncoveredArgHandler UncoveredArg;
7411   StringLiteralCheckType CT =
7412       checkFormatStringExpr(*this, OrigFormatExpr, Args, HasVAListArg,
7413                             format_idx, firstDataArg, Type, CallType,
7414                             /*IsFunctionCall*/ true, CheckedVarArgs,
7415                             UncoveredArg,
7416                             /*no string offset*/ llvm::APSInt(64, false) = 0);
7417 
7418   // Generate a diagnostic where an uncovered argument is detected.
7419   if (UncoveredArg.hasUncoveredArg()) {
7420     unsigned ArgIdx = UncoveredArg.getUncoveredArg() + firstDataArg;
7421     assert(ArgIdx < Args.size() && "ArgIdx outside bounds");
7422     UncoveredArg.Diagnose(*this, /*IsFunctionCall*/true, Args[ArgIdx]);
7423   }
7424 
7425   if (CT != SLCT_NotALiteral)
7426     // Literal format string found, check done!
7427     return CT == SLCT_CheckedLiteral;
7428 
7429   // Strftime is particular as it always uses a single 'time' argument,
7430   // so it is safe to pass a non-literal string.
7431   if (Type == FST_Strftime)
7432     return false;
7433 
7434   // Do not emit diag when the string param is a macro expansion and the
7435   // format is either NSString or CFString. This is a hack to prevent
7436   // diag when using the NSLocalizedString and CFCopyLocalizedString macros
7437   // which are usually used in place of NS and CF string literals.
7438   SourceLocation FormatLoc = Args[format_idx]->getBeginLoc();
7439   if (Type == FST_NSString && SourceMgr.isInSystemMacro(FormatLoc))
7440     return false;
7441 
7442   // If there are no arguments specified, warn with -Wformat-security, otherwise
7443   // warn only with -Wformat-nonliteral.
7444   if (Args.size() == firstDataArg) {
7445     Diag(FormatLoc, diag::warn_format_nonliteral_noargs)
7446       << OrigFormatExpr->getSourceRange();
7447     switch (Type) {
7448     default:
7449       break;
7450     case FST_Kprintf:
7451     case FST_FreeBSDKPrintf:
7452     case FST_Printf:
7453       Diag(FormatLoc, diag::note_format_security_fixit)
7454         << FixItHint::CreateInsertion(FormatLoc, "\"%s\", ");
7455       break;
7456     case FST_NSString:
7457       Diag(FormatLoc, diag::note_format_security_fixit)
7458         << FixItHint::CreateInsertion(FormatLoc, "@\"%@\", ");
7459       break;
7460     }
7461   } else {
7462     Diag(FormatLoc, diag::warn_format_nonliteral)
7463       << OrigFormatExpr->getSourceRange();
7464   }
7465   return false;
7466 }
7467 
7468 namespace {
7469 
7470 class CheckFormatHandler : public analyze_format_string::FormatStringHandler {
7471 protected:
7472   Sema &S;
7473   const FormatStringLiteral *FExpr;
7474   const Expr *OrigFormatExpr;
7475   const Sema::FormatStringType FSType;
7476   const unsigned FirstDataArg;
7477   const unsigned NumDataArgs;
7478   const char *Beg; // Start of format string.
7479   const bool HasVAListArg;
7480   ArrayRef<const Expr *> Args;
7481   unsigned FormatIdx;
7482   llvm::SmallBitVector CoveredArgs;
7483   bool usesPositionalArgs = false;
7484   bool atFirstArg = true;
7485   bool inFunctionCall;
7486   Sema::VariadicCallType CallType;
7487   llvm::SmallBitVector &CheckedVarArgs;
7488   UncoveredArgHandler &UncoveredArg;
7489 
7490 public:
7491   CheckFormatHandler(Sema &s, const FormatStringLiteral *fexpr,
7492                      const Expr *origFormatExpr,
7493                      const Sema::FormatStringType type, unsigned firstDataArg,
7494                      unsigned numDataArgs, const char *beg, bool hasVAListArg,
7495                      ArrayRef<const Expr *> Args, unsigned formatIdx,
7496                      bool inFunctionCall, Sema::VariadicCallType callType,
7497                      llvm::SmallBitVector &CheckedVarArgs,
7498                      UncoveredArgHandler &UncoveredArg)
7499       : S(s), FExpr(fexpr), OrigFormatExpr(origFormatExpr), FSType(type),
7500         FirstDataArg(firstDataArg), NumDataArgs(numDataArgs), Beg(beg),
7501         HasVAListArg(hasVAListArg), Args(Args), FormatIdx(formatIdx),
7502         inFunctionCall(inFunctionCall), CallType(callType),
7503         CheckedVarArgs(CheckedVarArgs), UncoveredArg(UncoveredArg) {
7504     CoveredArgs.resize(numDataArgs);
7505     CoveredArgs.reset();
7506   }
7507 
7508   void DoneProcessing();
7509 
7510   void HandleIncompleteSpecifier(const char *startSpecifier,
7511                                  unsigned specifierLen) override;
7512 
7513   void HandleInvalidLengthModifier(
7514                            const analyze_format_string::FormatSpecifier &FS,
7515                            const analyze_format_string::ConversionSpecifier &CS,
7516                            const char *startSpecifier, unsigned specifierLen,
7517                            unsigned DiagID);
7518 
7519   void HandleNonStandardLengthModifier(
7520                     const analyze_format_string::FormatSpecifier &FS,
7521                     const char *startSpecifier, unsigned specifierLen);
7522 
7523   void HandleNonStandardConversionSpecifier(
7524                     const analyze_format_string::ConversionSpecifier &CS,
7525                     const char *startSpecifier, unsigned specifierLen);
7526 
7527   void HandlePosition(const char *startPos, unsigned posLen) override;
7528 
7529   void HandleInvalidPosition(const char *startSpecifier,
7530                              unsigned specifierLen,
7531                              analyze_format_string::PositionContext p) override;
7532 
7533   void HandleZeroPosition(const char *startPos, unsigned posLen) override;
7534 
7535   void HandleNullChar(const char *nullCharacter) override;
7536 
7537   template <typename Range>
7538   static void
7539   EmitFormatDiagnostic(Sema &S, bool inFunctionCall, const Expr *ArgumentExpr,
7540                        const PartialDiagnostic &PDiag, SourceLocation StringLoc,
7541                        bool IsStringLocation, Range StringRange,
7542                        ArrayRef<FixItHint> Fixit = None);
7543 
7544 protected:
7545   bool HandleInvalidConversionSpecifier(unsigned argIndex, SourceLocation Loc,
7546                                         const char *startSpec,
7547                                         unsigned specifierLen,
7548                                         const char *csStart, unsigned csLen);
7549 
7550   void HandlePositionalNonpositionalArgs(SourceLocation Loc,
7551                                          const char *startSpec,
7552                                          unsigned specifierLen);
7553 
7554   SourceRange getFormatStringRange();
7555   CharSourceRange getSpecifierRange(const char *startSpecifier,
7556                                     unsigned specifierLen);
7557   SourceLocation getLocationOfByte(const char *x);
7558 
7559   const Expr *getDataArg(unsigned i) const;
7560 
7561   bool CheckNumArgs(const analyze_format_string::FormatSpecifier &FS,
7562                     const analyze_format_string::ConversionSpecifier &CS,
7563                     const char *startSpecifier, unsigned specifierLen,
7564                     unsigned argIndex);
7565 
7566   template <typename Range>
7567   void EmitFormatDiagnostic(PartialDiagnostic PDiag, SourceLocation StringLoc,
7568                             bool IsStringLocation, Range StringRange,
7569                             ArrayRef<FixItHint> Fixit = None);
7570 };
7571 
7572 } // namespace
7573 
7574 SourceRange CheckFormatHandler::getFormatStringRange() {
7575   return OrigFormatExpr->getSourceRange();
7576 }
7577 
7578 CharSourceRange CheckFormatHandler::
7579 getSpecifierRange(const char *startSpecifier, unsigned specifierLen) {
7580   SourceLocation Start = getLocationOfByte(startSpecifier);
7581   SourceLocation End   = getLocationOfByte(startSpecifier + specifierLen - 1);
7582 
7583   // Advance the end SourceLocation by one due to half-open ranges.
7584   End = End.getLocWithOffset(1);
7585 
7586   return CharSourceRange::getCharRange(Start, End);
7587 }
7588 
7589 SourceLocation CheckFormatHandler::getLocationOfByte(const char *x) {
7590   return FExpr->getLocationOfByte(x - Beg, S.getSourceManager(),
7591                                   S.getLangOpts(), S.Context.getTargetInfo());
7592 }
7593 
7594 void CheckFormatHandler::HandleIncompleteSpecifier(const char *startSpecifier,
7595                                                    unsigned specifierLen){
7596   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_incomplete_specifier),
7597                        getLocationOfByte(startSpecifier),
7598                        /*IsStringLocation*/true,
7599                        getSpecifierRange(startSpecifier, specifierLen));
7600 }
7601 
7602 void CheckFormatHandler::HandleInvalidLengthModifier(
7603     const analyze_format_string::FormatSpecifier &FS,
7604     const analyze_format_string::ConversionSpecifier &CS,
7605     const char *startSpecifier, unsigned specifierLen, unsigned DiagID) {
7606   using namespace analyze_format_string;
7607 
7608   const LengthModifier &LM = FS.getLengthModifier();
7609   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7610 
7611   // See if we know how to fix this length modifier.
7612   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7613   if (FixedLM) {
7614     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7615                          getLocationOfByte(LM.getStart()),
7616                          /*IsStringLocation*/true,
7617                          getSpecifierRange(startSpecifier, specifierLen));
7618 
7619     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7620       << FixedLM->toString()
7621       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7622 
7623   } else {
7624     FixItHint Hint;
7625     if (DiagID == diag::warn_format_nonsensical_length)
7626       Hint = FixItHint::CreateRemoval(LMRange);
7627 
7628     EmitFormatDiagnostic(S.PDiag(DiagID) << LM.toString() << CS.toString(),
7629                          getLocationOfByte(LM.getStart()),
7630                          /*IsStringLocation*/true,
7631                          getSpecifierRange(startSpecifier, specifierLen),
7632                          Hint);
7633   }
7634 }
7635 
7636 void CheckFormatHandler::HandleNonStandardLengthModifier(
7637     const analyze_format_string::FormatSpecifier &FS,
7638     const char *startSpecifier, unsigned specifierLen) {
7639   using namespace analyze_format_string;
7640 
7641   const LengthModifier &LM = FS.getLengthModifier();
7642   CharSourceRange LMRange = getSpecifierRange(LM.getStart(), LM.getLength());
7643 
7644   // See if we know how to fix this length modifier.
7645   Optional<LengthModifier> FixedLM = FS.getCorrectedLengthModifier();
7646   if (FixedLM) {
7647     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7648                            << LM.toString() << 0,
7649                          getLocationOfByte(LM.getStart()),
7650                          /*IsStringLocation*/true,
7651                          getSpecifierRange(startSpecifier, specifierLen));
7652 
7653     S.Diag(getLocationOfByte(LM.getStart()), diag::note_format_fix_specifier)
7654       << FixedLM->toString()
7655       << FixItHint::CreateReplacement(LMRange, FixedLM->toString());
7656 
7657   } else {
7658     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7659                            << LM.toString() << 0,
7660                          getLocationOfByte(LM.getStart()),
7661                          /*IsStringLocation*/true,
7662                          getSpecifierRange(startSpecifier, specifierLen));
7663   }
7664 }
7665 
7666 void CheckFormatHandler::HandleNonStandardConversionSpecifier(
7667     const analyze_format_string::ConversionSpecifier &CS,
7668     const char *startSpecifier, unsigned specifierLen) {
7669   using namespace analyze_format_string;
7670 
7671   // See if we know how to fix this conversion specifier.
7672   Optional<ConversionSpecifier> FixedCS = CS.getStandardSpecifier();
7673   if (FixedCS) {
7674     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7675                           << CS.toString() << /*conversion specifier*/1,
7676                          getLocationOfByte(CS.getStart()),
7677                          /*IsStringLocation*/true,
7678                          getSpecifierRange(startSpecifier, specifierLen));
7679 
7680     CharSourceRange CSRange = getSpecifierRange(CS.getStart(), CS.getLength());
7681     S.Diag(getLocationOfByte(CS.getStart()), diag::note_format_fix_specifier)
7682       << FixedCS->toString()
7683       << FixItHint::CreateReplacement(CSRange, FixedCS->toString());
7684   } else {
7685     EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard)
7686                           << CS.toString() << /*conversion specifier*/1,
7687                          getLocationOfByte(CS.getStart()),
7688                          /*IsStringLocation*/true,
7689                          getSpecifierRange(startSpecifier, specifierLen));
7690   }
7691 }
7692 
7693 void CheckFormatHandler::HandlePosition(const char *startPos,
7694                                         unsigned posLen) {
7695   EmitFormatDiagnostic(S.PDiag(diag::warn_format_non_standard_positional_arg),
7696                                getLocationOfByte(startPos),
7697                                /*IsStringLocation*/true,
7698                                getSpecifierRange(startPos, posLen));
7699 }
7700 
7701 void
7702 CheckFormatHandler::HandleInvalidPosition(const char *startPos, unsigned posLen,
7703                                      analyze_format_string::PositionContext p) {
7704   EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_positional_specifier)
7705                          << (unsigned) p,
7706                        getLocationOfByte(startPos), /*IsStringLocation*/true,
7707                        getSpecifierRange(startPos, posLen));
7708 }
7709 
7710 void CheckFormatHandler::HandleZeroPosition(const char *startPos,
7711                                             unsigned posLen) {
7712   EmitFormatDiagnostic(S.PDiag(diag::warn_format_zero_positional_specifier),
7713                                getLocationOfByte(startPos),
7714                                /*IsStringLocation*/true,
7715                                getSpecifierRange(startPos, posLen));
7716 }
7717 
7718 void CheckFormatHandler::HandleNullChar(const char *nullCharacter) {
7719   if (!isa<ObjCStringLiteral>(OrigFormatExpr)) {
7720     // The presence of a null character is likely an error.
7721     EmitFormatDiagnostic(
7722       S.PDiag(diag::warn_printf_format_string_contains_null_char),
7723       getLocationOfByte(nullCharacter), /*IsStringLocation*/true,
7724       getFormatStringRange());
7725   }
7726 }
7727 
7728 // Note that this may return NULL if there was an error parsing or building
7729 // one of the argument expressions.
7730 const Expr *CheckFormatHandler::getDataArg(unsigned i) const {
7731   return Args[FirstDataArg + i];
7732 }
7733 
7734 void CheckFormatHandler::DoneProcessing() {
7735   // Does the number of data arguments exceed the number of
7736   // format conversions in the format string?
7737   if (!HasVAListArg) {
7738       // Find any arguments that weren't covered.
7739     CoveredArgs.flip();
7740     signed notCoveredArg = CoveredArgs.find_first();
7741     if (notCoveredArg >= 0) {
7742       assert((unsigned)notCoveredArg < NumDataArgs);
7743       UncoveredArg.Update(notCoveredArg, OrigFormatExpr);
7744     } else {
7745       UncoveredArg.setAllCovered();
7746     }
7747   }
7748 }
7749 
7750 void UncoveredArgHandler::Diagnose(Sema &S, bool IsFunctionCall,
7751                                    const Expr *ArgExpr) {
7752   assert(hasUncoveredArg() && DiagnosticExprs.size() > 0 &&
7753          "Invalid state");
7754 
7755   if (!ArgExpr)
7756     return;
7757 
7758   SourceLocation Loc = ArgExpr->getBeginLoc();
7759 
7760   if (S.getSourceManager().isInSystemMacro(Loc))
7761     return;
7762 
7763   PartialDiagnostic PDiag = S.PDiag(diag::warn_printf_data_arg_not_used);
7764   for (auto E : DiagnosticExprs)
7765     PDiag << E->getSourceRange();
7766 
7767   CheckFormatHandler::EmitFormatDiagnostic(
7768                                   S, IsFunctionCall, DiagnosticExprs[0],
7769                                   PDiag, Loc, /*IsStringLocation*/false,
7770                                   DiagnosticExprs[0]->getSourceRange());
7771 }
7772 
7773 bool
7774 CheckFormatHandler::HandleInvalidConversionSpecifier(unsigned argIndex,
7775                                                      SourceLocation Loc,
7776                                                      const char *startSpec,
7777                                                      unsigned specifierLen,
7778                                                      const char *csStart,
7779                                                      unsigned csLen) {
7780   bool keepGoing = true;
7781   if (argIndex < NumDataArgs) {
7782     // Consider the argument coverered, even though the specifier doesn't
7783     // make sense.
7784     CoveredArgs.set(argIndex);
7785   }
7786   else {
7787     // If argIndex exceeds the number of data arguments we
7788     // don't issue a warning because that is just a cascade of warnings (and
7789     // they may have intended '%%' anyway). We don't want to continue processing
7790     // the format string after this point, however, as we will like just get
7791     // gibberish when trying to match arguments.
7792     keepGoing = false;
7793   }
7794 
7795   StringRef Specifier(csStart, csLen);
7796 
7797   // If the specifier in non-printable, it could be the first byte of a UTF-8
7798   // sequence. In that case, print the UTF-8 code point. If not, print the byte
7799   // hex value.
7800   std::string CodePointStr;
7801   if (!llvm::sys::locale::isPrint(*csStart)) {
7802     llvm::UTF32 CodePoint;
7803     const llvm::UTF8 **B = reinterpret_cast<const llvm::UTF8 **>(&csStart);
7804     const llvm::UTF8 *E =
7805         reinterpret_cast<const llvm::UTF8 *>(csStart + csLen);
7806     llvm::ConversionResult Result =
7807         llvm::convertUTF8Sequence(B, E, &CodePoint, llvm::strictConversion);
7808 
7809     if (Result != llvm::conversionOK) {
7810       unsigned char FirstChar = *csStart;
7811       CodePoint = (llvm::UTF32)FirstChar;
7812     }
7813 
7814     llvm::raw_string_ostream OS(CodePointStr);
7815     if (CodePoint < 256)
7816       OS << "\\x" << llvm::format("%02x", CodePoint);
7817     else if (CodePoint <= 0xFFFF)
7818       OS << "\\u" << llvm::format("%04x", CodePoint);
7819     else
7820       OS << "\\U" << llvm::format("%08x", CodePoint);
7821     OS.flush();
7822     Specifier = CodePointStr;
7823   }
7824 
7825   EmitFormatDiagnostic(
7826       S.PDiag(diag::warn_format_invalid_conversion) << Specifier, Loc,
7827       /*IsStringLocation*/ true, getSpecifierRange(startSpec, specifierLen));
7828 
7829   return keepGoing;
7830 }
7831 
7832 void
7833 CheckFormatHandler::HandlePositionalNonpositionalArgs(SourceLocation Loc,
7834                                                       const char *startSpec,
7835                                                       unsigned specifierLen) {
7836   EmitFormatDiagnostic(
7837     S.PDiag(diag::warn_format_mix_positional_nonpositional_args),
7838     Loc, /*isStringLoc*/true, getSpecifierRange(startSpec, specifierLen));
7839 }
7840 
7841 bool
7842 CheckFormatHandler::CheckNumArgs(
7843   const analyze_format_string::FormatSpecifier &FS,
7844   const analyze_format_string::ConversionSpecifier &CS,
7845   const char *startSpecifier, unsigned specifierLen, unsigned argIndex) {
7846 
7847   if (argIndex >= NumDataArgs) {
7848     PartialDiagnostic PDiag = FS.usesPositionalArg()
7849       ? (S.PDiag(diag::warn_printf_positional_arg_exceeds_data_args)
7850            << (argIndex+1) << NumDataArgs)
7851       : S.PDiag(diag::warn_printf_insufficient_data_args);
7852     EmitFormatDiagnostic(
7853       PDiag, getLocationOfByte(CS.getStart()), /*IsStringLocation*/true,
7854       getSpecifierRange(startSpecifier, specifierLen));
7855 
7856     // Since more arguments than conversion tokens are given, by extension
7857     // all arguments are covered, so mark this as so.
7858     UncoveredArg.setAllCovered();
7859     return false;
7860   }
7861   return true;
7862 }
7863 
7864 template<typename Range>
7865 void CheckFormatHandler::EmitFormatDiagnostic(PartialDiagnostic PDiag,
7866                                               SourceLocation Loc,
7867                                               bool IsStringLocation,
7868                                               Range StringRange,
7869                                               ArrayRef<FixItHint> FixIt) {
7870   EmitFormatDiagnostic(S, inFunctionCall, Args[FormatIdx], PDiag,
7871                        Loc, IsStringLocation, StringRange, FixIt);
7872 }
7873 
7874 /// If the format string is not within the function call, emit a note
7875 /// so that the function call and string are in diagnostic messages.
7876 ///
7877 /// \param InFunctionCall if true, the format string is within the function
7878 /// call and only one diagnostic message will be produced.  Otherwise, an
7879 /// extra note will be emitted pointing to location of the format string.
7880 ///
7881 /// \param ArgumentExpr the expression that is passed as the format string
7882 /// argument in the function call.  Used for getting locations when two
7883 /// diagnostics are emitted.
7884 ///
7885 /// \param PDiag the callee should already have provided any strings for the
7886 /// diagnostic message.  This function only adds locations and fixits
7887 /// to diagnostics.
7888 ///
7889 /// \param Loc primary location for diagnostic.  If two diagnostics are
7890 /// required, one will be at Loc and a new SourceLocation will be created for
7891 /// the other one.
7892 ///
7893 /// \param IsStringLocation if true, Loc points to the format string should be
7894 /// used for the note.  Otherwise, Loc points to the argument list and will
7895 /// be used with PDiag.
7896 ///
7897 /// \param StringRange some or all of the string to highlight.  This is
7898 /// templated so it can accept either a CharSourceRange or a SourceRange.
7899 ///
7900 /// \param FixIt optional fix it hint for the format string.
7901 template <typename Range>
7902 void CheckFormatHandler::EmitFormatDiagnostic(
7903     Sema &S, bool InFunctionCall, const Expr *ArgumentExpr,
7904     const PartialDiagnostic &PDiag, SourceLocation Loc, bool IsStringLocation,
7905     Range StringRange, ArrayRef<FixItHint> FixIt) {
7906   if (InFunctionCall) {
7907     const Sema::SemaDiagnosticBuilder &D = S.Diag(Loc, PDiag);
7908     D << StringRange;
7909     D << FixIt;
7910   } else {
7911     S.Diag(IsStringLocation ? ArgumentExpr->getExprLoc() : Loc, PDiag)
7912       << ArgumentExpr->getSourceRange();
7913 
7914     const Sema::SemaDiagnosticBuilder &Note =
7915       S.Diag(IsStringLocation ? Loc : StringRange.getBegin(),
7916              diag::note_format_string_defined);
7917 
7918     Note << StringRange;
7919     Note << FixIt;
7920   }
7921 }
7922 
7923 //===--- CHECK: Printf format string checking ------------------------------===//
7924 
7925 namespace {
7926 
7927 class CheckPrintfHandler : public CheckFormatHandler {
7928 public:
7929   CheckPrintfHandler(Sema &s, const FormatStringLiteral *fexpr,
7930                      const Expr *origFormatExpr,
7931                      const Sema::FormatStringType type, unsigned firstDataArg,
7932                      unsigned numDataArgs, bool isObjC, const char *beg,
7933                      bool hasVAListArg, ArrayRef<const Expr *> Args,
7934                      unsigned formatIdx, bool inFunctionCall,
7935                      Sema::VariadicCallType CallType,
7936                      llvm::SmallBitVector &CheckedVarArgs,
7937                      UncoveredArgHandler &UncoveredArg)
7938       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
7939                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
7940                            inFunctionCall, CallType, CheckedVarArgs,
7941                            UncoveredArg) {}
7942 
7943   bool isObjCContext() const { return FSType == Sema::FST_NSString; }
7944 
7945   /// Returns true if '%@' specifiers are allowed in the format string.
7946   bool allowsObjCArg() const {
7947     return FSType == Sema::FST_NSString || FSType == Sema::FST_OSLog ||
7948            FSType == Sema::FST_OSTrace;
7949   }
7950 
7951   bool HandleInvalidPrintfConversionSpecifier(
7952                                       const analyze_printf::PrintfSpecifier &FS,
7953                                       const char *startSpecifier,
7954                                       unsigned specifierLen) override;
7955 
7956   void handleInvalidMaskType(StringRef MaskType) override;
7957 
7958   bool HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier &FS,
7959                              const char *startSpecifier,
7960                              unsigned specifierLen) override;
7961   bool checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
7962                        const char *StartSpecifier,
7963                        unsigned SpecifierLen,
7964                        const Expr *E);
7965 
7966   bool HandleAmount(const analyze_format_string::OptionalAmount &Amt, unsigned k,
7967                     const char *startSpecifier, unsigned specifierLen);
7968   void HandleInvalidAmount(const analyze_printf::PrintfSpecifier &FS,
7969                            const analyze_printf::OptionalAmount &Amt,
7970                            unsigned type,
7971                            const char *startSpecifier, unsigned specifierLen);
7972   void HandleFlag(const analyze_printf::PrintfSpecifier &FS,
7973                   const analyze_printf::OptionalFlag &flag,
7974                   const char *startSpecifier, unsigned specifierLen);
7975   void HandleIgnoredFlag(const analyze_printf::PrintfSpecifier &FS,
7976                          const analyze_printf::OptionalFlag &ignoredFlag,
7977                          const analyze_printf::OptionalFlag &flag,
7978                          const char *startSpecifier, unsigned specifierLen);
7979   bool checkForCStrMembers(const analyze_printf::ArgType &AT,
7980                            const Expr *E);
7981 
7982   void HandleEmptyObjCModifierFlag(const char *startFlag,
7983                                    unsigned flagLen) override;
7984 
7985   void HandleInvalidObjCModifierFlag(const char *startFlag,
7986                                             unsigned flagLen) override;
7987 
7988   void HandleObjCFlagsWithNonObjCConversion(const char *flagsStart,
7989                                            const char *flagsEnd,
7990                                            const char *conversionPosition)
7991                                              override;
7992 };
7993 
7994 } // namespace
7995 
7996 bool CheckPrintfHandler::HandleInvalidPrintfConversionSpecifier(
7997                                       const analyze_printf::PrintfSpecifier &FS,
7998                                       const char *startSpecifier,
7999                                       unsigned specifierLen) {
8000   const analyze_printf::PrintfConversionSpecifier &CS =
8001     FS.getConversionSpecifier();
8002 
8003   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8004                                           getLocationOfByte(CS.getStart()),
8005                                           startSpecifier, specifierLen,
8006                                           CS.getStart(), CS.getLength());
8007 }
8008 
8009 void CheckPrintfHandler::handleInvalidMaskType(StringRef MaskType) {
8010   S.Diag(getLocationOfByte(MaskType.data()), diag::err_invalid_mask_type_size);
8011 }
8012 
8013 bool CheckPrintfHandler::HandleAmount(
8014                                const analyze_format_string::OptionalAmount &Amt,
8015                                unsigned k, const char *startSpecifier,
8016                                unsigned specifierLen) {
8017   if (Amt.hasDataArgument()) {
8018     if (!HasVAListArg) {
8019       unsigned argIndex = Amt.getArgIndex();
8020       if (argIndex >= NumDataArgs) {
8021         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_missing_arg)
8022                                << k,
8023                              getLocationOfByte(Amt.getStart()),
8024                              /*IsStringLocation*/true,
8025                              getSpecifierRange(startSpecifier, specifierLen));
8026         // Don't do any more checking.  We will just emit
8027         // spurious errors.
8028         return false;
8029       }
8030 
8031       // Type check the data argument.  It should be an 'int'.
8032       // Although not in conformance with C99, we also allow the argument to be
8033       // an 'unsigned int' as that is a reasonably safe case.  GCC also
8034       // doesn't emit a warning for that case.
8035       CoveredArgs.set(argIndex);
8036       const Expr *Arg = getDataArg(argIndex);
8037       if (!Arg)
8038         return false;
8039 
8040       QualType T = Arg->getType();
8041 
8042       const analyze_printf::ArgType &AT = Amt.getArgType(S.Context);
8043       assert(AT.isValid());
8044 
8045       if (!AT.matchesType(S.Context, T)) {
8046         EmitFormatDiagnostic(S.PDiag(diag::warn_printf_asterisk_wrong_type)
8047                                << k << AT.getRepresentativeTypeName(S.Context)
8048                                << T << Arg->getSourceRange(),
8049                              getLocationOfByte(Amt.getStart()),
8050                              /*IsStringLocation*/true,
8051                              getSpecifierRange(startSpecifier, specifierLen));
8052         // Don't do any more checking.  We will just emit
8053         // spurious errors.
8054         return false;
8055       }
8056     }
8057   }
8058   return true;
8059 }
8060 
8061 void CheckPrintfHandler::HandleInvalidAmount(
8062                                       const analyze_printf::PrintfSpecifier &FS,
8063                                       const analyze_printf::OptionalAmount &Amt,
8064                                       unsigned type,
8065                                       const char *startSpecifier,
8066                                       unsigned specifierLen) {
8067   const analyze_printf::PrintfConversionSpecifier &CS =
8068     FS.getConversionSpecifier();
8069 
8070   FixItHint fixit =
8071     Amt.getHowSpecified() == analyze_printf::OptionalAmount::Constant
8072       ? FixItHint::CreateRemoval(getSpecifierRange(Amt.getStart(),
8073                                  Amt.getConstantLength()))
8074       : FixItHint();
8075 
8076   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_optional_amount)
8077                          << type << CS.toString(),
8078                        getLocationOfByte(Amt.getStart()),
8079                        /*IsStringLocation*/true,
8080                        getSpecifierRange(startSpecifier, specifierLen),
8081                        fixit);
8082 }
8083 
8084 void CheckPrintfHandler::HandleFlag(const analyze_printf::PrintfSpecifier &FS,
8085                                     const analyze_printf::OptionalFlag &flag,
8086                                     const char *startSpecifier,
8087                                     unsigned specifierLen) {
8088   // Warn about pointless flag with a fixit removal.
8089   const analyze_printf::PrintfConversionSpecifier &CS =
8090     FS.getConversionSpecifier();
8091   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_nonsensical_flag)
8092                          << flag.toString() << CS.toString(),
8093                        getLocationOfByte(flag.getPosition()),
8094                        /*IsStringLocation*/true,
8095                        getSpecifierRange(startSpecifier, specifierLen),
8096                        FixItHint::CreateRemoval(
8097                          getSpecifierRange(flag.getPosition(), 1)));
8098 }
8099 
8100 void CheckPrintfHandler::HandleIgnoredFlag(
8101                                 const analyze_printf::PrintfSpecifier &FS,
8102                                 const analyze_printf::OptionalFlag &ignoredFlag,
8103                                 const analyze_printf::OptionalFlag &flag,
8104                                 const char *startSpecifier,
8105                                 unsigned specifierLen) {
8106   // Warn about ignored flag with a fixit removal.
8107   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_ignored_flag)
8108                          << ignoredFlag.toString() << flag.toString(),
8109                        getLocationOfByte(ignoredFlag.getPosition()),
8110                        /*IsStringLocation*/true,
8111                        getSpecifierRange(startSpecifier, specifierLen),
8112                        FixItHint::CreateRemoval(
8113                          getSpecifierRange(ignoredFlag.getPosition(), 1)));
8114 }
8115 
8116 void CheckPrintfHandler::HandleEmptyObjCModifierFlag(const char *startFlag,
8117                                                      unsigned flagLen) {
8118   // Warn about an empty flag.
8119   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_empty_objc_flag),
8120                        getLocationOfByte(startFlag),
8121                        /*IsStringLocation*/true,
8122                        getSpecifierRange(startFlag, flagLen));
8123 }
8124 
8125 void CheckPrintfHandler::HandleInvalidObjCModifierFlag(const char *startFlag,
8126                                                        unsigned flagLen) {
8127   // Warn about an invalid flag.
8128   auto Range = getSpecifierRange(startFlag, flagLen);
8129   StringRef flag(startFlag, flagLen);
8130   EmitFormatDiagnostic(S.PDiag(diag::warn_printf_invalid_objc_flag) << flag,
8131                       getLocationOfByte(startFlag),
8132                       /*IsStringLocation*/true,
8133                       Range, FixItHint::CreateRemoval(Range));
8134 }
8135 
8136 void CheckPrintfHandler::HandleObjCFlagsWithNonObjCConversion(
8137     const char *flagsStart, const char *flagsEnd, const char *conversionPosition) {
8138     // Warn about using '[...]' without a '@' conversion.
8139     auto Range = getSpecifierRange(flagsStart, flagsEnd - flagsStart + 1);
8140     auto diag = diag::warn_printf_ObjCflags_without_ObjCConversion;
8141     EmitFormatDiagnostic(S.PDiag(diag) << StringRef(conversionPosition, 1),
8142                          getLocationOfByte(conversionPosition),
8143                          /*IsStringLocation*/true,
8144                          Range, FixItHint::CreateRemoval(Range));
8145 }
8146 
8147 // Determines if the specified is a C++ class or struct containing
8148 // a member with the specified name and kind (e.g. a CXXMethodDecl named
8149 // "c_str()").
8150 template<typename MemberKind>
8151 static llvm::SmallPtrSet<MemberKind*, 1>
8152 CXXRecordMembersNamed(StringRef Name, Sema &S, QualType Ty) {
8153   const RecordType *RT = Ty->getAs<RecordType>();
8154   llvm::SmallPtrSet<MemberKind*, 1> Results;
8155 
8156   if (!RT)
8157     return Results;
8158   const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
8159   if (!RD || !RD->getDefinition())
8160     return Results;
8161 
8162   LookupResult R(S, &S.Context.Idents.get(Name), SourceLocation(),
8163                  Sema::LookupMemberName);
8164   R.suppressDiagnostics();
8165 
8166   // We just need to include all members of the right kind turned up by the
8167   // filter, at this point.
8168   if (S.LookupQualifiedName(R, RT->getDecl()))
8169     for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
8170       NamedDecl *decl = (*I)->getUnderlyingDecl();
8171       if (MemberKind *FK = dyn_cast<MemberKind>(decl))
8172         Results.insert(FK);
8173     }
8174   return Results;
8175 }
8176 
8177 /// Check if we could call '.c_str()' on an object.
8178 ///
8179 /// FIXME: This returns the wrong results in some cases (if cv-qualifiers don't
8180 /// allow the call, or if it would be ambiguous).
8181 bool Sema::hasCStrMethod(const Expr *E) {
8182   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8183 
8184   MethodSet Results =
8185       CXXRecordMembersNamed<CXXMethodDecl>("c_str", *this, E->getType());
8186   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8187        MI != ME; ++MI)
8188     if ((*MI)->getMinRequiredArguments() == 0)
8189       return true;
8190   return false;
8191 }
8192 
8193 // Check if a (w)string was passed when a (w)char* was needed, and offer a
8194 // better diagnostic if so. AT is assumed to be valid.
8195 // Returns true when a c_str() conversion method is found.
8196 bool CheckPrintfHandler::checkForCStrMembers(
8197     const analyze_printf::ArgType &AT, const Expr *E) {
8198   using MethodSet = llvm::SmallPtrSet<CXXMethodDecl *, 1>;
8199 
8200   MethodSet Results =
8201       CXXRecordMembersNamed<CXXMethodDecl>("c_str", S, E->getType());
8202 
8203   for (MethodSet::iterator MI = Results.begin(), ME = Results.end();
8204        MI != ME; ++MI) {
8205     const CXXMethodDecl *Method = *MI;
8206     if (Method->getMinRequiredArguments() == 0 &&
8207         AT.matchesType(S.Context, Method->getReturnType())) {
8208       // FIXME: Suggest parens if the expression needs them.
8209       SourceLocation EndLoc = S.getLocForEndOfToken(E->getEndLoc());
8210       S.Diag(E->getBeginLoc(), diag::note_printf_c_str)
8211           << "c_str()" << FixItHint::CreateInsertion(EndLoc, ".c_str()");
8212       return true;
8213     }
8214   }
8215 
8216   return false;
8217 }
8218 
8219 bool
8220 CheckPrintfHandler::HandlePrintfSpecifier(const analyze_printf::PrintfSpecifier
8221                                             &FS,
8222                                           const char *startSpecifier,
8223                                           unsigned specifierLen) {
8224   using namespace analyze_format_string;
8225   using namespace analyze_printf;
8226 
8227   const PrintfConversionSpecifier &CS = FS.getConversionSpecifier();
8228 
8229   if (FS.consumesDataArgument()) {
8230     if (atFirstArg) {
8231         atFirstArg = false;
8232         usesPositionalArgs = FS.usesPositionalArg();
8233     }
8234     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8235       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8236                                         startSpecifier, specifierLen);
8237       return false;
8238     }
8239   }
8240 
8241   // First check if the field width, precision, and conversion specifier
8242   // have matching data arguments.
8243   if (!HandleAmount(FS.getFieldWidth(), /* field width */ 0,
8244                     startSpecifier, specifierLen)) {
8245     return false;
8246   }
8247 
8248   if (!HandleAmount(FS.getPrecision(), /* precision */ 1,
8249                     startSpecifier, specifierLen)) {
8250     return false;
8251   }
8252 
8253   if (!CS.consumesDataArgument()) {
8254     // FIXME: Technically specifying a precision or field width here
8255     // makes no sense.  Worth issuing a warning at some point.
8256     return true;
8257   }
8258 
8259   // Consume the argument.
8260   unsigned argIndex = FS.getArgIndex();
8261   if (argIndex < NumDataArgs) {
8262     // The check to see if the argIndex is valid will come later.
8263     // We set the bit here because we may exit early from this
8264     // function if we encounter some other error.
8265     CoveredArgs.set(argIndex);
8266   }
8267 
8268   // FreeBSD kernel extensions.
8269   if (CS.getKind() == ConversionSpecifier::FreeBSDbArg ||
8270       CS.getKind() == ConversionSpecifier::FreeBSDDArg) {
8271     // We need at least two arguments.
8272     if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex + 1))
8273       return false;
8274 
8275     // Claim the second argument.
8276     CoveredArgs.set(argIndex + 1);
8277 
8278     // Type check the first argument (int for %b, pointer for %D)
8279     const Expr *Ex = getDataArg(argIndex);
8280     const analyze_printf::ArgType &AT =
8281       (CS.getKind() == ConversionSpecifier::FreeBSDbArg) ?
8282         ArgType(S.Context.IntTy) : ArgType::CPointerTy;
8283     if (AT.isValid() && !AT.matchesType(S.Context, Ex->getType()))
8284       EmitFormatDiagnostic(
8285           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8286               << AT.getRepresentativeTypeName(S.Context) << Ex->getType()
8287               << false << Ex->getSourceRange(),
8288           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8289           getSpecifierRange(startSpecifier, specifierLen));
8290 
8291     // Type check the second argument (char * for both %b and %D)
8292     Ex = getDataArg(argIndex + 1);
8293     const analyze_printf::ArgType &AT2 = ArgType::CStrTy;
8294     if (AT2.isValid() && !AT2.matchesType(S.Context, Ex->getType()))
8295       EmitFormatDiagnostic(
8296           S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8297               << AT2.getRepresentativeTypeName(S.Context) << Ex->getType()
8298               << false << Ex->getSourceRange(),
8299           Ex->getBeginLoc(), /*IsStringLocation*/ false,
8300           getSpecifierRange(startSpecifier, specifierLen));
8301 
8302      return true;
8303   }
8304 
8305   // Check for using an Objective-C specific conversion specifier
8306   // in a non-ObjC literal.
8307   if (!allowsObjCArg() && CS.isObjCArg()) {
8308     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8309                                                   specifierLen);
8310   }
8311 
8312   // %P can only be used with os_log.
8313   if (FSType != Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::PArg) {
8314     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8315                                                   specifierLen);
8316   }
8317 
8318   // %n is not allowed with os_log.
8319   if (FSType == Sema::FST_OSLog && CS.getKind() == ConversionSpecifier::nArg) {
8320     EmitFormatDiagnostic(S.PDiag(diag::warn_os_log_format_narg),
8321                          getLocationOfByte(CS.getStart()),
8322                          /*IsStringLocation*/ false,
8323                          getSpecifierRange(startSpecifier, specifierLen));
8324 
8325     return true;
8326   }
8327 
8328   // Only scalars are allowed for os_trace.
8329   if (FSType == Sema::FST_OSTrace &&
8330       (CS.getKind() == ConversionSpecifier::PArg ||
8331        CS.getKind() == ConversionSpecifier::sArg ||
8332        CS.getKind() == ConversionSpecifier::ObjCObjArg)) {
8333     return HandleInvalidPrintfConversionSpecifier(FS, startSpecifier,
8334                                                   specifierLen);
8335   }
8336 
8337   // Check for use of public/private annotation outside of os_log().
8338   if (FSType != Sema::FST_OSLog) {
8339     if (FS.isPublic().isSet()) {
8340       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8341                                << "public",
8342                            getLocationOfByte(FS.isPublic().getPosition()),
8343                            /*IsStringLocation*/ false,
8344                            getSpecifierRange(startSpecifier, specifierLen));
8345     }
8346     if (FS.isPrivate().isSet()) {
8347       EmitFormatDiagnostic(S.PDiag(diag::warn_format_invalid_annotation)
8348                                << "private",
8349                            getLocationOfByte(FS.isPrivate().getPosition()),
8350                            /*IsStringLocation*/ false,
8351                            getSpecifierRange(startSpecifier, specifierLen));
8352     }
8353   }
8354 
8355   // Check for invalid use of field width
8356   if (!FS.hasValidFieldWidth()) {
8357     HandleInvalidAmount(FS, FS.getFieldWidth(), /* field width */ 0,
8358         startSpecifier, specifierLen);
8359   }
8360 
8361   // Check for invalid use of precision
8362   if (!FS.hasValidPrecision()) {
8363     HandleInvalidAmount(FS, FS.getPrecision(), /* precision */ 1,
8364         startSpecifier, specifierLen);
8365   }
8366 
8367   // Precision is mandatory for %P specifier.
8368   if (CS.getKind() == ConversionSpecifier::PArg &&
8369       FS.getPrecision().getHowSpecified() == OptionalAmount::NotSpecified) {
8370     EmitFormatDiagnostic(S.PDiag(diag::warn_format_P_no_precision),
8371                          getLocationOfByte(startSpecifier),
8372                          /*IsStringLocation*/ false,
8373                          getSpecifierRange(startSpecifier, specifierLen));
8374   }
8375 
8376   // Check each flag does not conflict with any other component.
8377   if (!FS.hasValidThousandsGroupingPrefix())
8378     HandleFlag(FS, FS.hasThousandsGrouping(), startSpecifier, specifierLen);
8379   if (!FS.hasValidLeadingZeros())
8380     HandleFlag(FS, FS.hasLeadingZeros(), startSpecifier, specifierLen);
8381   if (!FS.hasValidPlusPrefix())
8382     HandleFlag(FS, FS.hasPlusPrefix(), startSpecifier, specifierLen);
8383   if (!FS.hasValidSpacePrefix())
8384     HandleFlag(FS, FS.hasSpacePrefix(), startSpecifier, specifierLen);
8385   if (!FS.hasValidAlternativeForm())
8386     HandleFlag(FS, FS.hasAlternativeForm(), startSpecifier, specifierLen);
8387   if (!FS.hasValidLeftJustified())
8388     HandleFlag(FS, FS.isLeftJustified(), startSpecifier, specifierLen);
8389 
8390   // Check that flags are not ignored by another flag
8391   if (FS.hasSpacePrefix() && FS.hasPlusPrefix()) // ' ' ignored by '+'
8392     HandleIgnoredFlag(FS, FS.hasSpacePrefix(), FS.hasPlusPrefix(),
8393         startSpecifier, specifierLen);
8394   if (FS.hasLeadingZeros() && FS.isLeftJustified()) // '0' ignored by '-'
8395     HandleIgnoredFlag(FS, FS.hasLeadingZeros(), FS.isLeftJustified(),
8396             startSpecifier, specifierLen);
8397 
8398   // Check the length modifier is valid with the given conversion specifier.
8399   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8400                                  S.getLangOpts()))
8401     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8402                                 diag::warn_format_nonsensical_length);
8403   else if (!FS.hasStandardLengthModifier())
8404     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8405   else if (!FS.hasStandardLengthConversionCombination())
8406     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8407                                 diag::warn_format_non_standard_conversion_spec);
8408 
8409   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8410     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8411 
8412   // The remaining checks depend on the data arguments.
8413   if (HasVAListArg)
8414     return true;
8415 
8416   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8417     return false;
8418 
8419   const Expr *Arg = getDataArg(argIndex);
8420   if (!Arg)
8421     return true;
8422 
8423   return checkFormatExpr(FS, startSpecifier, specifierLen, Arg);
8424 }
8425 
8426 static bool requiresParensToAddCast(const Expr *E) {
8427   // FIXME: We should have a general way to reason about operator
8428   // precedence and whether parens are actually needed here.
8429   // Take care of a few common cases where they aren't.
8430   const Expr *Inside = E->IgnoreImpCasts();
8431   if (const PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(Inside))
8432     Inside = POE->getSyntacticForm()->IgnoreImpCasts();
8433 
8434   switch (Inside->getStmtClass()) {
8435   case Stmt::ArraySubscriptExprClass:
8436   case Stmt::CallExprClass:
8437   case Stmt::CharacterLiteralClass:
8438   case Stmt::CXXBoolLiteralExprClass:
8439   case Stmt::DeclRefExprClass:
8440   case Stmt::FloatingLiteralClass:
8441   case Stmt::IntegerLiteralClass:
8442   case Stmt::MemberExprClass:
8443   case Stmt::ObjCArrayLiteralClass:
8444   case Stmt::ObjCBoolLiteralExprClass:
8445   case Stmt::ObjCBoxedExprClass:
8446   case Stmt::ObjCDictionaryLiteralClass:
8447   case Stmt::ObjCEncodeExprClass:
8448   case Stmt::ObjCIvarRefExprClass:
8449   case Stmt::ObjCMessageExprClass:
8450   case Stmt::ObjCPropertyRefExprClass:
8451   case Stmt::ObjCStringLiteralClass:
8452   case Stmt::ObjCSubscriptRefExprClass:
8453   case Stmt::ParenExprClass:
8454   case Stmt::StringLiteralClass:
8455   case Stmt::UnaryOperatorClass:
8456     return false;
8457   default:
8458     return true;
8459   }
8460 }
8461 
8462 static std::pair<QualType, StringRef>
8463 shouldNotPrintDirectly(const ASTContext &Context,
8464                        QualType IntendedTy,
8465                        const Expr *E) {
8466   // Use a 'while' to peel off layers of typedefs.
8467   QualType TyTy = IntendedTy;
8468   while (const TypedefType *UserTy = TyTy->getAs<TypedefType>()) {
8469     StringRef Name = UserTy->getDecl()->getName();
8470     QualType CastTy = llvm::StringSwitch<QualType>(Name)
8471       .Case("CFIndex", Context.getNSIntegerType())
8472       .Case("NSInteger", Context.getNSIntegerType())
8473       .Case("NSUInteger", Context.getNSUIntegerType())
8474       .Case("SInt32", Context.IntTy)
8475       .Case("UInt32", Context.UnsignedIntTy)
8476       .Default(QualType());
8477 
8478     if (!CastTy.isNull())
8479       return std::make_pair(CastTy, Name);
8480 
8481     TyTy = UserTy->desugar();
8482   }
8483 
8484   // Strip parens if necessary.
8485   if (const ParenExpr *PE = dyn_cast<ParenExpr>(E))
8486     return shouldNotPrintDirectly(Context,
8487                                   PE->getSubExpr()->getType(),
8488                                   PE->getSubExpr());
8489 
8490   // If this is a conditional expression, then its result type is constructed
8491   // via usual arithmetic conversions and thus there might be no necessary
8492   // typedef sugar there.  Recurse to operands to check for NSInteger &
8493   // Co. usage condition.
8494   if (const ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
8495     QualType TrueTy, FalseTy;
8496     StringRef TrueName, FalseName;
8497 
8498     std::tie(TrueTy, TrueName) =
8499       shouldNotPrintDirectly(Context,
8500                              CO->getTrueExpr()->getType(),
8501                              CO->getTrueExpr());
8502     std::tie(FalseTy, FalseName) =
8503       shouldNotPrintDirectly(Context,
8504                              CO->getFalseExpr()->getType(),
8505                              CO->getFalseExpr());
8506 
8507     if (TrueTy == FalseTy)
8508       return std::make_pair(TrueTy, TrueName);
8509     else if (TrueTy.isNull())
8510       return std::make_pair(FalseTy, FalseName);
8511     else if (FalseTy.isNull())
8512       return std::make_pair(TrueTy, TrueName);
8513   }
8514 
8515   return std::make_pair(QualType(), StringRef());
8516 }
8517 
8518 /// Return true if \p ICE is an implicit argument promotion of an arithmetic
8519 /// type. Bit-field 'promotions' from a higher ranked type to a lower ranked
8520 /// type do not count.
8521 static bool
8522 isArithmeticArgumentPromotion(Sema &S, const ImplicitCastExpr *ICE) {
8523   QualType From = ICE->getSubExpr()->getType();
8524   QualType To = ICE->getType();
8525   // It's an integer promotion if the destination type is the promoted
8526   // source type.
8527   if (ICE->getCastKind() == CK_IntegralCast &&
8528       From->isPromotableIntegerType() &&
8529       S.Context.getPromotedIntegerType(From) == To)
8530     return true;
8531   // Look through vector types, since we do default argument promotion for
8532   // those in OpenCL.
8533   if (const auto *VecTy = From->getAs<ExtVectorType>())
8534     From = VecTy->getElementType();
8535   if (const auto *VecTy = To->getAs<ExtVectorType>())
8536     To = VecTy->getElementType();
8537   // It's a floating promotion if the source type is a lower rank.
8538   return ICE->getCastKind() == CK_FloatingCast &&
8539          S.Context.getFloatingTypeOrder(From, To) < 0;
8540 }
8541 
8542 bool
8543 CheckPrintfHandler::checkFormatExpr(const analyze_printf::PrintfSpecifier &FS,
8544                                     const char *StartSpecifier,
8545                                     unsigned SpecifierLen,
8546                                     const Expr *E) {
8547   using namespace analyze_format_string;
8548   using namespace analyze_printf;
8549 
8550   // Now type check the data expression that matches the
8551   // format specifier.
8552   const analyze_printf::ArgType &AT = FS.getArgType(S.Context, isObjCContext());
8553   if (!AT.isValid())
8554     return true;
8555 
8556   QualType ExprTy = E->getType();
8557   while (const TypeOfExprType *TET = dyn_cast<TypeOfExprType>(ExprTy)) {
8558     ExprTy = TET->getUnderlyingExpr()->getType();
8559   }
8560 
8561   // Diagnose attempts to print a boolean value as a character. Unlike other
8562   // -Wformat diagnostics, this is fine from a type perspective, but it still
8563   // doesn't make sense.
8564   if (FS.getConversionSpecifier().getKind() == ConversionSpecifier::cArg &&
8565       E->isKnownToHaveBooleanValue()) {
8566     const CharSourceRange &CSR =
8567         getSpecifierRange(StartSpecifier, SpecifierLen);
8568     SmallString<4> FSString;
8569     llvm::raw_svector_ostream os(FSString);
8570     FS.toString(os);
8571     EmitFormatDiagnostic(S.PDiag(diag::warn_format_bool_as_character)
8572                              << FSString,
8573                          E->getExprLoc(), false, CSR);
8574     return true;
8575   }
8576 
8577   analyze_printf::ArgType::MatchKind Match = AT.matchesType(S.Context, ExprTy);
8578   if (Match == analyze_printf::ArgType::Match)
8579     return true;
8580 
8581   // Look through argument promotions for our error message's reported type.
8582   // This includes the integral and floating promotions, but excludes array
8583   // and function pointer decay (seeing that an argument intended to be a
8584   // string has type 'char [6]' is probably more confusing than 'char *') and
8585   // certain bitfield promotions (bitfields can be 'demoted' to a lesser type).
8586   if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
8587     if (isArithmeticArgumentPromotion(S, ICE)) {
8588       E = ICE->getSubExpr();
8589       ExprTy = E->getType();
8590 
8591       // Check if we didn't match because of an implicit cast from a 'char'
8592       // or 'short' to an 'int'.  This is done because printf is a varargs
8593       // function.
8594       if (ICE->getType() == S.Context.IntTy ||
8595           ICE->getType() == S.Context.UnsignedIntTy) {
8596         // All further checking is done on the subexpression
8597         const analyze_printf::ArgType::MatchKind ImplicitMatch =
8598             AT.matchesType(S.Context, ExprTy);
8599         if (ImplicitMatch == analyze_printf::ArgType::Match)
8600           return true;
8601         if (ImplicitMatch == ArgType::NoMatchPedantic ||
8602             ImplicitMatch == ArgType::NoMatchTypeConfusion)
8603           Match = ImplicitMatch;
8604       }
8605     }
8606   } else if (const CharacterLiteral *CL = dyn_cast<CharacterLiteral>(E)) {
8607     // Special case for 'a', which has type 'int' in C.
8608     // Note, however, that we do /not/ want to treat multibyte constants like
8609     // 'MooV' as characters! This form is deprecated but still exists.
8610     if (ExprTy == S.Context.IntTy)
8611       if (llvm::isUIntN(S.Context.getCharWidth(), CL->getValue()))
8612         ExprTy = S.Context.CharTy;
8613   }
8614 
8615   // Look through enums to their underlying type.
8616   bool IsEnum = false;
8617   if (auto EnumTy = ExprTy->getAs<EnumType>()) {
8618     ExprTy = EnumTy->getDecl()->getIntegerType();
8619     IsEnum = true;
8620   }
8621 
8622   // %C in an Objective-C context prints a unichar, not a wchar_t.
8623   // If the argument is an integer of some kind, believe the %C and suggest
8624   // a cast instead of changing the conversion specifier.
8625   QualType IntendedTy = ExprTy;
8626   if (isObjCContext() &&
8627       FS.getConversionSpecifier().getKind() == ConversionSpecifier::CArg) {
8628     if (ExprTy->isIntegralOrUnscopedEnumerationType() &&
8629         !ExprTy->isCharType()) {
8630       // 'unichar' is defined as a typedef of unsigned short, but we should
8631       // prefer using the typedef if it is visible.
8632       IntendedTy = S.Context.UnsignedShortTy;
8633 
8634       // While we are here, check if the value is an IntegerLiteral that happens
8635       // to be within the valid range.
8636       if (const IntegerLiteral *IL = dyn_cast<IntegerLiteral>(E)) {
8637         const llvm::APInt &V = IL->getValue();
8638         if (V.getActiveBits() <= S.Context.getTypeSize(IntendedTy))
8639           return true;
8640       }
8641 
8642       LookupResult Result(S, &S.Context.Idents.get("unichar"), E->getBeginLoc(),
8643                           Sema::LookupOrdinaryName);
8644       if (S.LookupName(Result, S.getCurScope())) {
8645         NamedDecl *ND = Result.getFoundDecl();
8646         if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(ND))
8647           if (TD->getUnderlyingType() == IntendedTy)
8648             IntendedTy = S.Context.getTypedefType(TD);
8649       }
8650     }
8651   }
8652 
8653   // Special-case some of Darwin's platform-independence types by suggesting
8654   // casts to primitive types that are known to be large enough.
8655   bool ShouldNotPrintDirectly = false; StringRef CastTyName;
8656   if (S.Context.getTargetInfo().getTriple().isOSDarwin()) {
8657     QualType CastTy;
8658     std::tie(CastTy, CastTyName) = shouldNotPrintDirectly(S.Context, IntendedTy, E);
8659     if (!CastTy.isNull()) {
8660       // %zi/%zu and %td/%tu are OK to use for NSInteger/NSUInteger of type int
8661       // (long in ASTContext). Only complain to pedants.
8662       if ((CastTyName == "NSInteger" || CastTyName == "NSUInteger") &&
8663           (AT.isSizeT() || AT.isPtrdiffT()) &&
8664           AT.matchesType(S.Context, CastTy))
8665         Match = ArgType::NoMatchPedantic;
8666       IntendedTy = CastTy;
8667       ShouldNotPrintDirectly = true;
8668     }
8669   }
8670 
8671   // We may be able to offer a FixItHint if it is a supported type.
8672   PrintfSpecifier fixedFS = FS;
8673   bool Success =
8674       fixedFS.fixType(IntendedTy, S.getLangOpts(), S.Context, isObjCContext());
8675 
8676   if (Success) {
8677     // Get the fix string from the fixed format specifier
8678     SmallString<16> buf;
8679     llvm::raw_svector_ostream os(buf);
8680     fixedFS.toString(os);
8681 
8682     CharSourceRange SpecRange = getSpecifierRange(StartSpecifier, SpecifierLen);
8683 
8684     if (IntendedTy == ExprTy && !ShouldNotPrintDirectly) {
8685       unsigned Diag;
8686       switch (Match) {
8687       case ArgType::Match: llvm_unreachable("expected non-matching");
8688       case ArgType::NoMatchPedantic:
8689         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8690         break;
8691       case ArgType::NoMatchTypeConfusion:
8692         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8693         break;
8694       case ArgType::NoMatch:
8695         Diag = diag::warn_format_conversion_argument_type_mismatch;
8696         break;
8697       }
8698 
8699       // In this case, the specifier is wrong and should be changed to match
8700       // the argument.
8701       EmitFormatDiagnostic(S.PDiag(Diag)
8702                                << AT.getRepresentativeTypeName(S.Context)
8703                                << IntendedTy << IsEnum << E->getSourceRange(),
8704                            E->getBeginLoc(),
8705                            /*IsStringLocation*/ false, SpecRange,
8706                            FixItHint::CreateReplacement(SpecRange, os.str()));
8707     } else {
8708       // The canonical type for formatting this value is different from the
8709       // actual type of the expression. (This occurs, for example, with Darwin's
8710       // NSInteger on 32-bit platforms, where it is typedef'd as 'int', but
8711       // should be printed as 'long' for 64-bit compatibility.)
8712       // Rather than emitting a normal format/argument mismatch, we want to
8713       // add a cast to the recommended type (and correct the format string
8714       // if necessary).
8715       SmallString<16> CastBuf;
8716       llvm::raw_svector_ostream CastFix(CastBuf);
8717       CastFix << "(";
8718       IntendedTy.print(CastFix, S.Context.getPrintingPolicy());
8719       CastFix << ")";
8720 
8721       SmallVector<FixItHint,4> Hints;
8722       if (!AT.matchesType(S.Context, IntendedTy) || ShouldNotPrintDirectly)
8723         Hints.push_back(FixItHint::CreateReplacement(SpecRange, os.str()));
8724 
8725       if (const CStyleCastExpr *CCast = dyn_cast<CStyleCastExpr>(E)) {
8726         // If there's already a cast present, just replace it.
8727         SourceRange CastRange(CCast->getLParenLoc(), CCast->getRParenLoc());
8728         Hints.push_back(FixItHint::CreateReplacement(CastRange, CastFix.str()));
8729 
8730       } else if (!requiresParensToAddCast(E)) {
8731         // If the expression has high enough precedence,
8732         // just write the C-style cast.
8733         Hints.push_back(
8734             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8735       } else {
8736         // Otherwise, add parens around the expression as well as the cast.
8737         CastFix << "(";
8738         Hints.push_back(
8739             FixItHint::CreateInsertion(E->getBeginLoc(), CastFix.str()));
8740 
8741         SourceLocation After = S.getLocForEndOfToken(E->getEndLoc());
8742         Hints.push_back(FixItHint::CreateInsertion(After, ")"));
8743       }
8744 
8745       if (ShouldNotPrintDirectly) {
8746         // The expression has a type that should not be printed directly.
8747         // We extract the name from the typedef because we don't want to show
8748         // the underlying type in the diagnostic.
8749         StringRef Name;
8750         if (const TypedefType *TypedefTy = dyn_cast<TypedefType>(ExprTy))
8751           Name = TypedefTy->getDecl()->getName();
8752         else
8753           Name = CastTyName;
8754         unsigned Diag = Match == ArgType::NoMatchPedantic
8755                             ? diag::warn_format_argument_needs_cast_pedantic
8756                             : diag::warn_format_argument_needs_cast;
8757         EmitFormatDiagnostic(S.PDiag(Diag) << Name << IntendedTy << IsEnum
8758                                            << E->getSourceRange(),
8759                              E->getBeginLoc(), /*IsStringLocation=*/false,
8760                              SpecRange, Hints);
8761       } else {
8762         // In this case, the expression could be printed using a different
8763         // specifier, but we've decided that the specifier is probably correct
8764         // and we should cast instead. Just use the normal warning message.
8765         EmitFormatDiagnostic(
8766             S.PDiag(diag::warn_format_conversion_argument_type_mismatch)
8767                 << AT.getRepresentativeTypeName(S.Context) << ExprTy << IsEnum
8768                 << E->getSourceRange(),
8769             E->getBeginLoc(), /*IsStringLocation*/ false, SpecRange, Hints);
8770       }
8771     }
8772   } else {
8773     const CharSourceRange &CSR = getSpecifierRange(StartSpecifier,
8774                                                    SpecifierLen);
8775     // Since the warning for passing non-POD types to variadic functions
8776     // was deferred until now, we emit a warning for non-POD
8777     // arguments here.
8778     switch (S.isValidVarArgType(ExprTy)) {
8779     case Sema::VAK_Valid:
8780     case Sema::VAK_ValidInCXX11: {
8781       unsigned Diag;
8782       switch (Match) {
8783       case ArgType::Match: llvm_unreachable("expected non-matching");
8784       case ArgType::NoMatchPedantic:
8785         Diag = diag::warn_format_conversion_argument_type_mismatch_pedantic;
8786         break;
8787       case ArgType::NoMatchTypeConfusion:
8788         Diag = diag::warn_format_conversion_argument_type_mismatch_confusion;
8789         break;
8790       case ArgType::NoMatch:
8791         Diag = diag::warn_format_conversion_argument_type_mismatch;
8792         break;
8793       }
8794 
8795       EmitFormatDiagnostic(
8796           S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context) << ExprTy
8797                         << IsEnum << CSR << E->getSourceRange(),
8798           E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8799       break;
8800     }
8801     case Sema::VAK_Undefined:
8802     case Sema::VAK_MSVCUndefined:
8803       EmitFormatDiagnostic(S.PDiag(diag::warn_non_pod_vararg_with_format_string)
8804                                << S.getLangOpts().CPlusPlus11 << ExprTy
8805                                << CallType
8806                                << AT.getRepresentativeTypeName(S.Context) << CSR
8807                                << E->getSourceRange(),
8808                            E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8809       checkForCStrMembers(AT, E);
8810       break;
8811 
8812     case Sema::VAK_Invalid:
8813       if (ExprTy->isObjCObjectType())
8814         EmitFormatDiagnostic(
8815             S.PDiag(diag::err_cannot_pass_objc_interface_to_vararg_format)
8816                 << S.getLangOpts().CPlusPlus11 << ExprTy << CallType
8817                 << AT.getRepresentativeTypeName(S.Context) << CSR
8818                 << E->getSourceRange(),
8819             E->getBeginLoc(), /*IsStringLocation*/ false, CSR);
8820       else
8821         // FIXME: If this is an initializer list, suggest removing the braces
8822         // or inserting a cast to the target type.
8823         S.Diag(E->getBeginLoc(), diag::err_cannot_pass_to_vararg_format)
8824             << isa<InitListExpr>(E) << ExprTy << CallType
8825             << AT.getRepresentativeTypeName(S.Context) << E->getSourceRange();
8826       break;
8827     }
8828 
8829     assert(FirstDataArg + FS.getArgIndex() < CheckedVarArgs.size() &&
8830            "format string specifier index out of range");
8831     CheckedVarArgs[FirstDataArg + FS.getArgIndex()] = true;
8832   }
8833 
8834   return true;
8835 }
8836 
8837 //===--- CHECK: Scanf format string checking ------------------------------===//
8838 
8839 namespace {
8840 
8841 class CheckScanfHandler : public CheckFormatHandler {
8842 public:
8843   CheckScanfHandler(Sema &s, const FormatStringLiteral *fexpr,
8844                     const Expr *origFormatExpr, Sema::FormatStringType type,
8845                     unsigned firstDataArg, unsigned numDataArgs,
8846                     const char *beg, bool hasVAListArg,
8847                     ArrayRef<const Expr *> Args, unsigned formatIdx,
8848                     bool inFunctionCall, Sema::VariadicCallType CallType,
8849                     llvm::SmallBitVector &CheckedVarArgs,
8850                     UncoveredArgHandler &UncoveredArg)
8851       : CheckFormatHandler(s, fexpr, origFormatExpr, type, firstDataArg,
8852                            numDataArgs, beg, hasVAListArg, Args, formatIdx,
8853                            inFunctionCall, CallType, CheckedVarArgs,
8854                            UncoveredArg) {}
8855 
8856   bool HandleScanfSpecifier(const analyze_scanf::ScanfSpecifier &FS,
8857                             const char *startSpecifier,
8858                             unsigned specifierLen) override;
8859 
8860   bool HandleInvalidScanfConversionSpecifier(
8861           const analyze_scanf::ScanfSpecifier &FS,
8862           const char *startSpecifier,
8863           unsigned specifierLen) override;
8864 
8865   void HandleIncompleteScanList(const char *start, const char *end) override;
8866 };
8867 
8868 } // namespace
8869 
8870 void CheckScanfHandler::HandleIncompleteScanList(const char *start,
8871                                                  const char *end) {
8872   EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_scanlist_incomplete),
8873                        getLocationOfByte(end), /*IsStringLocation*/true,
8874                        getSpecifierRange(start, end - start));
8875 }
8876 
8877 bool CheckScanfHandler::HandleInvalidScanfConversionSpecifier(
8878                                         const analyze_scanf::ScanfSpecifier &FS,
8879                                         const char *startSpecifier,
8880                                         unsigned specifierLen) {
8881   const analyze_scanf::ScanfConversionSpecifier &CS =
8882     FS.getConversionSpecifier();
8883 
8884   return HandleInvalidConversionSpecifier(FS.getArgIndex(),
8885                                           getLocationOfByte(CS.getStart()),
8886                                           startSpecifier, specifierLen,
8887                                           CS.getStart(), CS.getLength());
8888 }
8889 
8890 bool CheckScanfHandler::HandleScanfSpecifier(
8891                                        const analyze_scanf::ScanfSpecifier &FS,
8892                                        const char *startSpecifier,
8893                                        unsigned specifierLen) {
8894   using namespace analyze_scanf;
8895   using namespace analyze_format_string;
8896 
8897   const ScanfConversionSpecifier &CS = FS.getConversionSpecifier();
8898 
8899   // Handle case where '%' and '*' don't consume an argument.  These shouldn't
8900   // be used to decide if we are using positional arguments consistently.
8901   if (FS.consumesDataArgument()) {
8902     if (atFirstArg) {
8903       atFirstArg = false;
8904       usesPositionalArgs = FS.usesPositionalArg();
8905     }
8906     else if (usesPositionalArgs != FS.usesPositionalArg()) {
8907       HandlePositionalNonpositionalArgs(getLocationOfByte(CS.getStart()),
8908                                         startSpecifier, specifierLen);
8909       return false;
8910     }
8911   }
8912 
8913   // Check if the field with is non-zero.
8914   const OptionalAmount &Amt = FS.getFieldWidth();
8915   if (Amt.getHowSpecified() == OptionalAmount::Constant) {
8916     if (Amt.getConstantAmount() == 0) {
8917       const CharSourceRange &R = getSpecifierRange(Amt.getStart(),
8918                                                    Amt.getConstantLength());
8919       EmitFormatDiagnostic(S.PDiag(diag::warn_scanf_nonzero_width),
8920                            getLocationOfByte(Amt.getStart()),
8921                            /*IsStringLocation*/true, R,
8922                            FixItHint::CreateRemoval(R));
8923     }
8924   }
8925 
8926   if (!FS.consumesDataArgument()) {
8927     // FIXME: Technically specifying a precision or field width here
8928     // makes no sense.  Worth issuing a warning at some point.
8929     return true;
8930   }
8931 
8932   // Consume the argument.
8933   unsigned argIndex = FS.getArgIndex();
8934   if (argIndex < NumDataArgs) {
8935       // The check to see if the argIndex is valid will come later.
8936       // We set the bit here because we may exit early from this
8937       // function if we encounter some other error.
8938     CoveredArgs.set(argIndex);
8939   }
8940 
8941   // Check the length modifier is valid with the given conversion specifier.
8942   if (!FS.hasValidLengthModifier(S.getASTContext().getTargetInfo(),
8943                                  S.getLangOpts()))
8944     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8945                                 diag::warn_format_nonsensical_length);
8946   else if (!FS.hasStandardLengthModifier())
8947     HandleNonStandardLengthModifier(FS, startSpecifier, specifierLen);
8948   else if (!FS.hasStandardLengthConversionCombination())
8949     HandleInvalidLengthModifier(FS, CS, startSpecifier, specifierLen,
8950                                 diag::warn_format_non_standard_conversion_spec);
8951 
8952   if (!FS.hasStandardConversionSpecifier(S.getLangOpts()))
8953     HandleNonStandardConversionSpecifier(CS, startSpecifier, specifierLen);
8954 
8955   // The remaining checks depend on the data arguments.
8956   if (HasVAListArg)
8957     return true;
8958 
8959   if (!CheckNumArgs(FS, CS, startSpecifier, specifierLen, argIndex))
8960     return false;
8961 
8962   // Check that the argument type matches the format specifier.
8963   const Expr *Ex = getDataArg(argIndex);
8964   if (!Ex)
8965     return true;
8966 
8967   const analyze_format_string::ArgType &AT = FS.getArgType(S.Context);
8968 
8969   if (!AT.isValid()) {
8970     return true;
8971   }
8972 
8973   analyze_format_string::ArgType::MatchKind Match =
8974       AT.matchesType(S.Context, Ex->getType());
8975   bool Pedantic = Match == analyze_format_string::ArgType::NoMatchPedantic;
8976   if (Match == analyze_format_string::ArgType::Match)
8977     return true;
8978 
8979   ScanfSpecifier fixedFS = FS;
8980   bool Success = fixedFS.fixType(Ex->getType(), Ex->IgnoreImpCasts()->getType(),
8981                                  S.getLangOpts(), S.Context);
8982 
8983   unsigned Diag =
8984       Pedantic ? diag::warn_format_conversion_argument_type_mismatch_pedantic
8985                : diag::warn_format_conversion_argument_type_mismatch;
8986 
8987   if (Success) {
8988     // Get the fix string from the fixed format specifier.
8989     SmallString<128> buf;
8990     llvm::raw_svector_ostream os(buf);
8991     fixedFS.toString(os);
8992 
8993     EmitFormatDiagnostic(
8994         S.PDiag(Diag) << AT.getRepresentativeTypeName(S.Context)
8995                       << Ex->getType() << false << Ex->getSourceRange(),
8996         Ex->getBeginLoc(),
8997         /*IsStringLocation*/ false,
8998         getSpecifierRange(startSpecifier, specifierLen),
8999         FixItHint::CreateReplacement(
9000             getSpecifierRange(startSpecifier, specifierLen), os.str()));
9001   } else {
9002     EmitFormatDiagnostic(S.PDiag(Diag)
9003                              << AT.getRepresentativeTypeName(S.Context)
9004                              << Ex->getType() << false << Ex->getSourceRange(),
9005                          Ex->getBeginLoc(),
9006                          /*IsStringLocation*/ false,
9007                          getSpecifierRange(startSpecifier, specifierLen));
9008   }
9009 
9010   return true;
9011 }
9012 
9013 static void CheckFormatString(Sema &S, const FormatStringLiteral *FExpr,
9014                               const Expr *OrigFormatExpr,
9015                               ArrayRef<const Expr *> Args,
9016                               bool HasVAListArg, unsigned format_idx,
9017                               unsigned firstDataArg,
9018                               Sema::FormatStringType Type,
9019                               bool inFunctionCall,
9020                               Sema::VariadicCallType CallType,
9021                               llvm::SmallBitVector &CheckedVarArgs,
9022                               UncoveredArgHandler &UncoveredArg,
9023                               bool IgnoreStringsWithoutSpecifiers) {
9024   // CHECK: is the format string a wide literal?
9025   if (!FExpr->isAscii() && !FExpr->isUTF8()) {
9026     CheckFormatHandler::EmitFormatDiagnostic(
9027         S, inFunctionCall, Args[format_idx],
9028         S.PDiag(diag::warn_format_string_is_wide_literal), FExpr->getBeginLoc(),
9029         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9030     return;
9031   }
9032 
9033   // Str - The format string.  NOTE: this is NOT null-terminated!
9034   StringRef StrRef = FExpr->getString();
9035   const char *Str = StrRef.data();
9036   // Account for cases where the string literal is truncated in a declaration.
9037   const ConstantArrayType *T =
9038     S.Context.getAsConstantArrayType(FExpr->getType());
9039   assert(T && "String literal not of constant array type!");
9040   size_t TypeSize = T->getSize().getZExtValue();
9041   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9042   const unsigned numDataArgs = Args.size() - firstDataArg;
9043 
9044   if (IgnoreStringsWithoutSpecifiers &&
9045       !analyze_format_string::parseFormatStringHasFormattingSpecifiers(
9046           Str, Str + StrLen, S.getLangOpts(), S.Context.getTargetInfo()))
9047     return;
9048 
9049   // Emit a warning if the string literal is truncated and does not contain an
9050   // embedded null character.
9051   if (TypeSize <= StrRef.size() &&
9052       StrRef.substr(0, TypeSize).find('\0') == StringRef::npos) {
9053     CheckFormatHandler::EmitFormatDiagnostic(
9054         S, inFunctionCall, Args[format_idx],
9055         S.PDiag(diag::warn_printf_format_string_not_null_terminated),
9056         FExpr->getBeginLoc(),
9057         /*IsStringLocation=*/true, OrigFormatExpr->getSourceRange());
9058     return;
9059   }
9060 
9061   // CHECK: empty format string?
9062   if (StrLen == 0 && numDataArgs > 0) {
9063     CheckFormatHandler::EmitFormatDiagnostic(
9064         S, inFunctionCall, Args[format_idx],
9065         S.PDiag(diag::warn_empty_format_string), FExpr->getBeginLoc(),
9066         /*IsStringLocation*/ true, OrigFormatExpr->getSourceRange());
9067     return;
9068   }
9069 
9070   if (Type == Sema::FST_Printf || Type == Sema::FST_NSString ||
9071       Type == Sema::FST_FreeBSDKPrintf || Type == Sema::FST_OSLog ||
9072       Type == Sema::FST_OSTrace) {
9073     CheckPrintfHandler H(
9074         S, FExpr, OrigFormatExpr, Type, firstDataArg, numDataArgs,
9075         (Type == Sema::FST_NSString || Type == Sema::FST_OSTrace), Str,
9076         HasVAListArg, Args, format_idx, inFunctionCall, CallType,
9077         CheckedVarArgs, UncoveredArg);
9078 
9079     if (!analyze_format_string::ParsePrintfString(H, Str, Str + StrLen,
9080                                                   S.getLangOpts(),
9081                                                   S.Context.getTargetInfo(),
9082                                             Type == Sema::FST_FreeBSDKPrintf))
9083       H.DoneProcessing();
9084   } else if (Type == Sema::FST_Scanf) {
9085     CheckScanfHandler H(S, FExpr, OrigFormatExpr, Type, firstDataArg,
9086                         numDataArgs, Str, HasVAListArg, Args, format_idx,
9087                         inFunctionCall, CallType, CheckedVarArgs, UncoveredArg);
9088 
9089     if (!analyze_format_string::ParseScanfString(H, Str, Str + StrLen,
9090                                                  S.getLangOpts(),
9091                                                  S.Context.getTargetInfo()))
9092       H.DoneProcessing();
9093   } // TODO: handle other formats
9094 }
9095 
9096 bool Sema::FormatStringHasSArg(const StringLiteral *FExpr) {
9097   // Str - The format string.  NOTE: this is NOT null-terminated!
9098   StringRef StrRef = FExpr->getString();
9099   const char *Str = StrRef.data();
9100   // Account for cases where the string literal is truncated in a declaration.
9101   const ConstantArrayType *T = Context.getAsConstantArrayType(FExpr->getType());
9102   assert(T && "String literal not of constant array type!");
9103   size_t TypeSize = T->getSize().getZExtValue();
9104   size_t StrLen = std::min(std::max(TypeSize, size_t(1)) - 1, StrRef.size());
9105   return analyze_format_string::ParseFormatStringHasSArg(Str, Str + StrLen,
9106                                                          getLangOpts(),
9107                                                          Context.getTargetInfo());
9108 }
9109 
9110 //===--- CHECK: Warn on use of wrong absolute value function. -------------===//
9111 
9112 // Returns the related absolute value function that is larger, of 0 if one
9113 // does not exist.
9114 static unsigned getLargerAbsoluteValueFunction(unsigned AbsFunction) {
9115   switch (AbsFunction) {
9116   default:
9117     return 0;
9118 
9119   case Builtin::BI__builtin_abs:
9120     return Builtin::BI__builtin_labs;
9121   case Builtin::BI__builtin_labs:
9122     return Builtin::BI__builtin_llabs;
9123   case Builtin::BI__builtin_llabs:
9124     return 0;
9125 
9126   case Builtin::BI__builtin_fabsf:
9127     return Builtin::BI__builtin_fabs;
9128   case Builtin::BI__builtin_fabs:
9129     return Builtin::BI__builtin_fabsl;
9130   case Builtin::BI__builtin_fabsl:
9131     return 0;
9132 
9133   case Builtin::BI__builtin_cabsf:
9134     return Builtin::BI__builtin_cabs;
9135   case Builtin::BI__builtin_cabs:
9136     return Builtin::BI__builtin_cabsl;
9137   case Builtin::BI__builtin_cabsl:
9138     return 0;
9139 
9140   case Builtin::BIabs:
9141     return Builtin::BIlabs;
9142   case Builtin::BIlabs:
9143     return Builtin::BIllabs;
9144   case Builtin::BIllabs:
9145     return 0;
9146 
9147   case Builtin::BIfabsf:
9148     return Builtin::BIfabs;
9149   case Builtin::BIfabs:
9150     return Builtin::BIfabsl;
9151   case Builtin::BIfabsl:
9152     return 0;
9153 
9154   case Builtin::BIcabsf:
9155    return Builtin::BIcabs;
9156   case Builtin::BIcabs:
9157     return Builtin::BIcabsl;
9158   case Builtin::BIcabsl:
9159     return 0;
9160   }
9161 }
9162 
9163 // Returns the argument type of the absolute value function.
9164 static QualType getAbsoluteValueArgumentType(ASTContext &Context,
9165                                              unsigned AbsType) {
9166   if (AbsType == 0)
9167     return QualType();
9168 
9169   ASTContext::GetBuiltinTypeError Error = ASTContext::GE_None;
9170   QualType BuiltinType = Context.GetBuiltinType(AbsType, Error);
9171   if (Error != ASTContext::GE_None)
9172     return QualType();
9173 
9174   const FunctionProtoType *FT = BuiltinType->getAs<FunctionProtoType>();
9175   if (!FT)
9176     return QualType();
9177 
9178   if (FT->getNumParams() != 1)
9179     return QualType();
9180 
9181   return FT->getParamType(0);
9182 }
9183 
9184 // Returns the best absolute value function, or zero, based on type and
9185 // current absolute value function.
9186 static unsigned getBestAbsFunction(ASTContext &Context, QualType ArgType,
9187                                    unsigned AbsFunctionKind) {
9188   unsigned BestKind = 0;
9189   uint64_t ArgSize = Context.getTypeSize(ArgType);
9190   for (unsigned Kind = AbsFunctionKind; Kind != 0;
9191        Kind = getLargerAbsoluteValueFunction(Kind)) {
9192     QualType ParamType = getAbsoluteValueArgumentType(Context, Kind);
9193     if (Context.getTypeSize(ParamType) >= ArgSize) {
9194       if (BestKind == 0)
9195         BestKind = Kind;
9196       else if (Context.hasSameType(ParamType, ArgType)) {
9197         BestKind = Kind;
9198         break;
9199       }
9200     }
9201   }
9202   return BestKind;
9203 }
9204 
9205 enum AbsoluteValueKind {
9206   AVK_Integer,
9207   AVK_Floating,
9208   AVK_Complex
9209 };
9210 
9211 static AbsoluteValueKind getAbsoluteValueKind(QualType T) {
9212   if (T->isIntegralOrEnumerationType())
9213     return AVK_Integer;
9214   if (T->isRealFloatingType())
9215     return AVK_Floating;
9216   if (T->isAnyComplexType())
9217     return AVK_Complex;
9218 
9219   llvm_unreachable("Type not integer, floating, or complex");
9220 }
9221 
9222 // Changes the absolute value function to a different type.  Preserves whether
9223 // the function is a builtin.
9224 static unsigned changeAbsFunction(unsigned AbsKind,
9225                                   AbsoluteValueKind ValueKind) {
9226   switch (ValueKind) {
9227   case AVK_Integer:
9228     switch (AbsKind) {
9229     default:
9230       return 0;
9231     case Builtin::BI__builtin_fabsf:
9232     case Builtin::BI__builtin_fabs:
9233     case Builtin::BI__builtin_fabsl:
9234     case Builtin::BI__builtin_cabsf:
9235     case Builtin::BI__builtin_cabs:
9236     case Builtin::BI__builtin_cabsl:
9237       return Builtin::BI__builtin_abs;
9238     case Builtin::BIfabsf:
9239     case Builtin::BIfabs:
9240     case Builtin::BIfabsl:
9241     case Builtin::BIcabsf:
9242     case Builtin::BIcabs:
9243     case Builtin::BIcabsl:
9244       return Builtin::BIabs;
9245     }
9246   case AVK_Floating:
9247     switch (AbsKind) {
9248     default:
9249       return 0;
9250     case Builtin::BI__builtin_abs:
9251     case Builtin::BI__builtin_labs:
9252     case Builtin::BI__builtin_llabs:
9253     case Builtin::BI__builtin_cabsf:
9254     case Builtin::BI__builtin_cabs:
9255     case Builtin::BI__builtin_cabsl:
9256       return Builtin::BI__builtin_fabsf;
9257     case Builtin::BIabs:
9258     case Builtin::BIlabs:
9259     case Builtin::BIllabs:
9260     case Builtin::BIcabsf:
9261     case Builtin::BIcabs:
9262     case Builtin::BIcabsl:
9263       return Builtin::BIfabsf;
9264     }
9265   case AVK_Complex:
9266     switch (AbsKind) {
9267     default:
9268       return 0;
9269     case Builtin::BI__builtin_abs:
9270     case Builtin::BI__builtin_labs:
9271     case Builtin::BI__builtin_llabs:
9272     case Builtin::BI__builtin_fabsf:
9273     case Builtin::BI__builtin_fabs:
9274     case Builtin::BI__builtin_fabsl:
9275       return Builtin::BI__builtin_cabsf;
9276     case Builtin::BIabs:
9277     case Builtin::BIlabs:
9278     case Builtin::BIllabs:
9279     case Builtin::BIfabsf:
9280     case Builtin::BIfabs:
9281     case Builtin::BIfabsl:
9282       return Builtin::BIcabsf;
9283     }
9284   }
9285   llvm_unreachable("Unable to convert function");
9286 }
9287 
9288 static unsigned getAbsoluteValueFunctionKind(const FunctionDecl *FDecl) {
9289   const IdentifierInfo *FnInfo = FDecl->getIdentifier();
9290   if (!FnInfo)
9291     return 0;
9292 
9293   switch (FDecl->getBuiltinID()) {
9294   default:
9295     return 0;
9296   case Builtin::BI__builtin_abs:
9297   case Builtin::BI__builtin_fabs:
9298   case Builtin::BI__builtin_fabsf:
9299   case Builtin::BI__builtin_fabsl:
9300   case Builtin::BI__builtin_labs:
9301   case Builtin::BI__builtin_llabs:
9302   case Builtin::BI__builtin_cabs:
9303   case Builtin::BI__builtin_cabsf:
9304   case Builtin::BI__builtin_cabsl:
9305   case Builtin::BIabs:
9306   case Builtin::BIlabs:
9307   case Builtin::BIllabs:
9308   case Builtin::BIfabs:
9309   case Builtin::BIfabsf:
9310   case Builtin::BIfabsl:
9311   case Builtin::BIcabs:
9312   case Builtin::BIcabsf:
9313   case Builtin::BIcabsl:
9314     return FDecl->getBuiltinID();
9315   }
9316   llvm_unreachable("Unknown Builtin type");
9317 }
9318 
9319 // If the replacement is valid, emit a note with replacement function.
9320 // Additionally, suggest including the proper header if not already included.
9321 static void emitReplacement(Sema &S, SourceLocation Loc, SourceRange Range,
9322                             unsigned AbsKind, QualType ArgType) {
9323   bool EmitHeaderHint = true;
9324   const char *HeaderName = nullptr;
9325   const char *FunctionName = nullptr;
9326   if (S.getLangOpts().CPlusPlus && !ArgType->isAnyComplexType()) {
9327     FunctionName = "std::abs";
9328     if (ArgType->isIntegralOrEnumerationType()) {
9329       HeaderName = "cstdlib";
9330     } else if (ArgType->isRealFloatingType()) {
9331       HeaderName = "cmath";
9332     } else {
9333       llvm_unreachable("Invalid Type");
9334     }
9335 
9336     // Lookup all std::abs
9337     if (NamespaceDecl *Std = S.getStdNamespace()) {
9338       LookupResult R(S, &S.Context.Idents.get("abs"), Loc, Sema::LookupAnyName);
9339       R.suppressDiagnostics();
9340       S.LookupQualifiedName(R, Std);
9341 
9342       for (const auto *I : R) {
9343         const FunctionDecl *FDecl = nullptr;
9344         if (const UsingShadowDecl *UsingD = dyn_cast<UsingShadowDecl>(I)) {
9345           FDecl = dyn_cast<FunctionDecl>(UsingD->getTargetDecl());
9346         } else {
9347           FDecl = dyn_cast<FunctionDecl>(I);
9348         }
9349         if (!FDecl)
9350           continue;
9351 
9352         // Found std::abs(), check that they are the right ones.
9353         if (FDecl->getNumParams() != 1)
9354           continue;
9355 
9356         // Check that the parameter type can handle the argument.
9357         QualType ParamType = FDecl->getParamDecl(0)->getType();
9358         if (getAbsoluteValueKind(ArgType) == getAbsoluteValueKind(ParamType) &&
9359             S.Context.getTypeSize(ArgType) <=
9360                 S.Context.getTypeSize(ParamType)) {
9361           // Found a function, don't need the header hint.
9362           EmitHeaderHint = false;
9363           break;
9364         }
9365       }
9366     }
9367   } else {
9368     FunctionName = S.Context.BuiltinInfo.getName(AbsKind);
9369     HeaderName = S.Context.BuiltinInfo.getHeaderName(AbsKind);
9370 
9371     if (HeaderName) {
9372       DeclarationName DN(&S.Context.Idents.get(FunctionName));
9373       LookupResult R(S, DN, Loc, Sema::LookupAnyName);
9374       R.suppressDiagnostics();
9375       S.LookupName(R, S.getCurScope());
9376 
9377       if (R.isSingleResult()) {
9378         FunctionDecl *FD = dyn_cast<FunctionDecl>(R.getFoundDecl());
9379         if (FD && FD->getBuiltinID() == AbsKind) {
9380           EmitHeaderHint = false;
9381         } else {
9382           return;
9383         }
9384       } else if (!R.empty()) {
9385         return;
9386       }
9387     }
9388   }
9389 
9390   S.Diag(Loc, diag::note_replace_abs_function)
9391       << FunctionName << FixItHint::CreateReplacement(Range, FunctionName);
9392 
9393   if (!HeaderName)
9394     return;
9395 
9396   if (!EmitHeaderHint)
9397     return;
9398 
9399   S.Diag(Loc, diag::note_include_header_or_declare) << HeaderName
9400                                                     << FunctionName;
9401 }
9402 
9403 template <std::size_t StrLen>
9404 static bool IsStdFunction(const FunctionDecl *FDecl,
9405                           const char (&Str)[StrLen]) {
9406   if (!FDecl)
9407     return false;
9408   if (!FDecl->getIdentifier() || !FDecl->getIdentifier()->isStr(Str))
9409     return false;
9410   if (!FDecl->isInStdNamespace())
9411     return false;
9412 
9413   return true;
9414 }
9415 
9416 // Warn when using the wrong abs() function.
9417 void Sema::CheckAbsoluteValueFunction(const CallExpr *Call,
9418                                       const FunctionDecl *FDecl) {
9419   if (Call->getNumArgs() != 1)
9420     return;
9421 
9422   unsigned AbsKind = getAbsoluteValueFunctionKind(FDecl);
9423   bool IsStdAbs = IsStdFunction(FDecl, "abs");
9424   if (AbsKind == 0 && !IsStdAbs)
9425     return;
9426 
9427   QualType ArgType = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9428   QualType ParamType = Call->getArg(0)->getType();
9429 
9430   // Unsigned types cannot be negative.  Suggest removing the absolute value
9431   // function call.
9432   if (ArgType->isUnsignedIntegerType()) {
9433     const char *FunctionName =
9434         IsStdAbs ? "std::abs" : Context.BuiltinInfo.getName(AbsKind);
9435     Diag(Call->getExprLoc(), diag::warn_unsigned_abs) << ArgType << ParamType;
9436     Diag(Call->getExprLoc(), diag::note_remove_abs)
9437         << FunctionName
9438         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange());
9439     return;
9440   }
9441 
9442   // Taking the absolute value of a pointer is very suspicious, they probably
9443   // wanted to index into an array, dereference a pointer, call a function, etc.
9444   if (ArgType->isPointerType() || ArgType->canDecayToPointerType()) {
9445     unsigned DiagType = 0;
9446     if (ArgType->isFunctionType())
9447       DiagType = 1;
9448     else if (ArgType->isArrayType())
9449       DiagType = 2;
9450 
9451     Diag(Call->getExprLoc(), diag::warn_pointer_abs) << DiagType << ArgType;
9452     return;
9453   }
9454 
9455   // std::abs has overloads which prevent most of the absolute value problems
9456   // from occurring.
9457   if (IsStdAbs)
9458     return;
9459 
9460   AbsoluteValueKind ArgValueKind = getAbsoluteValueKind(ArgType);
9461   AbsoluteValueKind ParamValueKind = getAbsoluteValueKind(ParamType);
9462 
9463   // The argument and parameter are the same kind.  Check if they are the right
9464   // size.
9465   if (ArgValueKind == ParamValueKind) {
9466     if (Context.getTypeSize(ArgType) <= Context.getTypeSize(ParamType))
9467       return;
9468 
9469     unsigned NewAbsKind = getBestAbsFunction(Context, ArgType, AbsKind);
9470     Diag(Call->getExprLoc(), diag::warn_abs_too_small)
9471         << FDecl << ArgType << ParamType;
9472 
9473     if (NewAbsKind == 0)
9474       return;
9475 
9476     emitReplacement(*this, Call->getExprLoc(),
9477                     Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9478     return;
9479   }
9480 
9481   // ArgValueKind != ParamValueKind
9482   // The wrong type of absolute value function was used.  Attempt to find the
9483   // proper one.
9484   unsigned NewAbsKind = changeAbsFunction(AbsKind, ArgValueKind);
9485   NewAbsKind = getBestAbsFunction(Context, ArgType, NewAbsKind);
9486   if (NewAbsKind == 0)
9487     return;
9488 
9489   Diag(Call->getExprLoc(), diag::warn_wrong_absolute_value_type)
9490       << FDecl << ParamValueKind << ArgValueKind;
9491 
9492   emitReplacement(*this, Call->getExprLoc(),
9493                   Call->getCallee()->getSourceRange(), NewAbsKind, ArgType);
9494 }
9495 
9496 //===--- CHECK: Warn on use of std::max and unsigned zero. r---------------===//
9497 void Sema::CheckMaxUnsignedZero(const CallExpr *Call,
9498                                 const FunctionDecl *FDecl) {
9499   if (!Call || !FDecl) return;
9500 
9501   // Ignore template specializations and macros.
9502   if (inTemplateInstantiation()) return;
9503   if (Call->getExprLoc().isMacroID()) return;
9504 
9505   // Only care about the one template argument, two function parameter std::max
9506   if (Call->getNumArgs() != 2) return;
9507   if (!IsStdFunction(FDecl, "max")) return;
9508   const auto * ArgList = FDecl->getTemplateSpecializationArgs();
9509   if (!ArgList) return;
9510   if (ArgList->size() != 1) return;
9511 
9512   // Check that template type argument is unsigned integer.
9513   const auto& TA = ArgList->get(0);
9514   if (TA.getKind() != TemplateArgument::Type) return;
9515   QualType ArgType = TA.getAsType();
9516   if (!ArgType->isUnsignedIntegerType()) return;
9517 
9518   // See if either argument is a literal zero.
9519   auto IsLiteralZeroArg = [](const Expr* E) -> bool {
9520     const auto *MTE = dyn_cast<MaterializeTemporaryExpr>(E);
9521     if (!MTE) return false;
9522     const auto *Num = dyn_cast<IntegerLiteral>(MTE->getSubExpr());
9523     if (!Num) return false;
9524     if (Num->getValue() != 0) return false;
9525     return true;
9526   };
9527 
9528   const Expr *FirstArg = Call->getArg(0);
9529   const Expr *SecondArg = Call->getArg(1);
9530   const bool IsFirstArgZero = IsLiteralZeroArg(FirstArg);
9531   const bool IsSecondArgZero = IsLiteralZeroArg(SecondArg);
9532 
9533   // Only warn when exactly one argument is zero.
9534   if (IsFirstArgZero == IsSecondArgZero) return;
9535 
9536   SourceRange FirstRange = FirstArg->getSourceRange();
9537   SourceRange SecondRange = SecondArg->getSourceRange();
9538 
9539   SourceRange ZeroRange = IsFirstArgZero ? FirstRange : SecondRange;
9540 
9541   Diag(Call->getExprLoc(), diag::warn_max_unsigned_zero)
9542       << IsFirstArgZero << Call->getCallee()->getSourceRange() << ZeroRange;
9543 
9544   // Deduce what parts to remove so that "std::max(0u, foo)" becomes "(foo)".
9545   SourceRange RemovalRange;
9546   if (IsFirstArgZero) {
9547     RemovalRange = SourceRange(FirstRange.getBegin(),
9548                                SecondRange.getBegin().getLocWithOffset(-1));
9549   } else {
9550     RemovalRange = SourceRange(getLocForEndOfToken(FirstRange.getEnd()),
9551                                SecondRange.getEnd());
9552   }
9553 
9554   Diag(Call->getExprLoc(), diag::note_remove_max_call)
9555         << FixItHint::CreateRemoval(Call->getCallee()->getSourceRange())
9556         << FixItHint::CreateRemoval(RemovalRange);
9557 }
9558 
9559 //===--- CHECK: Standard memory functions ---------------------------------===//
9560 
9561 /// Takes the expression passed to the size_t parameter of functions
9562 /// such as memcmp, strncat, etc and warns if it's a comparison.
9563 ///
9564 /// This is to catch typos like `if (memcmp(&a, &b, sizeof(a) > 0))`.
9565 static bool CheckMemorySizeofForComparison(Sema &S, const Expr *E,
9566                                            IdentifierInfo *FnName,
9567                                            SourceLocation FnLoc,
9568                                            SourceLocation RParenLoc) {
9569   const BinaryOperator *Size = dyn_cast<BinaryOperator>(E);
9570   if (!Size)
9571     return false;
9572 
9573   // if E is binop and op is <=>, >, <, >=, <=, ==, &&, ||:
9574   if (!Size->isComparisonOp() && !Size->isLogicalOp())
9575     return false;
9576 
9577   SourceRange SizeRange = Size->getSourceRange();
9578   S.Diag(Size->getOperatorLoc(), diag::warn_memsize_comparison)
9579       << SizeRange << FnName;
9580   S.Diag(FnLoc, diag::note_memsize_comparison_paren)
9581       << FnName
9582       << FixItHint::CreateInsertion(
9583              S.getLocForEndOfToken(Size->getLHS()->getEndLoc()), ")")
9584       << FixItHint::CreateRemoval(RParenLoc);
9585   S.Diag(SizeRange.getBegin(), diag::note_memsize_comparison_cast_silence)
9586       << FixItHint::CreateInsertion(SizeRange.getBegin(), "(size_t)(")
9587       << FixItHint::CreateInsertion(S.getLocForEndOfToken(SizeRange.getEnd()),
9588                                     ")");
9589 
9590   return true;
9591 }
9592 
9593 /// Determine whether the given type is or contains a dynamic class type
9594 /// (e.g., whether it has a vtable).
9595 static const CXXRecordDecl *getContainedDynamicClass(QualType T,
9596                                                      bool &IsContained) {
9597   // Look through array types while ignoring qualifiers.
9598   const Type *Ty = T->getBaseElementTypeUnsafe();
9599   IsContained = false;
9600 
9601   const CXXRecordDecl *RD = Ty->getAsCXXRecordDecl();
9602   RD = RD ? RD->getDefinition() : nullptr;
9603   if (!RD || RD->isInvalidDecl())
9604     return nullptr;
9605 
9606   if (RD->isDynamicClass())
9607     return RD;
9608 
9609   // Check all the fields.  If any bases were dynamic, the class is dynamic.
9610   // It's impossible for a class to transitively contain itself by value, so
9611   // infinite recursion is impossible.
9612   for (auto *FD : RD->fields()) {
9613     bool SubContained;
9614     if (const CXXRecordDecl *ContainedRD =
9615             getContainedDynamicClass(FD->getType(), SubContained)) {
9616       IsContained = true;
9617       return ContainedRD;
9618     }
9619   }
9620 
9621   return nullptr;
9622 }
9623 
9624 static const UnaryExprOrTypeTraitExpr *getAsSizeOfExpr(const Expr *E) {
9625   if (const auto *Unary = dyn_cast<UnaryExprOrTypeTraitExpr>(E))
9626     if (Unary->getKind() == UETT_SizeOf)
9627       return Unary;
9628   return nullptr;
9629 }
9630 
9631 /// If E is a sizeof expression, returns its argument expression,
9632 /// otherwise returns NULL.
9633 static const Expr *getSizeOfExprArg(const Expr *E) {
9634   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9635     if (!SizeOf->isArgumentType())
9636       return SizeOf->getArgumentExpr()->IgnoreParenImpCasts();
9637   return nullptr;
9638 }
9639 
9640 /// If E is a sizeof expression, returns its argument type.
9641 static QualType getSizeOfArgType(const Expr *E) {
9642   if (const UnaryExprOrTypeTraitExpr *SizeOf = getAsSizeOfExpr(E))
9643     return SizeOf->getTypeOfArgument();
9644   return QualType();
9645 }
9646 
9647 namespace {
9648 
9649 struct SearchNonTrivialToInitializeField
9650     : DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField> {
9651   using Super =
9652       DefaultInitializedTypeVisitor<SearchNonTrivialToInitializeField>;
9653 
9654   SearchNonTrivialToInitializeField(const Expr *E, Sema &S) : E(E), S(S) {}
9655 
9656   void visitWithKind(QualType::PrimitiveDefaultInitializeKind PDIK, QualType FT,
9657                      SourceLocation SL) {
9658     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9659       asDerived().visitArray(PDIK, AT, SL);
9660       return;
9661     }
9662 
9663     Super::visitWithKind(PDIK, FT, SL);
9664   }
9665 
9666   void visitARCStrong(QualType FT, SourceLocation SL) {
9667     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9668   }
9669   void visitARCWeak(QualType FT, SourceLocation SL) {
9670     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 1);
9671   }
9672   void visitStruct(QualType FT, SourceLocation SL) {
9673     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9674       visit(FD->getType(), FD->getLocation());
9675   }
9676   void visitArray(QualType::PrimitiveDefaultInitializeKind PDIK,
9677                   const ArrayType *AT, SourceLocation SL) {
9678     visit(getContext().getBaseElementType(AT), SL);
9679   }
9680   void visitTrivial(QualType FT, SourceLocation SL) {}
9681 
9682   static void diag(QualType RT, const Expr *E, Sema &S) {
9683     SearchNonTrivialToInitializeField(E, S).visitStruct(RT, SourceLocation());
9684   }
9685 
9686   ASTContext &getContext() { return S.getASTContext(); }
9687 
9688   const Expr *E;
9689   Sema &S;
9690 };
9691 
9692 struct SearchNonTrivialToCopyField
9693     : CopiedTypeVisitor<SearchNonTrivialToCopyField, false> {
9694   using Super = CopiedTypeVisitor<SearchNonTrivialToCopyField, false>;
9695 
9696   SearchNonTrivialToCopyField(const Expr *E, Sema &S) : E(E), S(S) {}
9697 
9698   void visitWithKind(QualType::PrimitiveCopyKind PCK, QualType FT,
9699                      SourceLocation SL) {
9700     if (const auto *AT = asDerived().getContext().getAsArrayType(FT)) {
9701       asDerived().visitArray(PCK, AT, SL);
9702       return;
9703     }
9704 
9705     Super::visitWithKind(PCK, FT, SL);
9706   }
9707 
9708   void visitARCStrong(QualType FT, SourceLocation SL) {
9709     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9710   }
9711   void visitARCWeak(QualType FT, SourceLocation SL) {
9712     S.DiagRuntimeBehavior(SL, E, S.PDiag(diag::note_nontrivial_field) << 0);
9713   }
9714   void visitStruct(QualType FT, SourceLocation SL) {
9715     for (const FieldDecl *FD : FT->castAs<RecordType>()->getDecl()->fields())
9716       visit(FD->getType(), FD->getLocation());
9717   }
9718   void visitArray(QualType::PrimitiveCopyKind PCK, const ArrayType *AT,
9719                   SourceLocation SL) {
9720     visit(getContext().getBaseElementType(AT), SL);
9721   }
9722   void preVisit(QualType::PrimitiveCopyKind PCK, QualType FT,
9723                 SourceLocation SL) {}
9724   void visitTrivial(QualType FT, SourceLocation SL) {}
9725   void visitVolatileTrivial(QualType FT, SourceLocation SL) {}
9726 
9727   static void diag(QualType RT, const Expr *E, Sema &S) {
9728     SearchNonTrivialToCopyField(E, S).visitStruct(RT, SourceLocation());
9729   }
9730 
9731   ASTContext &getContext() { return S.getASTContext(); }
9732 
9733   const Expr *E;
9734   Sema &S;
9735 };
9736 
9737 }
9738 
9739 /// Detect if \c SizeofExpr is likely to calculate the sizeof an object.
9740 static bool doesExprLikelyComputeSize(const Expr *SizeofExpr) {
9741   SizeofExpr = SizeofExpr->IgnoreParenImpCasts();
9742 
9743   if (const auto *BO = dyn_cast<BinaryOperator>(SizeofExpr)) {
9744     if (BO->getOpcode() != BO_Mul && BO->getOpcode() != BO_Add)
9745       return false;
9746 
9747     return doesExprLikelyComputeSize(BO->getLHS()) ||
9748            doesExprLikelyComputeSize(BO->getRHS());
9749   }
9750 
9751   return getAsSizeOfExpr(SizeofExpr) != nullptr;
9752 }
9753 
9754 /// Check if the ArgLoc originated from a macro passed to the call at CallLoc.
9755 ///
9756 /// \code
9757 ///   #define MACRO 0
9758 ///   foo(MACRO);
9759 ///   foo(0);
9760 /// \endcode
9761 ///
9762 /// This should return true for the first call to foo, but not for the second
9763 /// (regardless of whether foo is a macro or function).
9764 static bool isArgumentExpandedFromMacro(SourceManager &SM,
9765                                         SourceLocation CallLoc,
9766                                         SourceLocation ArgLoc) {
9767   if (!CallLoc.isMacroID())
9768     return SM.getFileID(CallLoc) != SM.getFileID(ArgLoc);
9769 
9770   return SM.getFileID(SM.getImmediateMacroCallerLoc(CallLoc)) !=
9771          SM.getFileID(SM.getImmediateMacroCallerLoc(ArgLoc));
9772 }
9773 
9774 /// Diagnose cases like 'memset(buf, sizeof(buf), 0)', which should have the
9775 /// last two arguments transposed.
9776 static void CheckMemaccessSize(Sema &S, unsigned BId, const CallExpr *Call) {
9777   if (BId != Builtin::BImemset && BId != Builtin::BIbzero)
9778     return;
9779 
9780   const Expr *SizeArg =
9781     Call->getArg(BId == Builtin::BImemset ? 2 : 1)->IgnoreImpCasts();
9782 
9783   auto isLiteralZero = [](const Expr *E) {
9784     return isa<IntegerLiteral>(E) && cast<IntegerLiteral>(E)->getValue() == 0;
9785   };
9786 
9787   // If we're memsetting or bzeroing 0 bytes, then this is likely an error.
9788   SourceLocation CallLoc = Call->getRParenLoc();
9789   SourceManager &SM = S.getSourceManager();
9790   if (isLiteralZero(SizeArg) &&
9791       !isArgumentExpandedFromMacro(SM, CallLoc, SizeArg->getExprLoc())) {
9792 
9793     SourceLocation DiagLoc = SizeArg->getExprLoc();
9794 
9795     // Some platforms #define bzero to __builtin_memset. See if this is the
9796     // case, and if so, emit a better diagnostic.
9797     if (BId == Builtin::BIbzero ||
9798         (CallLoc.isMacroID() && Lexer::getImmediateMacroName(
9799                                     CallLoc, SM, S.getLangOpts()) == "bzero")) {
9800       S.Diag(DiagLoc, diag::warn_suspicious_bzero_size);
9801       S.Diag(DiagLoc, diag::note_suspicious_bzero_size_silence);
9802     } else if (!isLiteralZero(Call->getArg(1)->IgnoreImpCasts())) {
9803       S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 0;
9804       S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 0;
9805     }
9806     return;
9807   }
9808 
9809   // If the second argument to a memset is a sizeof expression and the third
9810   // isn't, this is also likely an error. This should catch
9811   // 'memset(buf, sizeof(buf), 0xff)'.
9812   if (BId == Builtin::BImemset &&
9813       doesExprLikelyComputeSize(Call->getArg(1)) &&
9814       !doesExprLikelyComputeSize(Call->getArg(2))) {
9815     SourceLocation DiagLoc = Call->getArg(1)->getExprLoc();
9816     S.Diag(DiagLoc, diag::warn_suspicious_sizeof_memset) << 1;
9817     S.Diag(DiagLoc, diag::note_suspicious_sizeof_memset_silence) << 1;
9818     return;
9819   }
9820 }
9821 
9822 /// Check for dangerous or invalid arguments to memset().
9823 ///
9824 /// This issues warnings on known problematic, dangerous or unspecified
9825 /// arguments to the standard 'memset', 'memcpy', 'memmove', and 'memcmp'
9826 /// function calls.
9827 ///
9828 /// \param Call The call expression to diagnose.
9829 void Sema::CheckMemaccessArguments(const CallExpr *Call,
9830                                    unsigned BId,
9831                                    IdentifierInfo *FnName) {
9832   assert(BId != 0);
9833 
9834   // It is possible to have a non-standard definition of memset.  Validate
9835   // we have enough arguments, and if not, abort further checking.
9836   unsigned ExpectedNumArgs =
9837       (BId == Builtin::BIstrndup || BId == Builtin::BIbzero ? 2 : 3);
9838   if (Call->getNumArgs() < ExpectedNumArgs)
9839     return;
9840 
9841   unsigned LastArg = (BId == Builtin::BImemset || BId == Builtin::BIbzero ||
9842                       BId == Builtin::BIstrndup ? 1 : 2);
9843   unsigned LenArg =
9844       (BId == Builtin::BIbzero || BId == Builtin::BIstrndup ? 1 : 2);
9845   const Expr *LenExpr = Call->getArg(LenArg)->IgnoreParenImpCasts();
9846 
9847   if (CheckMemorySizeofForComparison(*this, LenExpr, FnName,
9848                                      Call->getBeginLoc(), Call->getRParenLoc()))
9849     return;
9850 
9851   // Catch cases like 'memset(buf, sizeof(buf), 0)'.
9852   CheckMemaccessSize(*this, BId, Call);
9853 
9854   // We have special checking when the length is a sizeof expression.
9855   QualType SizeOfArgTy = getSizeOfArgType(LenExpr);
9856   const Expr *SizeOfArg = getSizeOfExprArg(LenExpr);
9857   llvm::FoldingSetNodeID SizeOfArgID;
9858 
9859   // Although widely used, 'bzero' is not a standard function. Be more strict
9860   // with the argument types before allowing diagnostics and only allow the
9861   // form bzero(ptr, sizeof(...)).
9862   QualType FirstArgTy = Call->getArg(0)->IgnoreParenImpCasts()->getType();
9863   if (BId == Builtin::BIbzero && !FirstArgTy->getAs<PointerType>())
9864     return;
9865 
9866   for (unsigned ArgIdx = 0; ArgIdx != LastArg; ++ArgIdx) {
9867     const Expr *Dest = Call->getArg(ArgIdx)->IgnoreParenImpCasts();
9868     SourceRange ArgRange = Call->getArg(ArgIdx)->getSourceRange();
9869 
9870     QualType DestTy = Dest->getType();
9871     QualType PointeeTy;
9872     if (const PointerType *DestPtrTy = DestTy->getAs<PointerType>()) {
9873       PointeeTy = DestPtrTy->getPointeeType();
9874 
9875       // Never warn about void type pointers. This can be used to suppress
9876       // false positives.
9877       if (PointeeTy->isVoidType())
9878         continue;
9879 
9880       // Catch "memset(p, 0, sizeof(p))" -- needs to be sizeof(*p). Do this by
9881       // actually comparing the expressions for equality. Because computing the
9882       // expression IDs can be expensive, we only do this if the diagnostic is
9883       // enabled.
9884       if (SizeOfArg &&
9885           !Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess,
9886                            SizeOfArg->getExprLoc())) {
9887         // We only compute IDs for expressions if the warning is enabled, and
9888         // cache the sizeof arg's ID.
9889         if (SizeOfArgID == llvm::FoldingSetNodeID())
9890           SizeOfArg->Profile(SizeOfArgID, Context, true);
9891         llvm::FoldingSetNodeID DestID;
9892         Dest->Profile(DestID, Context, true);
9893         if (DestID == SizeOfArgID) {
9894           // TODO: For strncpy() and friends, this could suggest sizeof(dst)
9895           //       over sizeof(src) as well.
9896           unsigned ActionIdx = 0; // Default is to suggest dereferencing.
9897           StringRef ReadableName = FnName->getName();
9898 
9899           if (const UnaryOperator *UnaryOp = dyn_cast<UnaryOperator>(Dest))
9900             if (UnaryOp->getOpcode() == UO_AddrOf)
9901               ActionIdx = 1; // If its an address-of operator, just remove it.
9902           if (!PointeeTy->isIncompleteType() &&
9903               (Context.getTypeSize(PointeeTy) == Context.getCharWidth()))
9904             ActionIdx = 2; // If the pointee's size is sizeof(char),
9905                            // suggest an explicit length.
9906 
9907           // If the function is defined as a builtin macro, do not show macro
9908           // expansion.
9909           SourceLocation SL = SizeOfArg->getExprLoc();
9910           SourceRange DSR = Dest->getSourceRange();
9911           SourceRange SSR = SizeOfArg->getSourceRange();
9912           SourceManager &SM = getSourceManager();
9913 
9914           if (SM.isMacroArgExpansion(SL)) {
9915             ReadableName = Lexer::getImmediateMacroName(SL, SM, LangOpts);
9916             SL = SM.getSpellingLoc(SL);
9917             DSR = SourceRange(SM.getSpellingLoc(DSR.getBegin()),
9918                              SM.getSpellingLoc(DSR.getEnd()));
9919             SSR = SourceRange(SM.getSpellingLoc(SSR.getBegin()),
9920                              SM.getSpellingLoc(SSR.getEnd()));
9921           }
9922 
9923           DiagRuntimeBehavior(SL, SizeOfArg,
9924                               PDiag(diag::warn_sizeof_pointer_expr_memaccess)
9925                                 << ReadableName
9926                                 << PointeeTy
9927                                 << DestTy
9928                                 << DSR
9929                                 << SSR);
9930           DiagRuntimeBehavior(SL, SizeOfArg,
9931                          PDiag(diag::warn_sizeof_pointer_expr_memaccess_note)
9932                                 << ActionIdx
9933                                 << SSR);
9934 
9935           break;
9936         }
9937       }
9938 
9939       // Also check for cases where the sizeof argument is the exact same
9940       // type as the memory argument, and where it points to a user-defined
9941       // record type.
9942       if (SizeOfArgTy != QualType()) {
9943         if (PointeeTy->isRecordType() &&
9944             Context.typesAreCompatible(SizeOfArgTy, DestTy)) {
9945           DiagRuntimeBehavior(LenExpr->getExprLoc(), Dest,
9946                               PDiag(diag::warn_sizeof_pointer_type_memaccess)
9947                                 << FnName << SizeOfArgTy << ArgIdx
9948                                 << PointeeTy << Dest->getSourceRange()
9949                                 << LenExpr->getSourceRange());
9950           break;
9951         }
9952       }
9953     } else if (DestTy->isArrayType()) {
9954       PointeeTy = DestTy;
9955     }
9956 
9957     if (PointeeTy == QualType())
9958       continue;
9959 
9960     // Always complain about dynamic classes.
9961     bool IsContained;
9962     if (const CXXRecordDecl *ContainedRD =
9963             getContainedDynamicClass(PointeeTy, IsContained)) {
9964 
9965       unsigned OperationType = 0;
9966       const bool IsCmp = BId == Builtin::BImemcmp || BId == Builtin::BIbcmp;
9967       // "overwritten" if we're warning about the destination for any call
9968       // but memcmp; otherwise a verb appropriate to the call.
9969       if (ArgIdx != 0 || IsCmp) {
9970         if (BId == Builtin::BImemcpy)
9971           OperationType = 1;
9972         else if(BId == Builtin::BImemmove)
9973           OperationType = 2;
9974         else if (IsCmp)
9975           OperationType = 3;
9976       }
9977 
9978       DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9979                           PDiag(diag::warn_dyn_class_memaccess)
9980                               << (IsCmp ? ArgIdx + 2 : ArgIdx) << FnName
9981                               << IsContained << ContainedRD << OperationType
9982                               << Call->getCallee()->getSourceRange());
9983     } else if (PointeeTy.hasNonTrivialObjCLifetime() &&
9984              BId != Builtin::BImemset)
9985       DiagRuntimeBehavior(
9986         Dest->getExprLoc(), Dest,
9987         PDiag(diag::warn_arc_object_memaccess)
9988           << ArgIdx << FnName << PointeeTy
9989           << Call->getCallee()->getSourceRange());
9990     else if (const auto *RT = PointeeTy->getAs<RecordType>()) {
9991       if ((BId == Builtin::BImemset || BId == Builtin::BIbzero) &&
9992           RT->getDecl()->isNonTrivialToPrimitiveDefaultInitialize()) {
9993         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
9994                             PDiag(diag::warn_cstruct_memaccess)
9995                                 << ArgIdx << FnName << PointeeTy << 0);
9996         SearchNonTrivialToInitializeField::diag(PointeeTy, Dest, *this);
9997       } else if ((BId == Builtin::BImemcpy || BId == Builtin::BImemmove) &&
9998                  RT->getDecl()->isNonTrivialToPrimitiveCopy()) {
9999         DiagRuntimeBehavior(Dest->getExprLoc(), Dest,
10000                             PDiag(diag::warn_cstruct_memaccess)
10001                                 << ArgIdx << FnName << PointeeTy << 1);
10002         SearchNonTrivialToCopyField::diag(PointeeTy, Dest, *this);
10003       } else {
10004         continue;
10005       }
10006     } else
10007       continue;
10008 
10009     DiagRuntimeBehavior(
10010       Dest->getExprLoc(), Dest,
10011       PDiag(diag::note_bad_memaccess_silence)
10012         << FixItHint::CreateInsertion(ArgRange.getBegin(), "(void*)"));
10013     break;
10014   }
10015 }
10016 
10017 // A little helper routine: ignore addition and subtraction of integer literals.
10018 // This intentionally does not ignore all integer constant expressions because
10019 // we don't want to remove sizeof().
10020 static const Expr *ignoreLiteralAdditions(const Expr *Ex, ASTContext &Ctx) {
10021   Ex = Ex->IgnoreParenCasts();
10022 
10023   while (true) {
10024     const BinaryOperator * BO = dyn_cast<BinaryOperator>(Ex);
10025     if (!BO || !BO->isAdditiveOp())
10026       break;
10027 
10028     const Expr *RHS = BO->getRHS()->IgnoreParenCasts();
10029     const Expr *LHS = BO->getLHS()->IgnoreParenCasts();
10030 
10031     if (isa<IntegerLiteral>(RHS))
10032       Ex = LHS;
10033     else if (isa<IntegerLiteral>(LHS))
10034       Ex = RHS;
10035     else
10036       break;
10037   }
10038 
10039   return Ex;
10040 }
10041 
10042 static bool isConstantSizeArrayWithMoreThanOneElement(QualType Ty,
10043                                                       ASTContext &Context) {
10044   // Only handle constant-sized or VLAs, but not flexible members.
10045   if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(Ty)) {
10046     // Only issue the FIXIT for arrays of size > 1.
10047     if (CAT->getSize().getSExtValue() <= 1)
10048       return false;
10049   } else if (!Ty->isVariableArrayType()) {
10050     return false;
10051   }
10052   return true;
10053 }
10054 
10055 // Warn if the user has made the 'size' argument to strlcpy or strlcat
10056 // be the size of the source, instead of the destination.
10057 void Sema::CheckStrlcpycatArguments(const CallExpr *Call,
10058                                     IdentifierInfo *FnName) {
10059 
10060   // Don't crash if the user has the wrong number of arguments
10061   unsigned NumArgs = Call->getNumArgs();
10062   if ((NumArgs != 3) && (NumArgs != 4))
10063     return;
10064 
10065   const Expr *SrcArg = ignoreLiteralAdditions(Call->getArg(1), Context);
10066   const Expr *SizeArg = ignoreLiteralAdditions(Call->getArg(2), Context);
10067   const Expr *CompareWithSrc = nullptr;
10068 
10069   if (CheckMemorySizeofForComparison(*this, SizeArg, FnName,
10070                                      Call->getBeginLoc(), Call->getRParenLoc()))
10071     return;
10072 
10073   // Look for 'strlcpy(dst, x, sizeof(x))'
10074   if (const Expr *Ex = getSizeOfExprArg(SizeArg))
10075     CompareWithSrc = Ex;
10076   else {
10077     // Look for 'strlcpy(dst, x, strlen(x))'
10078     if (const CallExpr *SizeCall = dyn_cast<CallExpr>(SizeArg)) {
10079       if (SizeCall->getBuiltinCallee() == Builtin::BIstrlen &&
10080           SizeCall->getNumArgs() == 1)
10081         CompareWithSrc = ignoreLiteralAdditions(SizeCall->getArg(0), Context);
10082     }
10083   }
10084 
10085   if (!CompareWithSrc)
10086     return;
10087 
10088   // Determine if the argument to sizeof/strlen is equal to the source
10089   // argument.  In principle there's all kinds of things you could do
10090   // here, for instance creating an == expression and evaluating it with
10091   // EvaluateAsBooleanCondition, but this uses a more direct technique:
10092   const DeclRefExpr *SrcArgDRE = dyn_cast<DeclRefExpr>(SrcArg);
10093   if (!SrcArgDRE)
10094     return;
10095 
10096   const DeclRefExpr *CompareWithSrcDRE = dyn_cast<DeclRefExpr>(CompareWithSrc);
10097   if (!CompareWithSrcDRE ||
10098       SrcArgDRE->getDecl() != CompareWithSrcDRE->getDecl())
10099     return;
10100 
10101   const Expr *OriginalSizeArg = Call->getArg(2);
10102   Diag(CompareWithSrcDRE->getBeginLoc(), diag::warn_strlcpycat_wrong_size)
10103       << OriginalSizeArg->getSourceRange() << FnName;
10104 
10105   // Output a FIXIT hint if the destination is an array (rather than a
10106   // pointer to an array).  This could be enhanced to handle some
10107   // pointers if we know the actual size, like if DstArg is 'array+2'
10108   // we could say 'sizeof(array)-2'.
10109   const Expr *DstArg = Call->getArg(0)->IgnoreParenImpCasts();
10110   if (!isConstantSizeArrayWithMoreThanOneElement(DstArg->getType(), Context))
10111     return;
10112 
10113   SmallString<128> sizeString;
10114   llvm::raw_svector_ostream OS(sizeString);
10115   OS << "sizeof(";
10116   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10117   OS << ")";
10118 
10119   Diag(OriginalSizeArg->getBeginLoc(), diag::note_strlcpycat_wrong_size)
10120       << FixItHint::CreateReplacement(OriginalSizeArg->getSourceRange(),
10121                                       OS.str());
10122 }
10123 
10124 /// Check if two expressions refer to the same declaration.
10125 static bool referToTheSameDecl(const Expr *E1, const Expr *E2) {
10126   if (const DeclRefExpr *D1 = dyn_cast_or_null<DeclRefExpr>(E1))
10127     if (const DeclRefExpr *D2 = dyn_cast_or_null<DeclRefExpr>(E2))
10128       return D1->getDecl() == D2->getDecl();
10129   return false;
10130 }
10131 
10132 static const Expr *getStrlenExprArg(const Expr *E) {
10133   if (const CallExpr *CE = dyn_cast<CallExpr>(E)) {
10134     const FunctionDecl *FD = CE->getDirectCallee();
10135     if (!FD || FD->getMemoryFunctionKind() != Builtin::BIstrlen)
10136       return nullptr;
10137     return CE->getArg(0)->IgnoreParenCasts();
10138   }
10139   return nullptr;
10140 }
10141 
10142 // Warn on anti-patterns as the 'size' argument to strncat.
10143 // The correct size argument should look like following:
10144 //   strncat(dst, src, sizeof(dst) - strlen(dest) - 1);
10145 void Sema::CheckStrncatArguments(const CallExpr *CE,
10146                                  IdentifierInfo *FnName) {
10147   // Don't crash if the user has the wrong number of arguments.
10148   if (CE->getNumArgs() < 3)
10149     return;
10150   const Expr *DstArg = CE->getArg(0)->IgnoreParenCasts();
10151   const Expr *SrcArg = CE->getArg(1)->IgnoreParenCasts();
10152   const Expr *LenArg = CE->getArg(2)->IgnoreParenCasts();
10153 
10154   if (CheckMemorySizeofForComparison(*this, LenArg, FnName, CE->getBeginLoc(),
10155                                      CE->getRParenLoc()))
10156     return;
10157 
10158   // Identify common expressions, which are wrongly used as the size argument
10159   // to strncat and may lead to buffer overflows.
10160   unsigned PatternType = 0;
10161   if (const Expr *SizeOfArg = getSizeOfExprArg(LenArg)) {
10162     // - sizeof(dst)
10163     if (referToTheSameDecl(SizeOfArg, DstArg))
10164       PatternType = 1;
10165     // - sizeof(src)
10166     else if (referToTheSameDecl(SizeOfArg, SrcArg))
10167       PatternType = 2;
10168   } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(LenArg)) {
10169     if (BE->getOpcode() == BO_Sub) {
10170       const Expr *L = BE->getLHS()->IgnoreParenCasts();
10171       const Expr *R = BE->getRHS()->IgnoreParenCasts();
10172       // - sizeof(dst) - strlen(dst)
10173       if (referToTheSameDecl(DstArg, getSizeOfExprArg(L)) &&
10174           referToTheSameDecl(DstArg, getStrlenExprArg(R)))
10175         PatternType = 1;
10176       // - sizeof(src) - (anything)
10177       else if (referToTheSameDecl(SrcArg, getSizeOfExprArg(L)))
10178         PatternType = 2;
10179     }
10180   }
10181 
10182   if (PatternType == 0)
10183     return;
10184 
10185   // Generate the diagnostic.
10186   SourceLocation SL = LenArg->getBeginLoc();
10187   SourceRange SR = LenArg->getSourceRange();
10188   SourceManager &SM = getSourceManager();
10189 
10190   // If the function is defined as a builtin macro, do not show macro expansion.
10191   if (SM.isMacroArgExpansion(SL)) {
10192     SL = SM.getSpellingLoc(SL);
10193     SR = SourceRange(SM.getSpellingLoc(SR.getBegin()),
10194                      SM.getSpellingLoc(SR.getEnd()));
10195   }
10196 
10197   // Check if the destination is an array (rather than a pointer to an array).
10198   QualType DstTy = DstArg->getType();
10199   bool isKnownSizeArray = isConstantSizeArrayWithMoreThanOneElement(DstTy,
10200                                                                     Context);
10201   if (!isKnownSizeArray) {
10202     if (PatternType == 1)
10203       Diag(SL, diag::warn_strncat_wrong_size) << SR;
10204     else
10205       Diag(SL, diag::warn_strncat_src_size) << SR;
10206     return;
10207   }
10208 
10209   if (PatternType == 1)
10210     Diag(SL, diag::warn_strncat_large_size) << SR;
10211   else
10212     Diag(SL, diag::warn_strncat_src_size) << SR;
10213 
10214   SmallString<128> sizeString;
10215   llvm::raw_svector_ostream OS(sizeString);
10216   OS << "sizeof(";
10217   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10218   OS << ") - ";
10219   OS << "strlen(";
10220   DstArg->printPretty(OS, nullptr, getPrintingPolicy());
10221   OS << ") - 1";
10222 
10223   Diag(SL, diag::note_strncat_wrong_size)
10224     << FixItHint::CreateReplacement(SR, OS.str());
10225 }
10226 
10227 namespace {
10228 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10229                                 const UnaryOperator *UnaryExpr,
10230                                 const VarDecl *Var) {
10231   StorageClass Class = Var->getStorageClass();
10232   if (Class == StorageClass::SC_Extern ||
10233       Class == StorageClass::SC_PrivateExtern ||
10234       Var->getType()->isReferenceType())
10235     return;
10236 
10237   S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10238       << CalleeName << Var;
10239 }
10240 
10241 void CheckFreeArgumentsOnLvalue(Sema &S, const std::string &CalleeName,
10242                                 const UnaryOperator *UnaryExpr, const Decl *D) {
10243   if (const auto *Field = dyn_cast<FieldDecl>(D))
10244     S.Diag(UnaryExpr->getBeginLoc(), diag::warn_free_nonheap_object)
10245         << CalleeName << Field;
10246 }
10247 
10248 void CheckFreeArgumentsAddressof(Sema &S, const std::string &CalleeName,
10249                                  const UnaryOperator *UnaryExpr) {
10250   if (UnaryExpr->getOpcode() != UnaryOperator::Opcode::UO_AddrOf)
10251     return;
10252 
10253   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(UnaryExpr->getSubExpr()))
10254     if (const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl()))
10255       return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr, Var);
10256 
10257   if (const auto *Lvalue = dyn_cast<MemberExpr>(UnaryExpr->getSubExpr()))
10258     return CheckFreeArgumentsOnLvalue(S, CalleeName, UnaryExpr,
10259                                       Lvalue->getMemberDecl());
10260 }
10261 
10262 void CheckFreeArgumentsStackArray(Sema &S, const std::string &CalleeName,
10263                                   const DeclRefExpr *Lvalue) {
10264   if (!Lvalue->getType()->isArrayType())
10265     return;
10266 
10267   const auto *Var = dyn_cast<VarDecl>(Lvalue->getDecl());
10268   if (Var == nullptr)
10269     return;
10270 
10271   S.Diag(Lvalue->getBeginLoc(), diag::warn_free_nonheap_object)
10272       << CalleeName << Var;
10273 }
10274 } // namespace
10275 
10276 /// Alerts the user that they are attempting to free a non-malloc'd object.
10277 void Sema::CheckFreeArguments(const CallExpr *E) {
10278   const Expr *Arg = E->getArg(0)->IgnoreParenCasts();
10279   const std::string CalleeName =
10280       dyn_cast<FunctionDecl>(E->getCalleeDecl())->getQualifiedNameAsString();
10281 
10282   if (const auto *UnaryExpr = dyn_cast<UnaryOperator>(Arg))
10283     return CheckFreeArgumentsAddressof(*this, CalleeName, UnaryExpr);
10284 
10285   if (const auto *Lvalue = dyn_cast<DeclRefExpr>(Arg))
10286     return CheckFreeArgumentsStackArray(*this, CalleeName, Lvalue);
10287 }
10288 
10289 void
10290 Sema::CheckReturnValExpr(Expr *RetValExp, QualType lhsType,
10291                          SourceLocation ReturnLoc,
10292                          bool isObjCMethod,
10293                          const AttrVec *Attrs,
10294                          const FunctionDecl *FD) {
10295   // Check if the return value is null but should not be.
10296   if (((Attrs && hasSpecificAttr<ReturnsNonNullAttr>(*Attrs)) ||
10297        (!isObjCMethod && isNonNullType(Context, lhsType))) &&
10298       CheckNonNullExpr(*this, RetValExp))
10299     Diag(ReturnLoc, diag::warn_null_ret)
10300       << (isObjCMethod ? 1 : 0) << RetValExp->getSourceRange();
10301 
10302   // C++11 [basic.stc.dynamic.allocation]p4:
10303   //   If an allocation function declared with a non-throwing
10304   //   exception-specification fails to allocate storage, it shall return
10305   //   a null pointer. Any other allocation function that fails to allocate
10306   //   storage shall indicate failure only by throwing an exception [...]
10307   if (FD) {
10308     OverloadedOperatorKind Op = FD->getOverloadedOperator();
10309     if (Op == OO_New || Op == OO_Array_New) {
10310       const FunctionProtoType *Proto
10311         = FD->getType()->castAs<FunctionProtoType>();
10312       if (!Proto->isNothrow(/*ResultIfDependent*/true) &&
10313           CheckNonNullExpr(*this, RetValExp))
10314         Diag(ReturnLoc, diag::warn_operator_new_returns_null)
10315           << FD << getLangOpts().CPlusPlus11;
10316     }
10317   }
10318 }
10319 
10320 //===--- CHECK: Floating-Point comparisons (-Wfloat-equal) ---------------===//
10321 
10322 /// Check for comparisons of floating point operands using != and ==.
10323 /// Issue a warning if these are no self-comparisons, as they are not likely
10324 /// to do what the programmer intended.
10325 void Sema::CheckFloatComparison(SourceLocation Loc, Expr* LHS, Expr *RHS) {
10326   Expr* LeftExprSansParen = LHS->IgnoreParenImpCasts();
10327   Expr* RightExprSansParen = RHS->IgnoreParenImpCasts();
10328 
10329   // Special case: check for x == x (which is OK).
10330   // Do not emit warnings for such cases.
10331   if (DeclRefExpr* DRL = dyn_cast<DeclRefExpr>(LeftExprSansParen))
10332     if (DeclRefExpr* DRR = dyn_cast<DeclRefExpr>(RightExprSansParen))
10333       if (DRL->getDecl() == DRR->getDecl())
10334         return;
10335 
10336   // Special case: check for comparisons against literals that can be exactly
10337   //  represented by APFloat.  In such cases, do not emit a warning.  This
10338   //  is a heuristic: often comparison against such literals are used to
10339   //  detect if a value in a variable has not changed.  This clearly can
10340   //  lead to false negatives.
10341   if (FloatingLiteral* FLL = dyn_cast<FloatingLiteral>(LeftExprSansParen)) {
10342     if (FLL->isExact())
10343       return;
10344   } else
10345     if (FloatingLiteral* FLR = dyn_cast<FloatingLiteral>(RightExprSansParen))
10346       if (FLR->isExact())
10347         return;
10348 
10349   // Check for comparisons with builtin types.
10350   if (CallExpr* CL = dyn_cast<CallExpr>(LeftExprSansParen))
10351     if (CL->getBuiltinCallee())
10352       return;
10353 
10354   if (CallExpr* CR = dyn_cast<CallExpr>(RightExprSansParen))
10355     if (CR->getBuiltinCallee())
10356       return;
10357 
10358   // Emit the diagnostic.
10359   Diag(Loc, diag::warn_floatingpoint_eq)
10360     << LHS->getSourceRange() << RHS->getSourceRange();
10361 }
10362 
10363 //===--- CHECK: Integer mixed-sign comparisons (-Wsign-compare) --------===//
10364 //===--- CHECK: Lossy implicit conversions (-Wconversion) --------------===//
10365 
10366 namespace {
10367 
10368 /// Structure recording the 'active' range of an integer-valued
10369 /// expression.
10370 struct IntRange {
10371   /// The number of bits active in the int. Note that this includes exactly one
10372   /// sign bit if !NonNegative.
10373   unsigned Width;
10374 
10375   /// True if the int is known not to have negative values. If so, all leading
10376   /// bits before Width are known zero, otherwise they are known to be the
10377   /// same as the MSB within Width.
10378   bool NonNegative;
10379 
10380   IntRange(unsigned Width, bool NonNegative)
10381       : Width(Width), NonNegative(NonNegative) {}
10382 
10383   /// Number of bits excluding the sign bit.
10384   unsigned valueBits() const {
10385     return NonNegative ? Width : Width - 1;
10386   }
10387 
10388   /// Returns the range of the bool type.
10389   static IntRange forBoolType() {
10390     return IntRange(1, true);
10391   }
10392 
10393   /// Returns the range of an opaque value of the given integral type.
10394   static IntRange forValueOfType(ASTContext &C, QualType T) {
10395     return forValueOfCanonicalType(C,
10396                           T->getCanonicalTypeInternal().getTypePtr());
10397   }
10398 
10399   /// Returns the range of an opaque value of a canonical integral type.
10400   static IntRange forValueOfCanonicalType(ASTContext &C, const Type *T) {
10401     assert(T->isCanonicalUnqualified());
10402 
10403     if (const VectorType *VT = dyn_cast<VectorType>(T))
10404       T = VT->getElementType().getTypePtr();
10405     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10406       T = CT->getElementType().getTypePtr();
10407     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10408       T = AT->getValueType().getTypePtr();
10409 
10410     if (!C.getLangOpts().CPlusPlus) {
10411       // For enum types in C code, use the underlying datatype.
10412       if (const EnumType *ET = dyn_cast<EnumType>(T))
10413         T = ET->getDecl()->getIntegerType().getDesugaredType(C).getTypePtr();
10414     } else if (const EnumType *ET = dyn_cast<EnumType>(T)) {
10415       // For enum types in C++, use the known bit width of the enumerators.
10416       EnumDecl *Enum = ET->getDecl();
10417       // In C++11, enums can have a fixed underlying type. Use this type to
10418       // compute the range.
10419       if (Enum->isFixed()) {
10420         return IntRange(C.getIntWidth(QualType(T, 0)),
10421                         !ET->isSignedIntegerOrEnumerationType());
10422       }
10423 
10424       unsigned NumPositive = Enum->getNumPositiveBits();
10425       unsigned NumNegative = Enum->getNumNegativeBits();
10426 
10427       if (NumNegative == 0)
10428         return IntRange(NumPositive, true/*NonNegative*/);
10429       else
10430         return IntRange(std::max(NumPositive + 1, NumNegative),
10431                         false/*NonNegative*/);
10432     }
10433 
10434     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10435       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10436 
10437     const BuiltinType *BT = cast<BuiltinType>(T);
10438     assert(BT->isInteger());
10439 
10440     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10441   }
10442 
10443   /// Returns the "target" range of a canonical integral type, i.e.
10444   /// the range of values expressible in the type.
10445   ///
10446   /// This matches forValueOfCanonicalType except that enums have the
10447   /// full range of their type, not the range of their enumerators.
10448   static IntRange forTargetOfCanonicalType(ASTContext &C, const Type *T) {
10449     assert(T->isCanonicalUnqualified());
10450 
10451     if (const VectorType *VT = dyn_cast<VectorType>(T))
10452       T = VT->getElementType().getTypePtr();
10453     if (const ComplexType *CT = dyn_cast<ComplexType>(T))
10454       T = CT->getElementType().getTypePtr();
10455     if (const AtomicType *AT = dyn_cast<AtomicType>(T))
10456       T = AT->getValueType().getTypePtr();
10457     if (const EnumType *ET = dyn_cast<EnumType>(T))
10458       T = C.getCanonicalType(ET->getDecl()->getIntegerType()).getTypePtr();
10459 
10460     if (const auto *EIT = dyn_cast<ExtIntType>(T))
10461       return IntRange(EIT->getNumBits(), EIT->isUnsigned());
10462 
10463     const BuiltinType *BT = cast<BuiltinType>(T);
10464     assert(BT->isInteger());
10465 
10466     return IntRange(C.getIntWidth(QualType(T, 0)), BT->isUnsignedInteger());
10467   }
10468 
10469   /// Returns the supremum of two ranges: i.e. their conservative merge.
10470   static IntRange join(IntRange L, IntRange R) {
10471     bool Unsigned = L.NonNegative && R.NonNegative;
10472     return IntRange(std::max(L.valueBits(), R.valueBits()) + !Unsigned,
10473                     L.NonNegative && R.NonNegative);
10474   }
10475 
10476   /// Return the range of a bitwise-AND of the two ranges.
10477   static IntRange bit_and(IntRange L, IntRange R) {
10478     unsigned Bits = std::max(L.Width, R.Width);
10479     bool NonNegative = false;
10480     if (L.NonNegative) {
10481       Bits = std::min(Bits, L.Width);
10482       NonNegative = true;
10483     }
10484     if (R.NonNegative) {
10485       Bits = std::min(Bits, R.Width);
10486       NonNegative = true;
10487     }
10488     return IntRange(Bits, NonNegative);
10489   }
10490 
10491   /// Return the range of a sum of the two ranges.
10492   static IntRange sum(IntRange L, IntRange R) {
10493     bool Unsigned = L.NonNegative && R.NonNegative;
10494     return IntRange(std::max(L.valueBits(), R.valueBits()) + 1 + !Unsigned,
10495                     Unsigned);
10496   }
10497 
10498   /// Return the range of a difference of the two ranges.
10499   static IntRange difference(IntRange L, IntRange R) {
10500     // We need a 1-bit-wider range if:
10501     //   1) LHS can be negative: least value can be reduced.
10502     //   2) RHS can be negative: greatest value can be increased.
10503     bool CanWiden = !L.NonNegative || !R.NonNegative;
10504     bool Unsigned = L.NonNegative && R.Width == 0;
10505     return IntRange(std::max(L.valueBits(), R.valueBits()) + CanWiden +
10506                         !Unsigned,
10507                     Unsigned);
10508   }
10509 
10510   /// Return the range of a product of the two ranges.
10511   static IntRange product(IntRange L, IntRange R) {
10512     // If both LHS and RHS can be negative, we can form
10513     //   -2^L * -2^R = 2^(L + R)
10514     // which requires L + R + 1 value bits to represent.
10515     bool CanWiden = !L.NonNegative && !R.NonNegative;
10516     bool Unsigned = L.NonNegative && R.NonNegative;
10517     return IntRange(L.valueBits() + R.valueBits() + CanWiden + !Unsigned,
10518                     Unsigned);
10519   }
10520 
10521   /// Return the range of a remainder operation between the two ranges.
10522   static IntRange rem(IntRange L, IntRange R) {
10523     // The result of a remainder can't be larger than the result of
10524     // either side. The sign of the result is the sign of the LHS.
10525     bool Unsigned = L.NonNegative;
10526     return IntRange(std::min(L.valueBits(), R.valueBits()) + !Unsigned,
10527                     Unsigned);
10528   }
10529 };
10530 
10531 } // namespace
10532 
10533 static IntRange GetValueRange(ASTContext &C, llvm::APSInt &value,
10534                               unsigned MaxWidth) {
10535   if (value.isSigned() && value.isNegative())
10536     return IntRange(value.getMinSignedBits(), false);
10537 
10538   if (value.getBitWidth() > MaxWidth)
10539     value = value.trunc(MaxWidth);
10540 
10541   // isNonNegative() just checks the sign bit without considering
10542   // signedness.
10543   return IntRange(value.getActiveBits(), true);
10544 }
10545 
10546 static IntRange GetValueRange(ASTContext &C, APValue &result, QualType Ty,
10547                               unsigned MaxWidth) {
10548   if (result.isInt())
10549     return GetValueRange(C, result.getInt(), MaxWidth);
10550 
10551   if (result.isVector()) {
10552     IntRange R = GetValueRange(C, result.getVectorElt(0), Ty, MaxWidth);
10553     for (unsigned i = 1, e = result.getVectorLength(); i != e; ++i) {
10554       IntRange El = GetValueRange(C, result.getVectorElt(i), Ty, MaxWidth);
10555       R = IntRange::join(R, El);
10556     }
10557     return R;
10558   }
10559 
10560   if (result.isComplexInt()) {
10561     IntRange R = GetValueRange(C, result.getComplexIntReal(), MaxWidth);
10562     IntRange I = GetValueRange(C, result.getComplexIntImag(), MaxWidth);
10563     return IntRange::join(R, I);
10564   }
10565 
10566   // This can happen with lossless casts to intptr_t of "based" lvalues.
10567   // Assume it might use arbitrary bits.
10568   // FIXME: The only reason we need to pass the type in here is to get
10569   // the sign right on this one case.  It would be nice if APValue
10570   // preserved this.
10571   assert(result.isLValue() || result.isAddrLabelDiff());
10572   return IntRange(MaxWidth, Ty->isUnsignedIntegerOrEnumerationType());
10573 }
10574 
10575 static QualType GetExprType(const Expr *E) {
10576   QualType Ty = E->getType();
10577   if (const AtomicType *AtomicRHS = Ty->getAs<AtomicType>())
10578     Ty = AtomicRHS->getValueType();
10579   return Ty;
10580 }
10581 
10582 /// Pseudo-evaluate the given integer expression, estimating the
10583 /// range of values it might take.
10584 ///
10585 /// \param MaxWidth The width to which the value will be truncated.
10586 /// \param Approximate If \c true, return a likely range for the result: in
10587 ///        particular, assume that aritmetic on narrower types doesn't leave
10588 ///        those types. If \c false, return a range including all possible
10589 ///        result values.
10590 static IntRange GetExprRange(ASTContext &C, const Expr *E, unsigned MaxWidth,
10591                              bool InConstantContext, bool Approximate) {
10592   E = E->IgnoreParens();
10593 
10594   // Try a full evaluation first.
10595   Expr::EvalResult result;
10596   if (E->EvaluateAsRValue(result, C, InConstantContext))
10597     return GetValueRange(C, result.Val, GetExprType(E), MaxWidth);
10598 
10599   // I think we only want to look through implicit casts here; if the
10600   // user has an explicit widening cast, we should treat the value as
10601   // being of the new, wider type.
10602   if (const auto *CE = dyn_cast<ImplicitCastExpr>(E)) {
10603     if (CE->getCastKind() == CK_NoOp || CE->getCastKind() == CK_LValueToRValue)
10604       return GetExprRange(C, CE->getSubExpr(), MaxWidth, InConstantContext,
10605                           Approximate);
10606 
10607     IntRange OutputTypeRange = IntRange::forValueOfType(C, GetExprType(CE));
10608 
10609     bool isIntegerCast = CE->getCastKind() == CK_IntegralCast ||
10610                          CE->getCastKind() == CK_BooleanToSignedIntegral;
10611 
10612     // Assume that non-integer casts can span the full range of the type.
10613     if (!isIntegerCast)
10614       return OutputTypeRange;
10615 
10616     IntRange SubRange = GetExprRange(C, CE->getSubExpr(),
10617                                      std::min(MaxWidth, OutputTypeRange.Width),
10618                                      InConstantContext, Approximate);
10619 
10620     // Bail out if the subexpr's range is as wide as the cast type.
10621     if (SubRange.Width >= OutputTypeRange.Width)
10622       return OutputTypeRange;
10623 
10624     // Otherwise, we take the smaller width, and we're non-negative if
10625     // either the output type or the subexpr is.
10626     return IntRange(SubRange.Width,
10627                     SubRange.NonNegative || OutputTypeRange.NonNegative);
10628   }
10629 
10630   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
10631     // If we can fold the condition, just take that operand.
10632     bool CondResult;
10633     if (CO->getCond()->EvaluateAsBooleanCondition(CondResult, C))
10634       return GetExprRange(C,
10635                           CondResult ? CO->getTrueExpr() : CO->getFalseExpr(),
10636                           MaxWidth, InConstantContext, Approximate);
10637 
10638     // Otherwise, conservatively merge.
10639     // GetExprRange requires an integer expression, but a throw expression
10640     // results in a void type.
10641     Expr *E = CO->getTrueExpr();
10642     IntRange L = E->getType()->isVoidType()
10643                      ? IntRange{0, true}
10644                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10645     E = CO->getFalseExpr();
10646     IntRange R = E->getType()->isVoidType()
10647                      ? IntRange{0, true}
10648                      : GetExprRange(C, E, MaxWidth, InConstantContext, Approximate);
10649     return IntRange::join(L, R);
10650   }
10651 
10652   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
10653     IntRange (*Combine)(IntRange, IntRange) = IntRange::join;
10654 
10655     switch (BO->getOpcode()) {
10656     case BO_Cmp:
10657       llvm_unreachable("builtin <=> should have class type");
10658 
10659     // Boolean-valued operations are single-bit and positive.
10660     case BO_LAnd:
10661     case BO_LOr:
10662     case BO_LT:
10663     case BO_GT:
10664     case BO_LE:
10665     case BO_GE:
10666     case BO_EQ:
10667     case BO_NE:
10668       return IntRange::forBoolType();
10669 
10670     // The type of the assignments is the type of the LHS, so the RHS
10671     // is not necessarily the same type.
10672     case BO_MulAssign:
10673     case BO_DivAssign:
10674     case BO_RemAssign:
10675     case BO_AddAssign:
10676     case BO_SubAssign:
10677     case BO_XorAssign:
10678     case BO_OrAssign:
10679       // TODO: bitfields?
10680       return IntRange::forValueOfType(C, GetExprType(E));
10681 
10682     // Simple assignments just pass through the RHS, which will have
10683     // been coerced to the LHS type.
10684     case BO_Assign:
10685       // TODO: bitfields?
10686       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10687                           Approximate);
10688 
10689     // Operations with opaque sources are black-listed.
10690     case BO_PtrMemD:
10691     case BO_PtrMemI:
10692       return IntRange::forValueOfType(C, GetExprType(E));
10693 
10694     // Bitwise-and uses the *infinum* of the two source ranges.
10695     case BO_And:
10696     case BO_AndAssign:
10697       Combine = IntRange::bit_and;
10698       break;
10699 
10700     // Left shift gets black-listed based on a judgement call.
10701     case BO_Shl:
10702       // ...except that we want to treat '1 << (blah)' as logically
10703       // positive.  It's an important idiom.
10704       if (IntegerLiteral *I
10705             = dyn_cast<IntegerLiteral>(BO->getLHS()->IgnoreParenCasts())) {
10706         if (I->getValue() == 1) {
10707           IntRange R = IntRange::forValueOfType(C, GetExprType(E));
10708           return IntRange(R.Width, /*NonNegative*/ true);
10709         }
10710       }
10711       LLVM_FALLTHROUGH;
10712 
10713     case BO_ShlAssign:
10714       return IntRange::forValueOfType(C, GetExprType(E));
10715 
10716     // Right shift by a constant can narrow its left argument.
10717     case BO_Shr:
10718     case BO_ShrAssign: {
10719       IntRange L = GetExprRange(C, BO->getLHS(), MaxWidth, InConstantContext,
10720                                 Approximate);
10721 
10722       // If the shift amount is a positive constant, drop the width by
10723       // that much.
10724       if (Optional<llvm::APSInt> shift =
10725               BO->getRHS()->getIntegerConstantExpr(C)) {
10726         if (shift->isNonNegative()) {
10727           unsigned zext = shift->getZExtValue();
10728           if (zext >= L.Width)
10729             L.Width = (L.NonNegative ? 0 : 1);
10730           else
10731             L.Width -= zext;
10732         }
10733       }
10734 
10735       return L;
10736     }
10737 
10738     // Comma acts as its right operand.
10739     case BO_Comma:
10740       return GetExprRange(C, BO->getRHS(), MaxWidth, InConstantContext,
10741                           Approximate);
10742 
10743     case BO_Add:
10744       if (!Approximate)
10745         Combine = IntRange::sum;
10746       break;
10747 
10748     case BO_Sub:
10749       if (BO->getLHS()->getType()->isPointerType())
10750         return IntRange::forValueOfType(C, GetExprType(E));
10751       if (!Approximate)
10752         Combine = IntRange::difference;
10753       break;
10754 
10755     case BO_Mul:
10756       if (!Approximate)
10757         Combine = IntRange::product;
10758       break;
10759 
10760     // The width of a division result is mostly determined by the size
10761     // of the LHS.
10762     case BO_Div: {
10763       // Don't 'pre-truncate' the operands.
10764       unsigned opWidth = C.getIntWidth(GetExprType(E));
10765       IntRange L = GetExprRange(C, BO->getLHS(), opWidth, InConstantContext,
10766                                 Approximate);
10767 
10768       // If the divisor is constant, use that.
10769       if (Optional<llvm::APSInt> divisor =
10770               BO->getRHS()->getIntegerConstantExpr(C)) {
10771         unsigned log2 = divisor->logBase2(); // floor(log_2(divisor))
10772         if (log2 >= L.Width)
10773           L.Width = (L.NonNegative ? 0 : 1);
10774         else
10775           L.Width = std::min(L.Width - log2, MaxWidth);
10776         return L;
10777       }
10778 
10779       // Otherwise, just use the LHS's width.
10780       // FIXME: This is wrong if the LHS could be its minimal value and the RHS
10781       // could be -1.
10782       IntRange R = GetExprRange(C, BO->getRHS(), opWidth, InConstantContext,
10783                                 Approximate);
10784       return IntRange(L.Width, L.NonNegative && R.NonNegative);
10785     }
10786 
10787     case BO_Rem:
10788       Combine = IntRange::rem;
10789       break;
10790 
10791     // The default behavior is okay for these.
10792     case BO_Xor:
10793     case BO_Or:
10794       break;
10795     }
10796 
10797     // Combine the two ranges, but limit the result to the type in which we
10798     // performed the computation.
10799     QualType T = GetExprType(E);
10800     unsigned opWidth = C.getIntWidth(T);
10801     IntRange L =
10802         GetExprRange(C, BO->getLHS(), opWidth, InConstantContext, Approximate);
10803     IntRange R =
10804         GetExprRange(C, BO->getRHS(), opWidth, InConstantContext, Approximate);
10805     IntRange C = Combine(L, R);
10806     C.NonNegative |= T->isUnsignedIntegerOrEnumerationType();
10807     C.Width = std::min(C.Width, MaxWidth);
10808     return C;
10809   }
10810 
10811   if (const auto *UO = dyn_cast<UnaryOperator>(E)) {
10812     switch (UO->getOpcode()) {
10813     // Boolean-valued operations are white-listed.
10814     case UO_LNot:
10815       return IntRange::forBoolType();
10816 
10817     // Operations with opaque sources are black-listed.
10818     case UO_Deref:
10819     case UO_AddrOf: // should be impossible
10820       return IntRange::forValueOfType(C, GetExprType(E));
10821 
10822     default:
10823       return GetExprRange(C, UO->getSubExpr(), MaxWidth, InConstantContext,
10824                           Approximate);
10825     }
10826   }
10827 
10828   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E))
10829     return GetExprRange(C, OVE->getSourceExpr(), MaxWidth, InConstantContext,
10830                         Approximate);
10831 
10832   if (const auto *BitField = E->getSourceBitField())
10833     return IntRange(BitField->getBitWidthValue(C),
10834                     BitField->getType()->isUnsignedIntegerOrEnumerationType());
10835 
10836   return IntRange::forValueOfType(C, GetExprType(E));
10837 }
10838 
10839 static IntRange GetExprRange(ASTContext &C, const Expr *E,
10840                              bool InConstantContext, bool Approximate) {
10841   return GetExprRange(C, E, C.getIntWidth(GetExprType(E)), InConstantContext,
10842                       Approximate);
10843 }
10844 
10845 /// Checks whether the given value, which currently has the given
10846 /// source semantics, has the same value when coerced through the
10847 /// target semantics.
10848 static bool IsSameFloatAfterCast(const llvm::APFloat &value,
10849                                  const llvm::fltSemantics &Src,
10850                                  const llvm::fltSemantics &Tgt) {
10851   llvm::APFloat truncated = value;
10852 
10853   bool ignored;
10854   truncated.convert(Src, llvm::APFloat::rmNearestTiesToEven, &ignored);
10855   truncated.convert(Tgt, llvm::APFloat::rmNearestTiesToEven, &ignored);
10856 
10857   return truncated.bitwiseIsEqual(value);
10858 }
10859 
10860 /// Checks whether the given value, which currently has the given
10861 /// source semantics, has the same value when coerced through the
10862 /// target semantics.
10863 ///
10864 /// The value might be a vector of floats (or a complex number).
10865 static bool IsSameFloatAfterCast(const APValue &value,
10866                                  const llvm::fltSemantics &Src,
10867                                  const llvm::fltSemantics &Tgt) {
10868   if (value.isFloat())
10869     return IsSameFloatAfterCast(value.getFloat(), Src, Tgt);
10870 
10871   if (value.isVector()) {
10872     for (unsigned i = 0, e = value.getVectorLength(); i != e; ++i)
10873       if (!IsSameFloatAfterCast(value.getVectorElt(i), Src, Tgt))
10874         return false;
10875     return true;
10876   }
10877 
10878   assert(value.isComplexFloat());
10879   return (IsSameFloatAfterCast(value.getComplexFloatReal(), Src, Tgt) &&
10880           IsSameFloatAfterCast(value.getComplexFloatImag(), Src, Tgt));
10881 }
10882 
10883 static void AnalyzeImplicitConversions(Sema &S, Expr *E, SourceLocation CC,
10884                                        bool IsListInit = false);
10885 
10886 static bool IsEnumConstOrFromMacro(Sema &S, Expr *E) {
10887   // Suppress cases where we are comparing against an enum constant.
10888   if (const DeclRefExpr *DR =
10889       dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts()))
10890     if (isa<EnumConstantDecl>(DR->getDecl()))
10891       return true;
10892 
10893   // Suppress cases where the value is expanded from a macro, unless that macro
10894   // is how a language represents a boolean literal. This is the case in both C
10895   // and Objective-C.
10896   SourceLocation BeginLoc = E->getBeginLoc();
10897   if (BeginLoc.isMacroID()) {
10898     StringRef MacroName = Lexer::getImmediateMacroName(
10899         BeginLoc, S.getSourceManager(), S.getLangOpts());
10900     return MacroName != "YES" && MacroName != "NO" &&
10901            MacroName != "true" && MacroName != "false";
10902   }
10903 
10904   return false;
10905 }
10906 
10907 static bool isKnownToHaveUnsignedValue(Expr *E) {
10908   return E->getType()->isIntegerType() &&
10909          (!E->getType()->isSignedIntegerType() ||
10910           !E->IgnoreParenImpCasts()->getType()->isSignedIntegerType());
10911 }
10912 
10913 namespace {
10914 /// The promoted range of values of a type. In general this has the
10915 /// following structure:
10916 ///
10917 ///     |-----------| . . . |-----------|
10918 ///     ^           ^       ^           ^
10919 ///    Min       HoleMin  HoleMax      Max
10920 ///
10921 /// ... where there is only a hole if a signed type is promoted to unsigned
10922 /// (in which case Min and Max are the smallest and largest representable
10923 /// values).
10924 struct PromotedRange {
10925   // Min, or HoleMax if there is a hole.
10926   llvm::APSInt PromotedMin;
10927   // Max, or HoleMin if there is a hole.
10928   llvm::APSInt PromotedMax;
10929 
10930   PromotedRange(IntRange R, unsigned BitWidth, bool Unsigned) {
10931     if (R.Width == 0)
10932       PromotedMin = PromotedMax = llvm::APSInt(BitWidth, Unsigned);
10933     else if (R.Width >= BitWidth && !Unsigned) {
10934       // Promotion made the type *narrower*. This happens when promoting
10935       // a < 32-bit unsigned / <= 32-bit signed bit-field to 'signed int'.
10936       // Treat all values of 'signed int' as being in range for now.
10937       PromotedMin = llvm::APSInt::getMinValue(BitWidth, Unsigned);
10938       PromotedMax = llvm::APSInt::getMaxValue(BitWidth, Unsigned);
10939     } else {
10940       PromotedMin = llvm::APSInt::getMinValue(R.Width, R.NonNegative)
10941                         .extOrTrunc(BitWidth);
10942       PromotedMin.setIsUnsigned(Unsigned);
10943 
10944       PromotedMax = llvm::APSInt::getMaxValue(R.Width, R.NonNegative)
10945                         .extOrTrunc(BitWidth);
10946       PromotedMax.setIsUnsigned(Unsigned);
10947     }
10948   }
10949 
10950   // Determine whether this range is contiguous (has no hole).
10951   bool isContiguous() const { return PromotedMin <= PromotedMax; }
10952 
10953   // Where a constant value is within the range.
10954   enum ComparisonResult {
10955     LT = 0x1,
10956     LE = 0x2,
10957     GT = 0x4,
10958     GE = 0x8,
10959     EQ = 0x10,
10960     NE = 0x20,
10961     InRangeFlag = 0x40,
10962 
10963     Less = LE | LT | NE,
10964     Min = LE | InRangeFlag,
10965     InRange = InRangeFlag,
10966     Max = GE | InRangeFlag,
10967     Greater = GE | GT | NE,
10968 
10969     OnlyValue = LE | GE | EQ | InRangeFlag,
10970     InHole = NE
10971   };
10972 
10973   ComparisonResult compare(const llvm::APSInt &Value) const {
10974     assert(Value.getBitWidth() == PromotedMin.getBitWidth() &&
10975            Value.isUnsigned() == PromotedMin.isUnsigned());
10976     if (!isContiguous()) {
10977       assert(Value.isUnsigned() && "discontiguous range for signed compare");
10978       if (Value.isMinValue()) return Min;
10979       if (Value.isMaxValue()) return Max;
10980       if (Value >= PromotedMin) return InRange;
10981       if (Value <= PromotedMax) return InRange;
10982       return InHole;
10983     }
10984 
10985     switch (llvm::APSInt::compareValues(Value, PromotedMin)) {
10986     case -1: return Less;
10987     case 0: return PromotedMin == PromotedMax ? OnlyValue : Min;
10988     case 1:
10989       switch (llvm::APSInt::compareValues(Value, PromotedMax)) {
10990       case -1: return InRange;
10991       case 0: return Max;
10992       case 1: return Greater;
10993       }
10994     }
10995 
10996     llvm_unreachable("impossible compare result");
10997   }
10998 
10999   static llvm::Optional<StringRef>
11000   constantValue(BinaryOperatorKind Op, ComparisonResult R, bool ConstantOnRHS) {
11001     if (Op == BO_Cmp) {
11002       ComparisonResult LTFlag = LT, GTFlag = GT;
11003       if (ConstantOnRHS) std::swap(LTFlag, GTFlag);
11004 
11005       if (R & EQ) return StringRef("'std::strong_ordering::equal'");
11006       if (R & LTFlag) return StringRef("'std::strong_ordering::less'");
11007       if (R & GTFlag) return StringRef("'std::strong_ordering::greater'");
11008       return llvm::None;
11009     }
11010 
11011     ComparisonResult TrueFlag, FalseFlag;
11012     if (Op == BO_EQ) {
11013       TrueFlag = EQ;
11014       FalseFlag = NE;
11015     } else if (Op == BO_NE) {
11016       TrueFlag = NE;
11017       FalseFlag = EQ;
11018     } else {
11019       if ((Op == BO_LT || Op == BO_GE) ^ ConstantOnRHS) {
11020         TrueFlag = LT;
11021         FalseFlag = GE;
11022       } else {
11023         TrueFlag = GT;
11024         FalseFlag = LE;
11025       }
11026       if (Op == BO_GE || Op == BO_LE)
11027         std::swap(TrueFlag, FalseFlag);
11028     }
11029     if (R & TrueFlag)
11030       return StringRef("true");
11031     if (R & FalseFlag)
11032       return StringRef("false");
11033     return llvm::None;
11034   }
11035 };
11036 }
11037 
11038 static bool HasEnumType(Expr *E) {
11039   // Strip off implicit integral promotions.
11040   while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
11041     if (ICE->getCastKind() != CK_IntegralCast &&
11042         ICE->getCastKind() != CK_NoOp)
11043       break;
11044     E = ICE->getSubExpr();
11045   }
11046 
11047   return E->getType()->isEnumeralType();
11048 }
11049 
11050 static int classifyConstantValue(Expr *Constant) {
11051   // The values of this enumeration are used in the diagnostics
11052   // diag::warn_out_of_range_compare and diag::warn_tautological_bool_compare.
11053   enum ConstantValueKind {
11054     Miscellaneous = 0,
11055     LiteralTrue,
11056     LiteralFalse
11057   };
11058   if (auto *BL = dyn_cast<CXXBoolLiteralExpr>(Constant))
11059     return BL->getValue() ? ConstantValueKind::LiteralTrue
11060                           : ConstantValueKind::LiteralFalse;
11061   return ConstantValueKind::Miscellaneous;
11062 }
11063 
11064 static bool CheckTautologicalComparison(Sema &S, BinaryOperator *E,
11065                                         Expr *Constant, Expr *Other,
11066                                         const llvm::APSInt &Value,
11067                                         bool RhsConstant) {
11068   if (S.inTemplateInstantiation())
11069     return false;
11070 
11071   Expr *OriginalOther = Other;
11072 
11073   Constant = Constant->IgnoreParenImpCasts();
11074   Other = Other->IgnoreParenImpCasts();
11075 
11076   // Suppress warnings on tautological comparisons between values of the same
11077   // enumeration type. There are only two ways we could warn on this:
11078   //  - If the constant is outside the range of representable values of
11079   //    the enumeration. In such a case, we should warn about the cast
11080   //    to enumeration type, not about the comparison.
11081   //  - If the constant is the maximum / minimum in-range value. For an
11082   //    enumeratin type, such comparisons can be meaningful and useful.
11083   if (Constant->getType()->isEnumeralType() &&
11084       S.Context.hasSameUnqualifiedType(Constant->getType(), Other->getType()))
11085     return false;
11086 
11087   IntRange OtherValueRange = GetExprRange(
11088       S.Context, Other, S.isConstantEvaluated(), /*Approximate*/ false);
11089 
11090   QualType OtherT = Other->getType();
11091   if (const auto *AT = OtherT->getAs<AtomicType>())
11092     OtherT = AT->getValueType();
11093   IntRange OtherTypeRange = IntRange::forValueOfType(S.Context, OtherT);
11094 
11095   // Special case for ObjC BOOL on targets where its a typedef for a signed char
11096   // (Namely, macOS). FIXME: IntRange::forValueOfType should do this.
11097   bool IsObjCSignedCharBool = S.getLangOpts().ObjC &&
11098                               S.NSAPIObj->isObjCBOOLType(OtherT) &&
11099                               OtherT->isSpecificBuiltinType(BuiltinType::SChar);
11100 
11101   // Whether we're treating Other as being a bool because of the form of
11102   // expression despite it having another type (typically 'int' in C).
11103   bool OtherIsBooleanDespiteType =
11104       !OtherT->isBooleanType() && Other->isKnownToHaveBooleanValue();
11105   if (OtherIsBooleanDespiteType || IsObjCSignedCharBool)
11106     OtherTypeRange = OtherValueRange = IntRange::forBoolType();
11107 
11108   // Check if all values in the range of possible values of this expression
11109   // lead to the same comparison outcome.
11110   PromotedRange OtherPromotedValueRange(OtherValueRange, Value.getBitWidth(),
11111                                         Value.isUnsigned());
11112   auto Cmp = OtherPromotedValueRange.compare(Value);
11113   auto Result = PromotedRange::constantValue(E->getOpcode(), Cmp, RhsConstant);
11114   if (!Result)
11115     return false;
11116 
11117   // Also consider the range determined by the type alone. This allows us to
11118   // classify the warning under the proper diagnostic group.
11119   bool TautologicalTypeCompare = false;
11120   {
11121     PromotedRange OtherPromotedTypeRange(OtherTypeRange, Value.getBitWidth(),
11122                                          Value.isUnsigned());
11123     auto TypeCmp = OtherPromotedTypeRange.compare(Value);
11124     if (auto TypeResult = PromotedRange::constantValue(E->getOpcode(), TypeCmp,
11125                                                        RhsConstant)) {
11126       TautologicalTypeCompare = true;
11127       Cmp = TypeCmp;
11128       Result = TypeResult;
11129     }
11130   }
11131 
11132   // Don't warn if the non-constant operand actually always evaluates to the
11133   // same value.
11134   if (!TautologicalTypeCompare && OtherValueRange.Width == 0)
11135     return false;
11136 
11137   // Suppress the diagnostic for an in-range comparison if the constant comes
11138   // from a macro or enumerator. We don't want to diagnose
11139   //
11140   //   some_long_value <= INT_MAX
11141   //
11142   // when sizeof(int) == sizeof(long).
11143   bool InRange = Cmp & PromotedRange::InRangeFlag;
11144   if (InRange && IsEnumConstOrFromMacro(S, Constant))
11145     return false;
11146 
11147   // A comparison of an unsigned bit-field against 0 is really a type problem,
11148   // even though at the type level the bit-field might promote to 'signed int'.
11149   if (Other->refersToBitField() && InRange && Value == 0 &&
11150       Other->getType()->isUnsignedIntegerOrEnumerationType())
11151     TautologicalTypeCompare = true;
11152 
11153   // If this is a comparison to an enum constant, include that
11154   // constant in the diagnostic.
11155   const EnumConstantDecl *ED = nullptr;
11156   if (const DeclRefExpr *DR = dyn_cast<DeclRefExpr>(Constant))
11157     ED = dyn_cast<EnumConstantDecl>(DR->getDecl());
11158 
11159   // Should be enough for uint128 (39 decimal digits)
11160   SmallString<64> PrettySourceValue;
11161   llvm::raw_svector_ostream OS(PrettySourceValue);
11162   if (ED) {
11163     OS << '\'' << *ED << "' (" << Value << ")";
11164   } else if (auto *BL = dyn_cast<ObjCBoolLiteralExpr>(
11165                Constant->IgnoreParenImpCasts())) {
11166     OS << (BL->getValue() ? "YES" : "NO");
11167   } else {
11168     OS << Value;
11169   }
11170 
11171   if (!TautologicalTypeCompare) {
11172     S.Diag(E->getOperatorLoc(), diag::warn_tautological_compare_value_range)
11173         << RhsConstant << OtherValueRange.Width << OtherValueRange.NonNegative
11174         << E->getOpcodeStr() << OS.str() << *Result
11175         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11176     return true;
11177   }
11178 
11179   if (IsObjCSignedCharBool) {
11180     S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11181                           S.PDiag(diag::warn_tautological_compare_objc_bool)
11182                               << OS.str() << *Result);
11183     return true;
11184   }
11185 
11186   // FIXME: We use a somewhat different formatting for the in-range cases and
11187   // cases involving boolean values for historical reasons. We should pick a
11188   // consistent way of presenting these diagnostics.
11189   if (!InRange || Other->isKnownToHaveBooleanValue()) {
11190 
11191     S.DiagRuntimeBehavior(
11192         E->getOperatorLoc(), E,
11193         S.PDiag(!InRange ? diag::warn_out_of_range_compare
11194                          : diag::warn_tautological_bool_compare)
11195             << OS.str() << classifyConstantValue(Constant) << OtherT
11196             << OtherIsBooleanDespiteType << *Result
11197             << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange());
11198   } else {
11199     unsigned Diag = (isKnownToHaveUnsignedValue(OriginalOther) && Value == 0)
11200                         ? (HasEnumType(OriginalOther)
11201                                ? diag::warn_unsigned_enum_always_true_comparison
11202                                : diag::warn_unsigned_always_true_comparison)
11203                         : diag::warn_tautological_constant_compare;
11204 
11205     S.Diag(E->getOperatorLoc(), Diag)
11206         << RhsConstant << OtherT << E->getOpcodeStr() << OS.str() << *Result
11207         << E->getLHS()->getSourceRange() << E->getRHS()->getSourceRange();
11208   }
11209 
11210   return true;
11211 }
11212 
11213 /// Analyze the operands of the given comparison.  Implements the
11214 /// fallback case from AnalyzeComparison.
11215 static void AnalyzeImpConvsInComparison(Sema &S, BinaryOperator *E) {
11216   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11217   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11218 }
11219 
11220 /// Implements -Wsign-compare.
11221 ///
11222 /// \param E the binary operator to check for warnings
11223 static void AnalyzeComparison(Sema &S, BinaryOperator *E) {
11224   // The type the comparison is being performed in.
11225   QualType T = E->getLHS()->getType();
11226 
11227   // Only analyze comparison operators where both sides have been converted to
11228   // the same type.
11229   if (!S.Context.hasSameUnqualifiedType(T, E->getRHS()->getType()))
11230     return AnalyzeImpConvsInComparison(S, E);
11231 
11232   // Don't analyze value-dependent comparisons directly.
11233   if (E->isValueDependent())
11234     return AnalyzeImpConvsInComparison(S, E);
11235 
11236   Expr *LHS = E->getLHS();
11237   Expr *RHS = E->getRHS();
11238 
11239   if (T->isIntegralType(S.Context)) {
11240     Optional<llvm::APSInt> RHSValue = RHS->getIntegerConstantExpr(S.Context);
11241     Optional<llvm::APSInt> LHSValue = LHS->getIntegerConstantExpr(S.Context);
11242 
11243     // We don't care about expressions whose result is a constant.
11244     if (RHSValue && LHSValue)
11245       return AnalyzeImpConvsInComparison(S, E);
11246 
11247     // We only care about expressions where just one side is literal
11248     if ((bool)RHSValue ^ (bool)LHSValue) {
11249       // Is the constant on the RHS or LHS?
11250       const bool RhsConstant = (bool)RHSValue;
11251       Expr *Const = RhsConstant ? RHS : LHS;
11252       Expr *Other = RhsConstant ? LHS : RHS;
11253       const llvm::APSInt &Value = RhsConstant ? *RHSValue : *LHSValue;
11254 
11255       // Check whether an integer constant comparison results in a value
11256       // of 'true' or 'false'.
11257       if (CheckTautologicalComparison(S, E, Const, Other, Value, RhsConstant))
11258         return AnalyzeImpConvsInComparison(S, E);
11259     }
11260   }
11261 
11262   if (!T->hasUnsignedIntegerRepresentation()) {
11263     // We don't do anything special if this isn't an unsigned integral
11264     // comparison:  we're only interested in integral comparisons, and
11265     // signed comparisons only happen in cases we don't care to warn about.
11266     return AnalyzeImpConvsInComparison(S, E);
11267   }
11268 
11269   LHS = LHS->IgnoreParenImpCasts();
11270   RHS = RHS->IgnoreParenImpCasts();
11271 
11272   if (!S.getLangOpts().CPlusPlus) {
11273     // Avoid warning about comparison of integers with different signs when
11274     // RHS/LHS has a `typeof(E)` type whose sign is different from the sign of
11275     // the type of `E`.
11276     if (const auto *TET = dyn_cast<TypeOfExprType>(LHS->getType()))
11277       LHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11278     if (const auto *TET = dyn_cast<TypeOfExprType>(RHS->getType()))
11279       RHS = TET->getUnderlyingExpr()->IgnoreParenImpCasts();
11280   }
11281 
11282   // Check to see if one of the (unmodified) operands is of different
11283   // signedness.
11284   Expr *signedOperand, *unsignedOperand;
11285   if (LHS->getType()->hasSignedIntegerRepresentation()) {
11286     assert(!RHS->getType()->hasSignedIntegerRepresentation() &&
11287            "unsigned comparison between two signed integer expressions?");
11288     signedOperand = LHS;
11289     unsignedOperand = RHS;
11290   } else if (RHS->getType()->hasSignedIntegerRepresentation()) {
11291     signedOperand = RHS;
11292     unsignedOperand = LHS;
11293   } else {
11294     return AnalyzeImpConvsInComparison(S, E);
11295   }
11296 
11297   // Otherwise, calculate the effective range of the signed operand.
11298   IntRange signedRange = GetExprRange(
11299       S.Context, signedOperand, S.isConstantEvaluated(), /*Approximate*/ true);
11300 
11301   // Go ahead and analyze implicit conversions in the operands.  Note
11302   // that we skip the implicit conversions on both sides.
11303   AnalyzeImplicitConversions(S, LHS, E->getOperatorLoc());
11304   AnalyzeImplicitConversions(S, RHS, E->getOperatorLoc());
11305 
11306   // If the signed range is non-negative, -Wsign-compare won't fire.
11307   if (signedRange.NonNegative)
11308     return;
11309 
11310   // For (in)equality comparisons, if the unsigned operand is a
11311   // constant which cannot collide with a overflowed signed operand,
11312   // then reinterpreting the signed operand as unsigned will not
11313   // change the result of the comparison.
11314   if (E->isEqualityOp()) {
11315     unsigned comparisonWidth = S.Context.getIntWidth(T);
11316     IntRange unsignedRange =
11317         GetExprRange(S.Context, unsignedOperand, S.isConstantEvaluated(),
11318                      /*Approximate*/ true);
11319 
11320     // We should never be unable to prove that the unsigned operand is
11321     // non-negative.
11322     assert(unsignedRange.NonNegative && "unsigned range includes negative?");
11323 
11324     if (unsignedRange.Width < comparisonWidth)
11325       return;
11326   }
11327 
11328   S.DiagRuntimeBehavior(E->getOperatorLoc(), E,
11329                         S.PDiag(diag::warn_mixed_sign_comparison)
11330                             << LHS->getType() << RHS->getType()
11331                             << LHS->getSourceRange() << RHS->getSourceRange());
11332 }
11333 
11334 /// Analyzes an attempt to assign the given value to a bitfield.
11335 ///
11336 /// Returns true if there was something fishy about the attempt.
11337 static bool AnalyzeBitFieldAssignment(Sema &S, FieldDecl *Bitfield, Expr *Init,
11338                                       SourceLocation InitLoc) {
11339   assert(Bitfield->isBitField());
11340   if (Bitfield->isInvalidDecl())
11341     return false;
11342 
11343   // White-list bool bitfields.
11344   QualType BitfieldType = Bitfield->getType();
11345   if (BitfieldType->isBooleanType())
11346      return false;
11347 
11348   if (BitfieldType->isEnumeralType()) {
11349     EnumDecl *BitfieldEnumDecl = BitfieldType->castAs<EnumType>()->getDecl();
11350     // If the underlying enum type was not explicitly specified as an unsigned
11351     // type and the enum contain only positive values, MSVC++ will cause an
11352     // inconsistency by storing this as a signed type.
11353     if (S.getLangOpts().CPlusPlus11 &&
11354         !BitfieldEnumDecl->getIntegerTypeSourceInfo() &&
11355         BitfieldEnumDecl->getNumPositiveBits() > 0 &&
11356         BitfieldEnumDecl->getNumNegativeBits() == 0) {
11357       S.Diag(InitLoc, diag::warn_no_underlying_type_specified_for_enum_bitfield)
11358           << BitfieldEnumDecl;
11359     }
11360   }
11361 
11362   if (Bitfield->getType()->isBooleanType())
11363     return false;
11364 
11365   // Ignore value- or type-dependent expressions.
11366   if (Bitfield->getBitWidth()->isValueDependent() ||
11367       Bitfield->getBitWidth()->isTypeDependent() ||
11368       Init->isValueDependent() ||
11369       Init->isTypeDependent())
11370     return false;
11371 
11372   Expr *OriginalInit = Init->IgnoreParenImpCasts();
11373   unsigned FieldWidth = Bitfield->getBitWidthValue(S.Context);
11374 
11375   Expr::EvalResult Result;
11376   if (!OriginalInit->EvaluateAsInt(Result, S.Context,
11377                                    Expr::SE_AllowSideEffects)) {
11378     // The RHS is not constant.  If the RHS has an enum type, make sure the
11379     // bitfield is wide enough to hold all the values of the enum without
11380     // truncation.
11381     if (const auto *EnumTy = OriginalInit->getType()->getAs<EnumType>()) {
11382       EnumDecl *ED = EnumTy->getDecl();
11383       bool SignedBitfield = BitfieldType->isSignedIntegerType();
11384 
11385       // Enum types are implicitly signed on Windows, so check if there are any
11386       // negative enumerators to see if the enum was intended to be signed or
11387       // not.
11388       bool SignedEnum = ED->getNumNegativeBits() > 0;
11389 
11390       // Check for surprising sign changes when assigning enum values to a
11391       // bitfield of different signedness.  If the bitfield is signed and we
11392       // have exactly the right number of bits to store this unsigned enum,
11393       // suggest changing the enum to an unsigned type. This typically happens
11394       // on Windows where unfixed enums always use an underlying type of 'int'.
11395       unsigned DiagID = 0;
11396       if (SignedEnum && !SignedBitfield) {
11397         DiagID = diag::warn_unsigned_bitfield_assigned_signed_enum;
11398       } else if (SignedBitfield && !SignedEnum &&
11399                  ED->getNumPositiveBits() == FieldWidth) {
11400         DiagID = diag::warn_signed_bitfield_enum_conversion;
11401       }
11402 
11403       if (DiagID) {
11404         S.Diag(InitLoc, DiagID) << Bitfield << ED;
11405         TypeSourceInfo *TSI = Bitfield->getTypeSourceInfo();
11406         SourceRange TypeRange =
11407             TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange();
11408         S.Diag(Bitfield->getTypeSpecStartLoc(), diag::note_change_bitfield_sign)
11409             << SignedEnum << TypeRange;
11410       }
11411 
11412       // Compute the required bitwidth. If the enum has negative values, we need
11413       // one more bit than the normal number of positive bits to represent the
11414       // sign bit.
11415       unsigned BitsNeeded = SignedEnum ? std::max(ED->getNumPositiveBits() + 1,
11416                                                   ED->getNumNegativeBits())
11417                                        : ED->getNumPositiveBits();
11418 
11419       // Check the bitwidth.
11420       if (BitsNeeded > FieldWidth) {
11421         Expr *WidthExpr = Bitfield->getBitWidth();
11422         S.Diag(InitLoc, diag::warn_bitfield_too_small_for_enum)
11423             << Bitfield << ED;
11424         S.Diag(WidthExpr->getExprLoc(), diag::note_widen_bitfield)
11425             << BitsNeeded << ED << WidthExpr->getSourceRange();
11426       }
11427     }
11428 
11429     return false;
11430   }
11431 
11432   llvm::APSInt Value = Result.Val.getInt();
11433 
11434   unsigned OriginalWidth = Value.getBitWidth();
11435 
11436   if (!Value.isSigned() || Value.isNegative())
11437     if (UnaryOperator *UO = dyn_cast<UnaryOperator>(OriginalInit))
11438       if (UO->getOpcode() == UO_Minus || UO->getOpcode() == UO_Not)
11439         OriginalWidth = Value.getMinSignedBits();
11440 
11441   if (OriginalWidth <= FieldWidth)
11442     return false;
11443 
11444   // Compute the value which the bitfield will contain.
11445   llvm::APSInt TruncatedValue = Value.trunc(FieldWidth);
11446   TruncatedValue.setIsSigned(BitfieldType->isSignedIntegerType());
11447 
11448   // Check whether the stored value is equal to the original value.
11449   TruncatedValue = TruncatedValue.extend(OriginalWidth);
11450   if (llvm::APSInt::isSameValue(Value, TruncatedValue))
11451     return false;
11452 
11453   // Special-case bitfields of width 1: booleans are naturally 0/1, and
11454   // therefore don't strictly fit into a signed bitfield of width 1.
11455   if (FieldWidth == 1 && Value == 1)
11456     return false;
11457 
11458   std::string PrettyValue = Value.toString(10);
11459   std::string PrettyTrunc = TruncatedValue.toString(10);
11460 
11461   S.Diag(InitLoc, diag::warn_impcast_bitfield_precision_constant)
11462     << PrettyValue << PrettyTrunc << OriginalInit->getType()
11463     << Init->getSourceRange();
11464 
11465   return true;
11466 }
11467 
11468 /// Analyze the given simple or compound assignment for warning-worthy
11469 /// operations.
11470 static void AnalyzeAssignment(Sema &S, BinaryOperator *E) {
11471   // Just recurse on the LHS.
11472   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11473 
11474   // We want to recurse on the RHS as normal unless we're assigning to
11475   // a bitfield.
11476   if (FieldDecl *Bitfield = E->getLHS()->getSourceBitField()) {
11477     if (AnalyzeBitFieldAssignment(S, Bitfield, E->getRHS(),
11478                                   E->getOperatorLoc())) {
11479       // Recurse, ignoring any implicit conversions on the RHS.
11480       return AnalyzeImplicitConversions(S, E->getRHS()->IgnoreParenImpCasts(),
11481                                         E->getOperatorLoc());
11482     }
11483   }
11484 
11485   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11486 
11487   // Diagnose implicitly sequentially-consistent atomic assignment.
11488   if (E->getLHS()->getType()->isAtomicType())
11489     S.Diag(E->getRHS()->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
11490 }
11491 
11492 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11493 static void DiagnoseImpCast(Sema &S, Expr *E, QualType SourceType, QualType T,
11494                             SourceLocation CContext, unsigned diag,
11495                             bool pruneControlFlow = false) {
11496   if (pruneControlFlow) {
11497     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11498                           S.PDiag(diag)
11499                               << SourceType << T << E->getSourceRange()
11500                               << SourceRange(CContext));
11501     return;
11502   }
11503   S.Diag(E->getExprLoc(), diag)
11504     << SourceType << T << E->getSourceRange() << SourceRange(CContext);
11505 }
11506 
11507 /// Diagnose an implicit cast;  purely a helper for CheckImplicitConversion.
11508 static void DiagnoseImpCast(Sema &S, Expr *E, QualType T,
11509                             SourceLocation CContext,
11510                             unsigned diag, bool pruneControlFlow = false) {
11511   DiagnoseImpCast(S, E, E->getType(), T, CContext, diag, pruneControlFlow);
11512 }
11513 
11514 static bool isObjCSignedCharBool(Sema &S, QualType Ty) {
11515   return Ty->isSpecificBuiltinType(BuiltinType::SChar) &&
11516       S.getLangOpts().ObjC && S.NSAPIObj->isObjCBOOLType(Ty);
11517 }
11518 
11519 static void adornObjCBoolConversionDiagWithTernaryFixit(
11520     Sema &S, Expr *SourceExpr, const Sema::SemaDiagnosticBuilder &Builder) {
11521   Expr *Ignored = SourceExpr->IgnoreImplicit();
11522   if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Ignored))
11523     Ignored = OVE->getSourceExpr();
11524   bool NeedsParens = isa<AbstractConditionalOperator>(Ignored) ||
11525                      isa<BinaryOperator>(Ignored) ||
11526                      isa<CXXOperatorCallExpr>(Ignored);
11527   SourceLocation EndLoc = S.getLocForEndOfToken(SourceExpr->getEndLoc());
11528   if (NeedsParens)
11529     Builder << FixItHint::CreateInsertion(SourceExpr->getBeginLoc(), "(")
11530             << FixItHint::CreateInsertion(EndLoc, ")");
11531   Builder << FixItHint::CreateInsertion(EndLoc, " ? YES : NO");
11532 }
11533 
11534 /// Diagnose an implicit cast from a floating point value to an integer value.
11535 static void DiagnoseFloatingImpCast(Sema &S, Expr *E, QualType T,
11536                                     SourceLocation CContext) {
11537   const bool IsBool = T->isSpecificBuiltinType(BuiltinType::Bool);
11538   const bool PruneWarnings = S.inTemplateInstantiation();
11539 
11540   Expr *InnerE = E->IgnoreParenImpCasts();
11541   // We also want to warn on, e.g., "int i = -1.234"
11542   if (UnaryOperator *UOp = dyn_cast<UnaryOperator>(InnerE))
11543     if (UOp->getOpcode() == UO_Minus || UOp->getOpcode() == UO_Plus)
11544       InnerE = UOp->getSubExpr()->IgnoreParenImpCasts();
11545 
11546   const bool IsLiteral =
11547       isa<FloatingLiteral>(E) || isa<FloatingLiteral>(InnerE);
11548 
11549   llvm::APFloat Value(0.0);
11550   bool IsConstant =
11551     E->EvaluateAsFloat(Value, S.Context, Expr::SE_AllowSideEffects);
11552   if (!IsConstant) {
11553     if (isObjCSignedCharBool(S, T)) {
11554       return adornObjCBoolConversionDiagWithTernaryFixit(
11555           S, E,
11556           S.Diag(CContext, diag::warn_impcast_float_to_objc_signed_char_bool)
11557               << E->getType());
11558     }
11559 
11560     return DiagnoseImpCast(S, E, T, CContext,
11561                            diag::warn_impcast_float_integer, PruneWarnings);
11562   }
11563 
11564   bool isExact = false;
11565 
11566   llvm::APSInt IntegerValue(S.Context.getIntWidth(T),
11567                             T->hasUnsignedIntegerRepresentation());
11568   llvm::APFloat::opStatus Result = Value.convertToInteger(
11569       IntegerValue, llvm::APFloat::rmTowardZero, &isExact);
11570 
11571   // FIXME: Force the precision of the source value down so we don't print
11572   // digits which are usually useless (we don't really care here if we
11573   // truncate a digit by accident in edge cases).  Ideally, APFloat::toString
11574   // would automatically print the shortest representation, but it's a bit
11575   // tricky to implement.
11576   SmallString<16> PrettySourceValue;
11577   unsigned precision = llvm::APFloat::semanticsPrecision(Value.getSemantics());
11578   precision = (precision * 59 + 195) / 196;
11579   Value.toString(PrettySourceValue, precision);
11580 
11581   if (isObjCSignedCharBool(S, T) && IntegerValue != 0 && IntegerValue != 1) {
11582     return adornObjCBoolConversionDiagWithTernaryFixit(
11583         S, E,
11584         S.Diag(CContext, diag::warn_impcast_constant_value_to_objc_bool)
11585             << PrettySourceValue);
11586   }
11587 
11588   if (Result == llvm::APFloat::opOK && isExact) {
11589     if (IsLiteral) return;
11590     return DiagnoseImpCast(S, E, T, CContext, diag::warn_impcast_float_integer,
11591                            PruneWarnings);
11592   }
11593 
11594   // Conversion of a floating-point value to a non-bool integer where the
11595   // integral part cannot be represented by the integer type is undefined.
11596   if (!IsBool && Result == llvm::APFloat::opInvalidOp)
11597     return DiagnoseImpCast(
11598         S, E, T, CContext,
11599         IsLiteral ? diag::warn_impcast_literal_float_to_integer_out_of_range
11600                   : diag::warn_impcast_float_to_integer_out_of_range,
11601         PruneWarnings);
11602 
11603   unsigned DiagID = 0;
11604   if (IsLiteral) {
11605     // Warn on floating point literal to integer.
11606     DiagID = diag::warn_impcast_literal_float_to_integer;
11607   } else if (IntegerValue == 0) {
11608     if (Value.isZero()) {  // Skip -0.0 to 0 conversion.
11609       return DiagnoseImpCast(S, E, T, CContext,
11610                              diag::warn_impcast_float_integer, PruneWarnings);
11611     }
11612     // Warn on non-zero to zero conversion.
11613     DiagID = diag::warn_impcast_float_to_integer_zero;
11614   } else {
11615     if (IntegerValue.isUnsigned()) {
11616       if (!IntegerValue.isMaxValue()) {
11617         return DiagnoseImpCast(S, E, T, CContext,
11618                                diag::warn_impcast_float_integer, PruneWarnings);
11619       }
11620     } else {  // IntegerValue.isSigned()
11621       if (!IntegerValue.isMaxSignedValue() &&
11622           !IntegerValue.isMinSignedValue()) {
11623         return DiagnoseImpCast(S, E, T, CContext,
11624                                diag::warn_impcast_float_integer, PruneWarnings);
11625       }
11626     }
11627     // Warn on evaluatable floating point expression to integer conversion.
11628     DiagID = diag::warn_impcast_float_to_integer;
11629   }
11630 
11631   SmallString<16> PrettyTargetValue;
11632   if (IsBool)
11633     PrettyTargetValue = Value.isZero() ? "false" : "true";
11634   else
11635     IntegerValue.toString(PrettyTargetValue);
11636 
11637   if (PruneWarnings) {
11638     S.DiagRuntimeBehavior(E->getExprLoc(), E,
11639                           S.PDiag(DiagID)
11640                               << E->getType() << T.getUnqualifiedType()
11641                               << PrettySourceValue << PrettyTargetValue
11642                               << E->getSourceRange() << SourceRange(CContext));
11643   } else {
11644     S.Diag(E->getExprLoc(), DiagID)
11645         << E->getType() << T.getUnqualifiedType() << PrettySourceValue
11646         << PrettyTargetValue << E->getSourceRange() << SourceRange(CContext);
11647   }
11648 }
11649 
11650 /// Analyze the given compound assignment for the possible losing of
11651 /// floating-point precision.
11652 static void AnalyzeCompoundAssignment(Sema &S, BinaryOperator *E) {
11653   assert(isa<CompoundAssignOperator>(E) &&
11654          "Must be compound assignment operation");
11655   // Recurse on the LHS and RHS in here
11656   AnalyzeImplicitConversions(S, E->getLHS(), E->getOperatorLoc());
11657   AnalyzeImplicitConversions(S, E->getRHS(), E->getOperatorLoc());
11658 
11659   if (E->getLHS()->getType()->isAtomicType())
11660     S.Diag(E->getOperatorLoc(), diag::warn_atomic_implicit_seq_cst);
11661 
11662   // Now check the outermost expression
11663   const auto *ResultBT = E->getLHS()->getType()->getAs<BuiltinType>();
11664   const auto *RBT = cast<CompoundAssignOperator>(E)
11665                         ->getComputationResultType()
11666                         ->getAs<BuiltinType>();
11667 
11668   // The below checks assume source is floating point.
11669   if (!ResultBT || !RBT || !RBT->isFloatingPoint()) return;
11670 
11671   // If source is floating point but target is an integer.
11672   if (ResultBT->isInteger())
11673     return DiagnoseImpCast(S, E, E->getRHS()->getType(), E->getLHS()->getType(),
11674                            E->getExprLoc(), diag::warn_impcast_float_integer);
11675 
11676   if (!ResultBT->isFloatingPoint())
11677     return;
11678 
11679   // If both source and target are floating points, warn about losing precision.
11680   int Order = S.getASTContext().getFloatingTypeSemanticOrder(
11681       QualType(ResultBT, 0), QualType(RBT, 0));
11682   if (Order < 0 && !S.SourceMgr.isInSystemMacro(E->getOperatorLoc()))
11683     // warn about dropping FP rank.
11684     DiagnoseImpCast(S, E->getRHS(), E->getLHS()->getType(), E->getOperatorLoc(),
11685                     diag::warn_impcast_float_result_precision);
11686 }
11687 
11688 static std::string PrettyPrintInRange(const llvm::APSInt &Value,
11689                                       IntRange Range) {
11690   if (!Range.Width) return "0";
11691 
11692   llvm::APSInt ValueInRange = Value;
11693   ValueInRange.setIsSigned(!Range.NonNegative);
11694   ValueInRange = ValueInRange.trunc(Range.Width);
11695   return ValueInRange.toString(10);
11696 }
11697 
11698 static bool IsImplicitBoolFloatConversion(Sema &S, Expr *Ex, bool ToBool) {
11699   if (!isa<ImplicitCastExpr>(Ex))
11700     return false;
11701 
11702   Expr *InnerE = Ex->IgnoreParenImpCasts();
11703   const Type *Target = S.Context.getCanonicalType(Ex->getType()).getTypePtr();
11704   const Type *Source =
11705     S.Context.getCanonicalType(InnerE->getType()).getTypePtr();
11706   if (Target->isDependentType())
11707     return false;
11708 
11709   const BuiltinType *FloatCandidateBT =
11710     dyn_cast<BuiltinType>(ToBool ? Source : Target);
11711   const Type *BoolCandidateType = ToBool ? Target : Source;
11712 
11713   return (BoolCandidateType->isSpecificBuiltinType(BuiltinType::Bool) &&
11714           FloatCandidateBT && (FloatCandidateBT->isFloatingPoint()));
11715 }
11716 
11717 static void CheckImplicitArgumentConversions(Sema &S, CallExpr *TheCall,
11718                                              SourceLocation CC) {
11719   unsigned NumArgs = TheCall->getNumArgs();
11720   for (unsigned i = 0; i < NumArgs; ++i) {
11721     Expr *CurrA = TheCall->getArg(i);
11722     if (!IsImplicitBoolFloatConversion(S, CurrA, true))
11723       continue;
11724 
11725     bool IsSwapped = ((i > 0) &&
11726         IsImplicitBoolFloatConversion(S, TheCall->getArg(i - 1), false));
11727     IsSwapped |= ((i < (NumArgs - 1)) &&
11728         IsImplicitBoolFloatConversion(S, TheCall->getArg(i + 1), false));
11729     if (IsSwapped) {
11730       // Warn on this floating-point to bool conversion.
11731       DiagnoseImpCast(S, CurrA->IgnoreParenImpCasts(),
11732                       CurrA->getType(), CC,
11733                       diag::warn_impcast_floating_point_to_bool);
11734     }
11735   }
11736 }
11737 
11738 static void DiagnoseNullConversion(Sema &S, Expr *E, QualType T,
11739                                    SourceLocation CC) {
11740   if (S.Diags.isIgnored(diag::warn_impcast_null_pointer_to_integer,
11741                         E->getExprLoc()))
11742     return;
11743 
11744   // Don't warn on functions which have return type nullptr_t.
11745   if (isa<CallExpr>(E))
11746     return;
11747 
11748   // Check for NULL (GNUNull) or nullptr (CXX11_nullptr).
11749   const Expr::NullPointerConstantKind NullKind =
11750       E->isNullPointerConstant(S.Context, Expr::NPC_ValueDependentIsNotNull);
11751   if (NullKind != Expr::NPCK_GNUNull && NullKind != Expr::NPCK_CXX11_nullptr)
11752     return;
11753 
11754   // Return if target type is a safe conversion.
11755   if (T->isAnyPointerType() || T->isBlockPointerType() ||
11756       T->isMemberPointerType() || !T->isScalarType() || T->isNullPtrType())
11757     return;
11758 
11759   SourceLocation Loc = E->getSourceRange().getBegin();
11760 
11761   // Venture through the macro stacks to get to the source of macro arguments.
11762   // The new location is a better location than the complete location that was
11763   // passed in.
11764   Loc = S.SourceMgr.getTopMacroCallerLoc(Loc);
11765   CC = S.SourceMgr.getTopMacroCallerLoc(CC);
11766 
11767   // __null is usually wrapped in a macro.  Go up a macro if that is the case.
11768   if (NullKind == Expr::NPCK_GNUNull && Loc.isMacroID()) {
11769     StringRef MacroName = Lexer::getImmediateMacroNameForDiagnostics(
11770         Loc, S.SourceMgr, S.getLangOpts());
11771     if (MacroName == "NULL")
11772       Loc = S.SourceMgr.getImmediateExpansionRange(Loc).getBegin();
11773   }
11774 
11775   // Only warn if the null and context location are in the same macro expansion.
11776   if (S.SourceMgr.getFileID(Loc) != S.SourceMgr.getFileID(CC))
11777     return;
11778 
11779   S.Diag(Loc, diag::warn_impcast_null_pointer_to_integer)
11780       << (NullKind == Expr::NPCK_CXX11_nullptr) << T << SourceRange(CC)
11781       << FixItHint::CreateReplacement(Loc,
11782                                       S.getFixItZeroLiteralForType(T, Loc));
11783 }
11784 
11785 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11786                                   ObjCArrayLiteral *ArrayLiteral);
11787 
11788 static void
11789 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11790                            ObjCDictionaryLiteral *DictionaryLiteral);
11791 
11792 /// Check a single element within a collection literal against the
11793 /// target element type.
11794 static void checkObjCCollectionLiteralElement(Sema &S,
11795                                               QualType TargetElementType,
11796                                               Expr *Element,
11797                                               unsigned ElementKind) {
11798   // Skip a bitcast to 'id' or qualified 'id'.
11799   if (auto ICE = dyn_cast<ImplicitCastExpr>(Element)) {
11800     if (ICE->getCastKind() == CK_BitCast &&
11801         ICE->getSubExpr()->getType()->getAs<ObjCObjectPointerType>())
11802       Element = ICE->getSubExpr();
11803   }
11804 
11805   QualType ElementType = Element->getType();
11806   ExprResult ElementResult(Element);
11807   if (ElementType->getAs<ObjCObjectPointerType>() &&
11808       S.CheckSingleAssignmentConstraints(TargetElementType,
11809                                          ElementResult,
11810                                          false, false)
11811         != Sema::Compatible) {
11812     S.Diag(Element->getBeginLoc(), diag::warn_objc_collection_literal_element)
11813         << ElementType << ElementKind << TargetElementType
11814         << Element->getSourceRange();
11815   }
11816 
11817   if (auto ArrayLiteral = dyn_cast<ObjCArrayLiteral>(Element))
11818     checkObjCArrayLiteral(S, TargetElementType, ArrayLiteral);
11819   else if (auto DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(Element))
11820     checkObjCDictionaryLiteral(S, TargetElementType, DictionaryLiteral);
11821 }
11822 
11823 /// Check an Objective-C array literal being converted to the given
11824 /// target type.
11825 static void checkObjCArrayLiteral(Sema &S, QualType TargetType,
11826                                   ObjCArrayLiteral *ArrayLiteral) {
11827   if (!S.NSArrayDecl)
11828     return;
11829 
11830   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11831   if (!TargetObjCPtr)
11832     return;
11833 
11834   if (TargetObjCPtr->isUnspecialized() ||
11835       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11836         != S.NSArrayDecl->getCanonicalDecl())
11837     return;
11838 
11839   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11840   if (TypeArgs.size() != 1)
11841     return;
11842 
11843   QualType TargetElementType = TypeArgs[0];
11844   for (unsigned I = 0, N = ArrayLiteral->getNumElements(); I != N; ++I) {
11845     checkObjCCollectionLiteralElement(S, TargetElementType,
11846                                       ArrayLiteral->getElement(I),
11847                                       0);
11848   }
11849 }
11850 
11851 /// Check an Objective-C dictionary literal being converted to the given
11852 /// target type.
11853 static void
11854 checkObjCDictionaryLiteral(Sema &S, QualType TargetType,
11855                            ObjCDictionaryLiteral *DictionaryLiteral) {
11856   if (!S.NSDictionaryDecl)
11857     return;
11858 
11859   const auto *TargetObjCPtr = TargetType->getAs<ObjCObjectPointerType>();
11860   if (!TargetObjCPtr)
11861     return;
11862 
11863   if (TargetObjCPtr->isUnspecialized() ||
11864       TargetObjCPtr->getInterfaceDecl()->getCanonicalDecl()
11865         != S.NSDictionaryDecl->getCanonicalDecl())
11866     return;
11867 
11868   auto TypeArgs = TargetObjCPtr->getTypeArgs();
11869   if (TypeArgs.size() != 2)
11870     return;
11871 
11872   QualType TargetKeyType = TypeArgs[0];
11873   QualType TargetObjectType = TypeArgs[1];
11874   for (unsigned I = 0, N = DictionaryLiteral->getNumElements(); I != N; ++I) {
11875     auto Element = DictionaryLiteral->getKeyValueElement(I);
11876     checkObjCCollectionLiteralElement(S, TargetKeyType, Element.Key, 1);
11877     checkObjCCollectionLiteralElement(S, TargetObjectType, Element.Value, 2);
11878   }
11879 }
11880 
11881 // Helper function to filter out cases for constant width constant conversion.
11882 // Don't warn on char array initialization or for non-decimal values.
11883 static bool isSameWidthConstantConversion(Sema &S, Expr *E, QualType T,
11884                                           SourceLocation CC) {
11885   // If initializing from a constant, and the constant starts with '0',
11886   // then it is a binary, octal, or hexadecimal.  Allow these constants
11887   // to fill all the bits, even if there is a sign change.
11888   if (auto *IntLit = dyn_cast<IntegerLiteral>(E->IgnoreParenImpCasts())) {
11889     const char FirstLiteralCharacter =
11890         S.getSourceManager().getCharacterData(IntLit->getBeginLoc())[0];
11891     if (FirstLiteralCharacter == '0')
11892       return false;
11893   }
11894 
11895   // If the CC location points to a '{', and the type is char, then assume
11896   // assume it is an array initialization.
11897   if (CC.isValid() && T->isCharType()) {
11898     const char FirstContextCharacter =
11899         S.getSourceManager().getCharacterData(CC)[0];
11900     if (FirstContextCharacter == '{')
11901       return false;
11902   }
11903 
11904   return true;
11905 }
11906 
11907 static const IntegerLiteral *getIntegerLiteral(Expr *E) {
11908   const auto *IL = dyn_cast<IntegerLiteral>(E);
11909   if (!IL) {
11910     if (auto *UO = dyn_cast<UnaryOperator>(E)) {
11911       if (UO->getOpcode() == UO_Minus)
11912         return dyn_cast<IntegerLiteral>(UO->getSubExpr());
11913     }
11914   }
11915 
11916   return IL;
11917 }
11918 
11919 static void DiagnoseIntInBoolContext(Sema &S, Expr *E) {
11920   E = E->IgnoreParenImpCasts();
11921   SourceLocation ExprLoc = E->getExprLoc();
11922 
11923   if (const auto *BO = dyn_cast<BinaryOperator>(E)) {
11924     BinaryOperator::Opcode Opc = BO->getOpcode();
11925     Expr::EvalResult Result;
11926     // Do not diagnose unsigned shifts.
11927     if (Opc == BO_Shl) {
11928       const auto *LHS = getIntegerLiteral(BO->getLHS());
11929       const auto *RHS = getIntegerLiteral(BO->getRHS());
11930       if (LHS && LHS->getValue() == 0)
11931         S.Diag(ExprLoc, diag::warn_left_shift_always) << 0;
11932       else if (!E->isValueDependent() && LHS && RHS &&
11933                RHS->getValue().isNonNegative() &&
11934                E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects))
11935         S.Diag(ExprLoc, diag::warn_left_shift_always)
11936             << (Result.Val.getInt() != 0);
11937       else if (E->getType()->isSignedIntegerType())
11938         S.Diag(ExprLoc, diag::warn_left_shift_in_bool_context) << E;
11939     }
11940   }
11941 
11942   if (const auto *CO = dyn_cast<ConditionalOperator>(E)) {
11943     const auto *LHS = getIntegerLiteral(CO->getTrueExpr());
11944     const auto *RHS = getIntegerLiteral(CO->getFalseExpr());
11945     if (!LHS || !RHS)
11946       return;
11947     if ((LHS->getValue() == 0 || LHS->getValue() == 1) &&
11948         (RHS->getValue() == 0 || RHS->getValue() == 1))
11949       // Do not diagnose common idioms.
11950       return;
11951     if (LHS->getValue() != 0 && RHS->getValue() != 0)
11952       S.Diag(ExprLoc, diag::warn_integer_constants_in_conditional_always_true);
11953   }
11954 }
11955 
11956 static void CheckImplicitConversion(Sema &S, Expr *E, QualType T,
11957                                     SourceLocation CC,
11958                                     bool *ICContext = nullptr,
11959                                     bool IsListInit = false) {
11960   if (E->isTypeDependent() || E->isValueDependent()) return;
11961 
11962   const Type *Source = S.Context.getCanonicalType(E->getType()).getTypePtr();
11963   const Type *Target = S.Context.getCanonicalType(T).getTypePtr();
11964   if (Source == Target) return;
11965   if (Target->isDependentType()) return;
11966 
11967   // If the conversion context location is invalid don't complain. We also
11968   // don't want to emit a warning if the issue occurs from the expansion of
11969   // a system macro. The problem is that 'getSpellingLoc()' is slow, so we
11970   // delay this check as long as possible. Once we detect we are in that
11971   // scenario, we just return.
11972   if (CC.isInvalid())
11973     return;
11974 
11975   if (Source->isAtomicType())
11976     S.Diag(E->getExprLoc(), diag::warn_atomic_implicit_seq_cst);
11977 
11978   // Diagnose implicit casts to bool.
11979   if (Target->isSpecificBuiltinType(BuiltinType::Bool)) {
11980     if (isa<StringLiteral>(E))
11981       // Warn on string literal to bool.  Checks for string literals in logical
11982       // and expressions, for instance, assert(0 && "error here"), are
11983       // prevented by a check in AnalyzeImplicitConversions().
11984       return DiagnoseImpCast(S, E, T, CC,
11985                              diag::warn_impcast_string_literal_to_bool);
11986     if (isa<ObjCStringLiteral>(E) || isa<ObjCArrayLiteral>(E) ||
11987         isa<ObjCDictionaryLiteral>(E) || isa<ObjCBoxedExpr>(E)) {
11988       // This covers the literal expressions that evaluate to Objective-C
11989       // objects.
11990       return DiagnoseImpCast(S, E, T, CC,
11991                              diag::warn_impcast_objective_c_literal_to_bool);
11992     }
11993     if (Source->isPointerType() || Source->canDecayToPointerType()) {
11994       // Warn on pointer to bool conversion that is always true.
11995       S.DiagnoseAlwaysNonNullPointer(E, Expr::NPCK_NotNull, /*IsEqual*/ false,
11996                                      SourceRange(CC));
11997     }
11998   }
11999 
12000   // If the we're converting a constant to an ObjC BOOL on a platform where BOOL
12001   // is a typedef for signed char (macOS), then that constant value has to be 1
12002   // or 0.
12003   if (isObjCSignedCharBool(S, T) && Source->isIntegralType(S.Context)) {
12004     Expr::EvalResult Result;
12005     if (E->EvaluateAsInt(Result, S.getASTContext(),
12006                          Expr::SE_AllowSideEffects)) {
12007       if (Result.Val.getInt() != 1 && Result.Val.getInt() != 0) {
12008         adornObjCBoolConversionDiagWithTernaryFixit(
12009             S, E,
12010             S.Diag(CC, diag::warn_impcast_constant_value_to_objc_bool)
12011                 << Result.Val.getInt().toString(10));
12012       }
12013       return;
12014     }
12015   }
12016 
12017   // Check implicit casts from Objective-C collection literals to specialized
12018   // collection types, e.g., NSArray<NSString *> *.
12019   if (auto *ArrayLiteral = dyn_cast<ObjCArrayLiteral>(E))
12020     checkObjCArrayLiteral(S, QualType(Target, 0), ArrayLiteral);
12021   else if (auto *DictionaryLiteral = dyn_cast<ObjCDictionaryLiteral>(E))
12022     checkObjCDictionaryLiteral(S, QualType(Target, 0), DictionaryLiteral);
12023 
12024   // Strip vector types.
12025   if (isa<VectorType>(Source)) {
12026     if (!isa<VectorType>(Target)) {
12027       if (S.SourceMgr.isInSystemMacro(CC))
12028         return;
12029       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_vector_scalar);
12030     }
12031 
12032     // If the vector cast is cast between two vectors of the same size, it is
12033     // a bitcast, not a conversion.
12034     if (S.Context.getTypeSize(Source) == S.Context.getTypeSize(Target))
12035       return;
12036 
12037     Source = cast<VectorType>(Source)->getElementType().getTypePtr();
12038     Target = cast<VectorType>(Target)->getElementType().getTypePtr();
12039   }
12040   if (auto VecTy = dyn_cast<VectorType>(Target))
12041     Target = VecTy->getElementType().getTypePtr();
12042 
12043   // Strip complex types.
12044   if (isa<ComplexType>(Source)) {
12045     if (!isa<ComplexType>(Target)) {
12046       if (S.SourceMgr.isInSystemMacro(CC) || Target->isBooleanType())
12047         return;
12048 
12049       return DiagnoseImpCast(S, E, T, CC,
12050                              S.getLangOpts().CPlusPlus
12051                                  ? diag::err_impcast_complex_scalar
12052                                  : diag::warn_impcast_complex_scalar);
12053     }
12054 
12055     Source = cast<ComplexType>(Source)->getElementType().getTypePtr();
12056     Target = cast<ComplexType>(Target)->getElementType().getTypePtr();
12057   }
12058 
12059   const BuiltinType *SourceBT = dyn_cast<BuiltinType>(Source);
12060   const BuiltinType *TargetBT = dyn_cast<BuiltinType>(Target);
12061 
12062   // If the source is floating point...
12063   if (SourceBT && SourceBT->isFloatingPoint()) {
12064     // ...and the target is floating point...
12065     if (TargetBT && TargetBT->isFloatingPoint()) {
12066       // ...then warn if we're dropping FP rank.
12067 
12068       int Order = S.getASTContext().getFloatingTypeSemanticOrder(
12069           QualType(SourceBT, 0), QualType(TargetBT, 0));
12070       if (Order > 0) {
12071         // Don't warn about float constants that are precisely
12072         // representable in the target type.
12073         Expr::EvalResult result;
12074         if (E->EvaluateAsRValue(result, S.Context)) {
12075           // Value might be a float, a float vector, or a float complex.
12076           if (IsSameFloatAfterCast(result.Val,
12077                    S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)),
12078                    S.Context.getFloatTypeSemantics(QualType(SourceBT, 0))))
12079             return;
12080         }
12081 
12082         if (S.SourceMgr.isInSystemMacro(CC))
12083           return;
12084 
12085         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_float_precision);
12086       }
12087       // ... or possibly if we're increasing rank, too
12088       else if (Order < 0) {
12089         if (S.SourceMgr.isInSystemMacro(CC))
12090           return;
12091 
12092         DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_double_promotion);
12093       }
12094       return;
12095     }
12096 
12097     // If the target is integral, always warn.
12098     if (TargetBT && TargetBT->isInteger()) {
12099       if (S.SourceMgr.isInSystemMacro(CC))
12100         return;
12101 
12102       DiagnoseFloatingImpCast(S, E, T, CC);
12103     }
12104 
12105     // Detect the case where a call result is converted from floating-point to
12106     // to bool, and the final argument to the call is converted from bool, to
12107     // discover this typo:
12108     //
12109     //    bool b = fabs(x < 1.0);  // should be "bool b = fabs(x) < 1.0;"
12110     //
12111     // FIXME: This is an incredibly special case; is there some more general
12112     // way to detect this class of misplaced-parentheses bug?
12113     if (Target->isBooleanType() && isa<CallExpr>(E)) {
12114       // Check last argument of function call to see if it is an
12115       // implicit cast from a type matching the type the result
12116       // is being cast to.
12117       CallExpr *CEx = cast<CallExpr>(E);
12118       if (unsigned NumArgs = CEx->getNumArgs()) {
12119         Expr *LastA = CEx->getArg(NumArgs - 1);
12120         Expr *InnerE = LastA->IgnoreParenImpCasts();
12121         if (isa<ImplicitCastExpr>(LastA) &&
12122             InnerE->getType()->isBooleanType()) {
12123           // Warn on this floating-point to bool conversion
12124           DiagnoseImpCast(S, E, T, CC,
12125                           diag::warn_impcast_floating_point_to_bool);
12126         }
12127       }
12128     }
12129     return;
12130   }
12131 
12132   // Valid casts involving fixed point types should be accounted for here.
12133   if (Source->isFixedPointType()) {
12134     if (Target->isUnsaturatedFixedPointType()) {
12135       Expr::EvalResult Result;
12136       if (E->EvaluateAsFixedPoint(Result, S.Context, Expr::SE_AllowSideEffects,
12137                                   S.isConstantEvaluated())) {
12138         llvm::APFixedPoint Value = Result.Val.getFixedPoint();
12139         llvm::APFixedPoint MaxVal = S.Context.getFixedPointMax(T);
12140         llvm::APFixedPoint MinVal = S.Context.getFixedPointMin(T);
12141         if (Value > MaxVal || Value < MinVal) {
12142           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12143                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12144                                     << Value.toString() << T
12145                                     << E->getSourceRange()
12146                                     << clang::SourceRange(CC));
12147           return;
12148         }
12149       }
12150     } else if (Target->isIntegerType()) {
12151       Expr::EvalResult Result;
12152       if (!S.isConstantEvaluated() &&
12153           E->EvaluateAsFixedPoint(Result, S.Context,
12154                                   Expr::SE_AllowSideEffects)) {
12155         llvm::APFixedPoint FXResult = Result.Val.getFixedPoint();
12156 
12157         bool Overflowed;
12158         llvm::APSInt IntResult = FXResult.convertToInt(
12159             S.Context.getIntWidth(T),
12160             Target->isSignedIntegerOrEnumerationType(), &Overflowed);
12161 
12162         if (Overflowed) {
12163           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12164                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12165                                     << FXResult.toString() << T
12166                                     << E->getSourceRange()
12167                                     << clang::SourceRange(CC));
12168           return;
12169         }
12170       }
12171     }
12172   } else if (Target->isUnsaturatedFixedPointType()) {
12173     if (Source->isIntegerType()) {
12174       Expr::EvalResult Result;
12175       if (!S.isConstantEvaluated() &&
12176           E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects)) {
12177         llvm::APSInt Value = Result.Val.getInt();
12178 
12179         bool Overflowed;
12180         llvm::APFixedPoint IntResult = llvm::APFixedPoint::getFromIntValue(
12181             Value, S.Context.getFixedPointSemantics(T), &Overflowed);
12182 
12183         if (Overflowed) {
12184           S.DiagRuntimeBehavior(E->getExprLoc(), E,
12185                                 S.PDiag(diag::warn_impcast_fixed_point_range)
12186                                     << Value.toString(/*Radix=*/10) << T
12187                                     << E->getSourceRange()
12188                                     << clang::SourceRange(CC));
12189           return;
12190         }
12191       }
12192     }
12193   }
12194 
12195   // If we are casting an integer type to a floating point type without
12196   // initialization-list syntax, we might lose accuracy if the floating
12197   // point type has a narrower significand than the integer type.
12198   if (SourceBT && TargetBT && SourceBT->isIntegerType() &&
12199       TargetBT->isFloatingType() && !IsListInit) {
12200     // Determine the number of precision bits in the source integer type.
12201     IntRange SourceRange = GetExprRange(S.Context, E, S.isConstantEvaluated(),
12202                                         /*Approximate*/ true);
12203     unsigned int SourcePrecision = SourceRange.Width;
12204 
12205     // Determine the number of precision bits in the
12206     // target floating point type.
12207     unsigned int TargetPrecision = llvm::APFloatBase::semanticsPrecision(
12208         S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12209 
12210     if (SourcePrecision > 0 && TargetPrecision > 0 &&
12211         SourcePrecision > TargetPrecision) {
12212 
12213       if (Optional<llvm::APSInt> SourceInt =
12214               E->getIntegerConstantExpr(S.Context)) {
12215         // If the source integer is a constant, convert it to the target
12216         // floating point type. Issue a warning if the value changes
12217         // during the whole conversion.
12218         llvm::APFloat TargetFloatValue(
12219             S.Context.getFloatTypeSemantics(QualType(TargetBT, 0)));
12220         llvm::APFloat::opStatus ConversionStatus =
12221             TargetFloatValue.convertFromAPInt(
12222                 *SourceInt, SourceBT->isSignedInteger(),
12223                 llvm::APFloat::rmNearestTiesToEven);
12224 
12225         if (ConversionStatus != llvm::APFloat::opOK) {
12226           std::string PrettySourceValue = SourceInt->toString(10);
12227           SmallString<32> PrettyTargetValue;
12228           TargetFloatValue.toString(PrettyTargetValue, TargetPrecision);
12229 
12230           S.DiagRuntimeBehavior(
12231               E->getExprLoc(), E,
12232               S.PDiag(diag::warn_impcast_integer_float_precision_constant)
12233                   << PrettySourceValue << PrettyTargetValue << E->getType() << T
12234                   << E->getSourceRange() << clang::SourceRange(CC));
12235         }
12236       } else {
12237         // Otherwise, the implicit conversion may lose precision.
12238         DiagnoseImpCast(S, E, T, CC,
12239                         diag::warn_impcast_integer_float_precision);
12240       }
12241     }
12242   }
12243 
12244   DiagnoseNullConversion(S, E, T, CC);
12245 
12246   S.DiscardMisalignedMemberAddress(Target, E);
12247 
12248   if (Target->isBooleanType())
12249     DiagnoseIntInBoolContext(S, E);
12250 
12251   if (!Source->isIntegerType() || !Target->isIntegerType())
12252     return;
12253 
12254   // TODO: remove this early return once the false positives for constant->bool
12255   // in templates, macros, etc, are reduced or removed.
12256   if (Target->isSpecificBuiltinType(BuiltinType::Bool))
12257     return;
12258 
12259   if (isObjCSignedCharBool(S, T) && !Source->isCharType() &&
12260       !E->isKnownToHaveBooleanValue(/*Semantic=*/false)) {
12261     return adornObjCBoolConversionDiagWithTernaryFixit(
12262         S, E,
12263         S.Diag(CC, diag::warn_impcast_int_to_objc_signed_char_bool)
12264             << E->getType());
12265   }
12266 
12267   IntRange SourceTypeRange =
12268       IntRange::forTargetOfCanonicalType(S.Context, Source);
12269   IntRange LikelySourceRange =
12270       GetExprRange(S.Context, E, S.isConstantEvaluated(), /*Approximate*/ true);
12271   IntRange TargetRange = IntRange::forTargetOfCanonicalType(S.Context, Target);
12272 
12273   if (LikelySourceRange.Width > TargetRange.Width) {
12274     // If the source is a constant, use a default-on diagnostic.
12275     // TODO: this should happen for bitfield stores, too.
12276     Expr::EvalResult Result;
12277     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects,
12278                          S.isConstantEvaluated())) {
12279       llvm::APSInt Value(32);
12280       Value = Result.Val.getInt();
12281 
12282       if (S.SourceMgr.isInSystemMacro(CC))
12283         return;
12284 
12285       std::string PrettySourceValue = Value.toString(10);
12286       std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12287 
12288       S.DiagRuntimeBehavior(
12289           E->getExprLoc(), E,
12290           S.PDiag(diag::warn_impcast_integer_precision_constant)
12291               << PrettySourceValue << PrettyTargetValue << E->getType() << T
12292               << E->getSourceRange() << SourceRange(CC));
12293       return;
12294     }
12295 
12296     // People want to build with -Wshorten-64-to-32 and not -Wconversion.
12297     if (S.SourceMgr.isInSystemMacro(CC))
12298       return;
12299 
12300     if (TargetRange.Width == 32 && S.Context.getIntWidth(E->getType()) == 64)
12301       return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_64_32,
12302                              /* pruneControlFlow */ true);
12303     return DiagnoseImpCast(S, E, T, CC, diag::warn_impcast_integer_precision);
12304   }
12305 
12306   if (TargetRange.Width > SourceTypeRange.Width) {
12307     if (auto *UO = dyn_cast<UnaryOperator>(E))
12308       if (UO->getOpcode() == UO_Minus)
12309         if (Source->isUnsignedIntegerType()) {
12310           if (Target->isUnsignedIntegerType())
12311             return DiagnoseImpCast(S, E, T, CC,
12312                                    diag::warn_impcast_high_order_zero_bits);
12313           if (Target->isSignedIntegerType())
12314             return DiagnoseImpCast(S, E, T, CC,
12315                                    diag::warn_impcast_nonnegative_result);
12316         }
12317   }
12318 
12319   if (TargetRange.Width == LikelySourceRange.Width &&
12320       !TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12321       Source->isSignedIntegerType()) {
12322     // Warn when doing a signed to signed conversion, warn if the positive
12323     // source value is exactly the width of the target type, which will
12324     // cause a negative value to be stored.
12325 
12326     Expr::EvalResult Result;
12327     if (E->EvaluateAsInt(Result, S.Context, Expr::SE_AllowSideEffects) &&
12328         !S.SourceMgr.isInSystemMacro(CC)) {
12329       llvm::APSInt Value = Result.Val.getInt();
12330       if (isSameWidthConstantConversion(S, E, T, CC)) {
12331         std::string PrettySourceValue = Value.toString(10);
12332         std::string PrettyTargetValue = PrettyPrintInRange(Value, TargetRange);
12333 
12334         S.DiagRuntimeBehavior(
12335             E->getExprLoc(), E,
12336             S.PDiag(diag::warn_impcast_integer_precision_constant)
12337                 << PrettySourceValue << PrettyTargetValue << E->getType() << T
12338                 << E->getSourceRange() << SourceRange(CC));
12339         return;
12340       }
12341     }
12342 
12343     // Fall through for non-constants to give a sign conversion warning.
12344   }
12345 
12346   if ((TargetRange.NonNegative && !LikelySourceRange.NonNegative) ||
12347       (!TargetRange.NonNegative && LikelySourceRange.NonNegative &&
12348        LikelySourceRange.Width == TargetRange.Width)) {
12349     if (S.SourceMgr.isInSystemMacro(CC))
12350       return;
12351 
12352     unsigned DiagID = diag::warn_impcast_integer_sign;
12353 
12354     // Traditionally, gcc has warned about this under -Wsign-compare.
12355     // We also want to warn about it in -Wconversion.
12356     // So if -Wconversion is off, use a completely identical diagnostic
12357     // in the sign-compare group.
12358     // The conditional-checking code will
12359     if (ICContext) {
12360       DiagID = diag::warn_impcast_integer_sign_conditional;
12361       *ICContext = true;
12362     }
12363 
12364     return DiagnoseImpCast(S, E, T, CC, DiagID);
12365   }
12366 
12367   // Diagnose conversions between different enumeration types.
12368   // In C, we pretend that the type of an EnumConstantDecl is its enumeration
12369   // type, to give us better diagnostics.
12370   QualType SourceType = E->getType();
12371   if (!S.getLangOpts().CPlusPlus) {
12372     if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
12373       if (EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
12374         EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
12375         SourceType = S.Context.getTypeDeclType(Enum);
12376         Source = S.Context.getCanonicalType(SourceType).getTypePtr();
12377       }
12378   }
12379 
12380   if (const EnumType *SourceEnum = Source->getAs<EnumType>())
12381     if (const EnumType *TargetEnum = Target->getAs<EnumType>())
12382       if (SourceEnum->getDecl()->hasNameForLinkage() &&
12383           TargetEnum->getDecl()->hasNameForLinkage() &&
12384           SourceEnum != TargetEnum) {
12385         if (S.SourceMgr.isInSystemMacro(CC))
12386           return;
12387 
12388         return DiagnoseImpCast(S, E, SourceType, T, CC,
12389                                diag::warn_impcast_different_enum_types);
12390       }
12391 }
12392 
12393 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12394                                      SourceLocation CC, QualType T);
12395 
12396 static void CheckConditionalOperand(Sema &S, Expr *E, QualType T,
12397                                     SourceLocation CC, bool &ICContext) {
12398   E = E->IgnoreParenImpCasts();
12399 
12400   if (auto *CO = dyn_cast<AbstractConditionalOperator>(E))
12401     return CheckConditionalOperator(S, CO, CC, T);
12402 
12403   AnalyzeImplicitConversions(S, E, CC);
12404   if (E->getType() != T)
12405     return CheckImplicitConversion(S, E, T, CC, &ICContext);
12406 }
12407 
12408 static void CheckConditionalOperator(Sema &S, AbstractConditionalOperator *E,
12409                                      SourceLocation CC, QualType T) {
12410   AnalyzeImplicitConversions(S, E->getCond(), E->getQuestionLoc());
12411 
12412   Expr *TrueExpr = E->getTrueExpr();
12413   if (auto *BCO = dyn_cast<BinaryConditionalOperator>(E))
12414     TrueExpr = BCO->getCommon();
12415 
12416   bool Suspicious = false;
12417   CheckConditionalOperand(S, TrueExpr, T, CC, Suspicious);
12418   CheckConditionalOperand(S, E->getFalseExpr(), T, CC, Suspicious);
12419 
12420   if (T->isBooleanType())
12421     DiagnoseIntInBoolContext(S, E);
12422 
12423   // If -Wconversion would have warned about either of the candidates
12424   // for a signedness conversion to the context type...
12425   if (!Suspicious) return;
12426 
12427   // ...but it's currently ignored...
12428   if (!S.Diags.isIgnored(diag::warn_impcast_integer_sign_conditional, CC))
12429     return;
12430 
12431   // ...then check whether it would have warned about either of the
12432   // candidates for a signedness conversion to the condition type.
12433   if (E->getType() == T) return;
12434 
12435   Suspicious = false;
12436   CheckImplicitConversion(S, TrueExpr->IgnoreParenImpCasts(),
12437                           E->getType(), CC, &Suspicious);
12438   if (!Suspicious)
12439     CheckImplicitConversion(S, E->getFalseExpr()->IgnoreParenImpCasts(),
12440                             E->getType(), CC, &Suspicious);
12441 }
12442 
12443 /// Check conversion of given expression to boolean.
12444 /// Input argument E is a logical expression.
12445 static void CheckBoolLikeConversion(Sema &S, Expr *E, SourceLocation CC) {
12446   if (S.getLangOpts().Bool)
12447     return;
12448   if (E->IgnoreParenImpCasts()->getType()->isAtomicType())
12449     return;
12450   CheckImplicitConversion(S, E->IgnoreParenImpCasts(), S.Context.BoolTy, CC);
12451 }
12452 
12453 namespace {
12454 struct AnalyzeImplicitConversionsWorkItem {
12455   Expr *E;
12456   SourceLocation CC;
12457   bool IsListInit;
12458 };
12459 }
12460 
12461 /// Data recursive variant of AnalyzeImplicitConversions. Subexpressions
12462 /// that should be visited are added to WorkList.
12463 static void AnalyzeImplicitConversions(
12464     Sema &S, AnalyzeImplicitConversionsWorkItem Item,
12465     llvm::SmallVectorImpl<AnalyzeImplicitConversionsWorkItem> &WorkList) {
12466   Expr *OrigE = Item.E;
12467   SourceLocation CC = Item.CC;
12468 
12469   QualType T = OrigE->getType();
12470   Expr *E = OrigE->IgnoreParenImpCasts();
12471 
12472   // Propagate whether we are in a C++ list initialization expression.
12473   // If so, we do not issue warnings for implicit int-float conversion
12474   // precision loss, because C++11 narrowing already handles it.
12475   bool IsListInit = Item.IsListInit ||
12476                     (isa<InitListExpr>(OrigE) && S.getLangOpts().CPlusPlus);
12477 
12478   if (E->isTypeDependent() || E->isValueDependent())
12479     return;
12480 
12481   Expr *SourceExpr = E;
12482   // Examine, but don't traverse into the source expression of an
12483   // OpaqueValueExpr, since it may have multiple parents and we don't want to
12484   // emit duplicate diagnostics. Its fine to examine the form or attempt to
12485   // evaluate it in the context of checking the specific conversion to T though.
12486   if (auto *OVE = dyn_cast<OpaqueValueExpr>(E))
12487     if (auto *Src = OVE->getSourceExpr())
12488       SourceExpr = Src;
12489 
12490   if (const auto *UO = dyn_cast<UnaryOperator>(SourceExpr))
12491     if (UO->getOpcode() == UO_Not &&
12492         UO->getSubExpr()->isKnownToHaveBooleanValue())
12493       S.Diag(UO->getBeginLoc(), diag::warn_bitwise_negation_bool)
12494           << OrigE->getSourceRange() << T->isBooleanType()
12495           << FixItHint::CreateReplacement(UO->getBeginLoc(), "!");
12496 
12497   // For conditional operators, we analyze the arguments as if they
12498   // were being fed directly into the output.
12499   if (auto *CO = dyn_cast<AbstractConditionalOperator>(SourceExpr)) {
12500     CheckConditionalOperator(S, CO, CC, T);
12501     return;
12502   }
12503 
12504   // Check implicit argument conversions for function calls.
12505   if (CallExpr *Call = dyn_cast<CallExpr>(SourceExpr))
12506     CheckImplicitArgumentConversions(S, Call, CC);
12507 
12508   // Go ahead and check any implicit conversions we might have skipped.
12509   // The non-canonical typecheck is just an optimization;
12510   // CheckImplicitConversion will filter out dead implicit conversions.
12511   if (SourceExpr->getType() != T)
12512     CheckImplicitConversion(S, SourceExpr, T, CC, nullptr, IsListInit);
12513 
12514   // Now continue drilling into this expression.
12515 
12516   if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(E)) {
12517     // The bound subexpressions in a PseudoObjectExpr are not reachable
12518     // as transitive children.
12519     // FIXME: Use a more uniform representation for this.
12520     for (auto *SE : POE->semantics())
12521       if (auto *OVE = dyn_cast<OpaqueValueExpr>(SE))
12522         WorkList.push_back({OVE->getSourceExpr(), CC, IsListInit});
12523   }
12524 
12525   // Skip past explicit casts.
12526   if (auto *CE = dyn_cast<ExplicitCastExpr>(E)) {
12527     E = CE->getSubExpr()->IgnoreParenImpCasts();
12528     if (!CE->getType()->isVoidType() && E->getType()->isAtomicType())
12529       S.Diag(E->getBeginLoc(), diag::warn_atomic_implicit_seq_cst);
12530     WorkList.push_back({E, CC, IsListInit});
12531     return;
12532   }
12533 
12534   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
12535     // Do a somewhat different check with comparison operators.
12536     if (BO->isComparisonOp())
12537       return AnalyzeComparison(S, BO);
12538 
12539     // And with simple assignments.
12540     if (BO->getOpcode() == BO_Assign)
12541       return AnalyzeAssignment(S, BO);
12542     // And with compound assignments.
12543     if (BO->isAssignmentOp())
12544       return AnalyzeCompoundAssignment(S, BO);
12545   }
12546 
12547   // These break the otherwise-useful invariant below.  Fortunately,
12548   // we don't really need to recurse into them, because any internal
12549   // expressions should have been analyzed already when they were
12550   // built into statements.
12551   if (isa<StmtExpr>(E)) return;
12552 
12553   // Don't descend into unevaluated contexts.
12554   if (isa<UnaryExprOrTypeTraitExpr>(E)) return;
12555 
12556   // Now just recurse over the expression's children.
12557   CC = E->getExprLoc();
12558   BinaryOperator *BO = dyn_cast<BinaryOperator>(E);
12559   bool IsLogicalAndOperator = BO && BO->getOpcode() == BO_LAnd;
12560   for (Stmt *SubStmt : E->children()) {
12561     Expr *ChildExpr = dyn_cast_or_null<Expr>(SubStmt);
12562     if (!ChildExpr)
12563       continue;
12564 
12565     if (IsLogicalAndOperator &&
12566         isa<StringLiteral>(ChildExpr->IgnoreParenImpCasts()))
12567       // Ignore checking string literals that are in logical and operators.
12568       // This is a common pattern for asserts.
12569       continue;
12570     WorkList.push_back({ChildExpr, CC, IsListInit});
12571   }
12572 
12573   if (BO && BO->isLogicalOp()) {
12574     Expr *SubExpr = BO->getLHS()->IgnoreParenImpCasts();
12575     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12576       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12577 
12578     SubExpr = BO->getRHS()->IgnoreParenImpCasts();
12579     if (!IsLogicalAndOperator || !isa<StringLiteral>(SubExpr))
12580       ::CheckBoolLikeConversion(S, SubExpr, BO->getExprLoc());
12581   }
12582 
12583   if (const UnaryOperator *U = dyn_cast<UnaryOperator>(E)) {
12584     if (U->getOpcode() == UO_LNot) {
12585       ::CheckBoolLikeConversion(S, U->getSubExpr(), CC);
12586     } else if (U->getOpcode() != UO_AddrOf) {
12587       if (U->getSubExpr()->getType()->isAtomicType())
12588         S.Diag(U->getSubExpr()->getBeginLoc(),
12589                diag::warn_atomic_implicit_seq_cst);
12590     }
12591   }
12592 }
12593 
12594 /// AnalyzeImplicitConversions - Find and report any interesting
12595 /// implicit conversions in the given expression.  There are a couple
12596 /// of competing diagnostics here, -Wconversion and -Wsign-compare.
12597 static void AnalyzeImplicitConversions(Sema &S, Expr *OrigE, SourceLocation CC,
12598                                        bool IsListInit/*= false*/) {
12599   llvm::SmallVector<AnalyzeImplicitConversionsWorkItem, 16> WorkList;
12600   WorkList.push_back({OrigE, CC, IsListInit});
12601   while (!WorkList.empty())
12602     AnalyzeImplicitConversions(S, WorkList.pop_back_val(), WorkList);
12603 }
12604 
12605 /// Diagnose integer type and any valid implicit conversion to it.
12606 static bool checkOpenCLEnqueueIntType(Sema &S, Expr *E, const QualType &IntT) {
12607   // Taking into account implicit conversions,
12608   // allow any integer.
12609   if (!E->getType()->isIntegerType()) {
12610     S.Diag(E->getBeginLoc(),
12611            diag::err_opencl_enqueue_kernel_invalid_local_size_type);
12612     return true;
12613   }
12614   // Potentially emit standard warnings for implicit conversions if enabled
12615   // using -Wconversion.
12616   CheckImplicitConversion(S, E, IntT, E->getBeginLoc());
12617   return false;
12618 }
12619 
12620 // Helper function for Sema::DiagnoseAlwaysNonNullPointer.
12621 // Returns true when emitting a warning about taking the address of a reference.
12622 static bool CheckForReference(Sema &SemaRef, const Expr *E,
12623                               const PartialDiagnostic &PD) {
12624   E = E->IgnoreParenImpCasts();
12625 
12626   const FunctionDecl *FD = nullptr;
12627 
12628   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
12629     if (!DRE->getDecl()->getType()->isReferenceType())
12630       return false;
12631   } else if (const MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12632     if (!M->getMemberDecl()->getType()->isReferenceType())
12633       return false;
12634   } else if (const CallExpr *Call = dyn_cast<CallExpr>(E)) {
12635     if (!Call->getCallReturnType(SemaRef.Context)->isReferenceType())
12636       return false;
12637     FD = Call->getDirectCallee();
12638   } else {
12639     return false;
12640   }
12641 
12642   SemaRef.Diag(E->getExprLoc(), PD);
12643 
12644   // If possible, point to location of function.
12645   if (FD) {
12646     SemaRef.Diag(FD->getLocation(), diag::note_reference_is_return_value) << FD;
12647   }
12648 
12649   return true;
12650 }
12651 
12652 // Returns true if the SourceLocation is expanded from any macro body.
12653 // Returns false if the SourceLocation is invalid, is from not in a macro
12654 // expansion, or is from expanded from a top-level macro argument.
12655 static bool IsInAnyMacroBody(const SourceManager &SM, SourceLocation Loc) {
12656   if (Loc.isInvalid())
12657     return false;
12658 
12659   while (Loc.isMacroID()) {
12660     if (SM.isMacroBodyExpansion(Loc))
12661       return true;
12662     Loc = SM.getImmediateMacroCallerLoc(Loc);
12663   }
12664 
12665   return false;
12666 }
12667 
12668 /// Diagnose pointers that are always non-null.
12669 /// \param E the expression containing the pointer
12670 /// \param NullKind NPCK_NotNull if E is a cast to bool, otherwise, E is
12671 /// compared to a null pointer
12672 /// \param IsEqual True when the comparison is equal to a null pointer
12673 /// \param Range Extra SourceRange to highlight in the diagnostic
12674 void Sema::DiagnoseAlwaysNonNullPointer(Expr *E,
12675                                         Expr::NullPointerConstantKind NullKind,
12676                                         bool IsEqual, SourceRange Range) {
12677   if (!E)
12678     return;
12679 
12680   // Don't warn inside macros.
12681   if (E->getExprLoc().isMacroID()) {
12682     const SourceManager &SM = getSourceManager();
12683     if (IsInAnyMacroBody(SM, E->getExprLoc()) ||
12684         IsInAnyMacroBody(SM, Range.getBegin()))
12685       return;
12686   }
12687   E = E->IgnoreImpCasts();
12688 
12689   const bool IsCompare = NullKind != Expr::NPCK_NotNull;
12690 
12691   if (isa<CXXThisExpr>(E)) {
12692     unsigned DiagID = IsCompare ? diag::warn_this_null_compare
12693                                 : diag::warn_this_bool_conversion;
12694     Diag(E->getExprLoc(), DiagID) << E->getSourceRange() << Range << IsEqual;
12695     return;
12696   }
12697 
12698   bool IsAddressOf = false;
12699 
12700   if (UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
12701     if (UO->getOpcode() != UO_AddrOf)
12702       return;
12703     IsAddressOf = true;
12704     E = UO->getSubExpr();
12705   }
12706 
12707   if (IsAddressOf) {
12708     unsigned DiagID = IsCompare
12709                           ? diag::warn_address_of_reference_null_compare
12710                           : diag::warn_address_of_reference_bool_conversion;
12711     PartialDiagnostic PD = PDiag(DiagID) << E->getSourceRange() << Range
12712                                          << IsEqual;
12713     if (CheckForReference(*this, E, PD)) {
12714       return;
12715     }
12716   }
12717 
12718   auto ComplainAboutNonnullParamOrCall = [&](const Attr *NonnullAttr) {
12719     bool IsParam = isa<NonNullAttr>(NonnullAttr);
12720     std::string Str;
12721     llvm::raw_string_ostream S(Str);
12722     E->printPretty(S, nullptr, getPrintingPolicy());
12723     unsigned DiagID = IsCompare ? diag::warn_nonnull_expr_compare
12724                                 : diag::warn_cast_nonnull_to_bool;
12725     Diag(E->getExprLoc(), DiagID) << IsParam << S.str()
12726       << E->getSourceRange() << Range << IsEqual;
12727     Diag(NonnullAttr->getLocation(), diag::note_declared_nonnull) << IsParam;
12728   };
12729 
12730   // If we have a CallExpr that is tagged with returns_nonnull, we can complain.
12731   if (auto *Call = dyn_cast<CallExpr>(E->IgnoreParenImpCasts())) {
12732     if (auto *Callee = Call->getDirectCallee()) {
12733       if (const Attr *A = Callee->getAttr<ReturnsNonNullAttr>()) {
12734         ComplainAboutNonnullParamOrCall(A);
12735         return;
12736       }
12737     }
12738   }
12739 
12740   // Expect to find a single Decl.  Skip anything more complicated.
12741   ValueDecl *D = nullptr;
12742   if (DeclRefExpr *R = dyn_cast<DeclRefExpr>(E)) {
12743     D = R->getDecl();
12744   } else if (MemberExpr *M = dyn_cast<MemberExpr>(E)) {
12745     D = M->getMemberDecl();
12746   }
12747 
12748   // Weak Decls can be null.
12749   if (!D || D->isWeak())
12750     return;
12751 
12752   // Check for parameter decl with nonnull attribute
12753   if (const auto* PV = dyn_cast<ParmVarDecl>(D)) {
12754     if (getCurFunction() &&
12755         !getCurFunction()->ModifiedNonNullParams.count(PV)) {
12756       if (const Attr *A = PV->getAttr<NonNullAttr>()) {
12757         ComplainAboutNonnullParamOrCall(A);
12758         return;
12759       }
12760 
12761       if (const auto *FD = dyn_cast<FunctionDecl>(PV->getDeclContext())) {
12762         // Skip function template not specialized yet.
12763         if (FD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplate)
12764           return;
12765         auto ParamIter = llvm::find(FD->parameters(), PV);
12766         assert(ParamIter != FD->param_end());
12767         unsigned ParamNo = std::distance(FD->param_begin(), ParamIter);
12768 
12769         for (const auto *NonNull : FD->specific_attrs<NonNullAttr>()) {
12770           if (!NonNull->args_size()) {
12771               ComplainAboutNonnullParamOrCall(NonNull);
12772               return;
12773           }
12774 
12775           for (const ParamIdx &ArgNo : NonNull->args()) {
12776             if (ArgNo.getASTIndex() == ParamNo) {
12777               ComplainAboutNonnullParamOrCall(NonNull);
12778               return;
12779             }
12780           }
12781         }
12782       }
12783     }
12784   }
12785 
12786   QualType T = D->getType();
12787   const bool IsArray = T->isArrayType();
12788   const bool IsFunction = T->isFunctionType();
12789 
12790   // Address of function is used to silence the function warning.
12791   if (IsAddressOf && IsFunction) {
12792     return;
12793   }
12794 
12795   // Found nothing.
12796   if (!IsAddressOf && !IsFunction && !IsArray)
12797     return;
12798 
12799   // Pretty print the expression for the diagnostic.
12800   std::string Str;
12801   llvm::raw_string_ostream S(Str);
12802   E->printPretty(S, nullptr, getPrintingPolicy());
12803 
12804   unsigned DiagID = IsCompare ? diag::warn_null_pointer_compare
12805                               : diag::warn_impcast_pointer_to_bool;
12806   enum {
12807     AddressOf,
12808     FunctionPointer,
12809     ArrayPointer
12810   } DiagType;
12811   if (IsAddressOf)
12812     DiagType = AddressOf;
12813   else if (IsFunction)
12814     DiagType = FunctionPointer;
12815   else if (IsArray)
12816     DiagType = ArrayPointer;
12817   else
12818     llvm_unreachable("Could not determine diagnostic.");
12819   Diag(E->getExprLoc(), DiagID) << DiagType << S.str() << E->getSourceRange()
12820                                 << Range << IsEqual;
12821 
12822   if (!IsFunction)
12823     return;
12824 
12825   // Suggest '&' to silence the function warning.
12826   Diag(E->getExprLoc(), diag::note_function_warning_silence)
12827       << FixItHint::CreateInsertion(E->getBeginLoc(), "&");
12828 
12829   // Check to see if '()' fixit should be emitted.
12830   QualType ReturnType;
12831   UnresolvedSet<4> NonTemplateOverloads;
12832   tryExprAsCall(*E, ReturnType, NonTemplateOverloads);
12833   if (ReturnType.isNull())
12834     return;
12835 
12836   if (IsCompare) {
12837     // There are two cases here.  If there is null constant, the only suggest
12838     // for a pointer return type.  If the null is 0, then suggest if the return
12839     // type is a pointer or an integer type.
12840     if (!ReturnType->isPointerType()) {
12841       if (NullKind == Expr::NPCK_ZeroExpression ||
12842           NullKind == Expr::NPCK_ZeroLiteral) {
12843         if (!ReturnType->isIntegerType())
12844           return;
12845       } else {
12846         return;
12847       }
12848     }
12849   } else { // !IsCompare
12850     // For function to bool, only suggest if the function pointer has bool
12851     // return type.
12852     if (!ReturnType->isSpecificBuiltinType(BuiltinType::Bool))
12853       return;
12854   }
12855   Diag(E->getExprLoc(), diag::note_function_to_function_call)
12856       << FixItHint::CreateInsertion(getLocForEndOfToken(E->getEndLoc()), "()");
12857 }
12858 
12859 /// Diagnoses "dangerous" implicit conversions within the given
12860 /// expression (which is a full expression).  Implements -Wconversion
12861 /// and -Wsign-compare.
12862 ///
12863 /// \param CC the "context" location of the implicit conversion, i.e.
12864 ///   the most location of the syntactic entity requiring the implicit
12865 ///   conversion
12866 void Sema::CheckImplicitConversions(Expr *E, SourceLocation CC) {
12867   // Don't diagnose in unevaluated contexts.
12868   if (isUnevaluatedContext())
12869     return;
12870 
12871   // Don't diagnose for value- or type-dependent expressions.
12872   if (E->isTypeDependent() || E->isValueDependent())
12873     return;
12874 
12875   // Check for array bounds violations in cases where the check isn't triggered
12876   // elsewhere for other Expr types (like BinaryOperators), e.g. when an
12877   // ArraySubscriptExpr is on the RHS of a variable initialization.
12878   CheckArrayAccess(E);
12879 
12880   // This is not the right CC for (e.g.) a variable initialization.
12881   AnalyzeImplicitConversions(*this, E, CC);
12882 }
12883 
12884 /// CheckBoolLikeConversion - Check conversion of given expression to boolean.
12885 /// Input argument E is a logical expression.
12886 void Sema::CheckBoolLikeConversion(Expr *E, SourceLocation CC) {
12887   ::CheckBoolLikeConversion(*this, E, CC);
12888 }
12889 
12890 /// Diagnose when expression is an integer constant expression and its evaluation
12891 /// results in integer overflow
12892 void Sema::CheckForIntOverflow (Expr *E) {
12893   // Use a work list to deal with nested struct initializers.
12894   SmallVector<Expr *, 2> Exprs(1, E);
12895 
12896   do {
12897     Expr *OriginalE = Exprs.pop_back_val();
12898     Expr *E = OriginalE->IgnoreParenCasts();
12899 
12900     if (isa<BinaryOperator>(E)) {
12901       E->EvaluateForOverflow(Context);
12902       continue;
12903     }
12904 
12905     if (auto InitList = dyn_cast<InitListExpr>(OriginalE))
12906       Exprs.append(InitList->inits().begin(), InitList->inits().end());
12907     else if (isa<ObjCBoxedExpr>(OriginalE))
12908       E->EvaluateForOverflow(Context);
12909     else if (auto Call = dyn_cast<CallExpr>(E))
12910       Exprs.append(Call->arg_begin(), Call->arg_end());
12911     else if (auto Message = dyn_cast<ObjCMessageExpr>(E))
12912       Exprs.append(Message->arg_begin(), Message->arg_end());
12913   } while (!Exprs.empty());
12914 }
12915 
12916 namespace {
12917 
12918 /// Visitor for expressions which looks for unsequenced operations on the
12919 /// same object.
12920 class SequenceChecker : public ConstEvaluatedExprVisitor<SequenceChecker> {
12921   using Base = ConstEvaluatedExprVisitor<SequenceChecker>;
12922 
12923   /// A tree of sequenced regions within an expression. Two regions are
12924   /// unsequenced if one is an ancestor or a descendent of the other. When we
12925   /// finish processing an expression with sequencing, such as a comma
12926   /// expression, we fold its tree nodes into its parent, since they are
12927   /// unsequenced with respect to nodes we will visit later.
12928   class SequenceTree {
12929     struct Value {
12930       explicit Value(unsigned Parent) : Parent(Parent), Merged(false) {}
12931       unsigned Parent : 31;
12932       unsigned Merged : 1;
12933     };
12934     SmallVector<Value, 8> Values;
12935 
12936   public:
12937     /// A region within an expression which may be sequenced with respect
12938     /// to some other region.
12939     class Seq {
12940       friend class SequenceTree;
12941 
12942       unsigned Index;
12943 
12944       explicit Seq(unsigned N) : Index(N) {}
12945 
12946     public:
12947       Seq() : Index(0) {}
12948     };
12949 
12950     SequenceTree() { Values.push_back(Value(0)); }
12951     Seq root() const { return Seq(0); }
12952 
12953     /// Create a new sequence of operations, which is an unsequenced
12954     /// subset of \p Parent. This sequence of operations is sequenced with
12955     /// respect to other children of \p Parent.
12956     Seq allocate(Seq Parent) {
12957       Values.push_back(Value(Parent.Index));
12958       return Seq(Values.size() - 1);
12959     }
12960 
12961     /// Merge a sequence of operations into its parent.
12962     void merge(Seq S) {
12963       Values[S.Index].Merged = true;
12964     }
12965 
12966     /// Determine whether two operations are unsequenced. This operation
12967     /// is asymmetric: \p Cur should be the more recent sequence, and \p Old
12968     /// should have been merged into its parent as appropriate.
12969     bool isUnsequenced(Seq Cur, Seq Old) {
12970       unsigned C = representative(Cur.Index);
12971       unsigned Target = representative(Old.Index);
12972       while (C >= Target) {
12973         if (C == Target)
12974           return true;
12975         C = Values[C].Parent;
12976       }
12977       return false;
12978     }
12979 
12980   private:
12981     /// Pick a representative for a sequence.
12982     unsigned representative(unsigned K) {
12983       if (Values[K].Merged)
12984         // Perform path compression as we go.
12985         return Values[K].Parent = representative(Values[K].Parent);
12986       return K;
12987     }
12988   };
12989 
12990   /// An object for which we can track unsequenced uses.
12991   using Object = const NamedDecl *;
12992 
12993   /// Different flavors of object usage which we track. We only track the
12994   /// least-sequenced usage of each kind.
12995   enum UsageKind {
12996     /// A read of an object. Multiple unsequenced reads are OK.
12997     UK_Use,
12998 
12999     /// A modification of an object which is sequenced before the value
13000     /// computation of the expression, such as ++n in C++.
13001     UK_ModAsValue,
13002 
13003     /// A modification of an object which is not sequenced before the value
13004     /// computation of the expression, such as n++.
13005     UK_ModAsSideEffect,
13006 
13007     UK_Count = UK_ModAsSideEffect + 1
13008   };
13009 
13010   /// Bundle together a sequencing region and the expression corresponding
13011   /// to a specific usage. One Usage is stored for each usage kind in UsageInfo.
13012   struct Usage {
13013     const Expr *UsageExpr;
13014     SequenceTree::Seq Seq;
13015 
13016     Usage() : UsageExpr(nullptr), Seq() {}
13017   };
13018 
13019   struct UsageInfo {
13020     Usage Uses[UK_Count];
13021 
13022     /// Have we issued a diagnostic for this object already?
13023     bool Diagnosed;
13024 
13025     UsageInfo() : Uses(), Diagnosed(false) {}
13026   };
13027   using UsageInfoMap = llvm::SmallDenseMap<Object, UsageInfo, 16>;
13028 
13029   Sema &SemaRef;
13030 
13031   /// Sequenced regions within the expression.
13032   SequenceTree Tree;
13033 
13034   /// Declaration modifications and references which we have seen.
13035   UsageInfoMap UsageMap;
13036 
13037   /// The region we are currently within.
13038   SequenceTree::Seq Region;
13039 
13040   /// Filled in with declarations which were modified as a side-effect
13041   /// (that is, post-increment operations).
13042   SmallVectorImpl<std::pair<Object, Usage>> *ModAsSideEffect = nullptr;
13043 
13044   /// Expressions to check later. We defer checking these to reduce
13045   /// stack usage.
13046   SmallVectorImpl<const Expr *> &WorkList;
13047 
13048   /// RAII object wrapping the visitation of a sequenced subexpression of an
13049   /// expression. At the end of this process, the side-effects of the evaluation
13050   /// become sequenced with respect to the value computation of the result, so
13051   /// we downgrade any UK_ModAsSideEffect within the evaluation to
13052   /// UK_ModAsValue.
13053   struct SequencedSubexpression {
13054     SequencedSubexpression(SequenceChecker &Self)
13055       : Self(Self), OldModAsSideEffect(Self.ModAsSideEffect) {
13056       Self.ModAsSideEffect = &ModAsSideEffect;
13057     }
13058 
13059     ~SequencedSubexpression() {
13060       for (const std::pair<Object, Usage> &M : llvm::reverse(ModAsSideEffect)) {
13061         // Add a new usage with usage kind UK_ModAsValue, and then restore
13062         // the previous usage with UK_ModAsSideEffect (thus clearing it if
13063         // the previous one was empty).
13064         UsageInfo &UI = Self.UsageMap[M.first];
13065         auto &SideEffectUsage = UI.Uses[UK_ModAsSideEffect];
13066         Self.addUsage(M.first, UI, SideEffectUsage.UsageExpr, UK_ModAsValue);
13067         SideEffectUsage = M.second;
13068       }
13069       Self.ModAsSideEffect = OldModAsSideEffect;
13070     }
13071 
13072     SequenceChecker &Self;
13073     SmallVector<std::pair<Object, Usage>, 4> ModAsSideEffect;
13074     SmallVectorImpl<std::pair<Object, Usage>> *OldModAsSideEffect;
13075   };
13076 
13077   /// RAII object wrapping the visitation of a subexpression which we might
13078   /// choose to evaluate as a constant. If any subexpression is evaluated and
13079   /// found to be non-constant, this allows us to suppress the evaluation of
13080   /// the outer expression.
13081   class EvaluationTracker {
13082   public:
13083     EvaluationTracker(SequenceChecker &Self)
13084         : Self(Self), Prev(Self.EvalTracker) {
13085       Self.EvalTracker = this;
13086     }
13087 
13088     ~EvaluationTracker() {
13089       Self.EvalTracker = Prev;
13090       if (Prev)
13091         Prev->EvalOK &= EvalOK;
13092     }
13093 
13094     bool evaluate(const Expr *E, bool &Result) {
13095       if (!EvalOK || E->isValueDependent())
13096         return false;
13097       EvalOK = E->EvaluateAsBooleanCondition(
13098           Result, Self.SemaRef.Context, Self.SemaRef.isConstantEvaluated());
13099       return EvalOK;
13100     }
13101 
13102   private:
13103     SequenceChecker &Self;
13104     EvaluationTracker *Prev;
13105     bool EvalOK = true;
13106   } *EvalTracker = nullptr;
13107 
13108   /// Find the object which is produced by the specified expression,
13109   /// if any.
13110   Object getObject(const Expr *E, bool Mod) const {
13111     E = E->IgnoreParenCasts();
13112     if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
13113       if (Mod && (UO->getOpcode() == UO_PreInc || UO->getOpcode() == UO_PreDec))
13114         return getObject(UO->getSubExpr(), Mod);
13115     } else if (const BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
13116       if (BO->getOpcode() == BO_Comma)
13117         return getObject(BO->getRHS(), Mod);
13118       if (Mod && BO->isAssignmentOp())
13119         return getObject(BO->getLHS(), Mod);
13120     } else if (const MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
13121       // FIXME: Check for more interesting cases, like "x.n = ++x.n".
13122       if (isa<CXXThisExpr>(ME->getBase()->IgnoreParenCasts()))
13123         return ME->getMemberDecl();
13124     } else if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
13125       // FIXME: If this is a reference, map through to its value.
13126       return DRE->getDecl();
13127     return nullptr;
13128   }
13129 
13130   /// Note that an object \p O was modified or used by an expression
13131   /// \p UsageExpr with usage kind \p UK. \p UI is the \p UsageInfo for
13132   /// the object \p O as obtained via the \p UsageMap.
13133   void addUsage(Object O, UsageInfo &UI, const Expr *UsageExpr, UsageKind UK) {
13134     // Get the old usage for the given object and usage kind.
13135     Usage &U = UI.Uses[UK];
13136     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq)) {
13137       // If we have a modification as side effect and are in a sequenced
13138       // subexpression, save the old Usage so that we can restore it later
13139       // in SequencedSubexpression::~SequencedSubexpression.
13140       if (UK == UK_ModAsSideEffect && ModAsSideEffect)
13141         ModAsSideEffect->push_back(std::make_pair(O, U));
13142       // Then record the new usage with the current sequencing region.
13143       U.UsageExpr = UsageExpr;
13144       U.Seq = Region;
13145     }
13146   }
13147 
13148   /// Check whether a modification or use of an object \p O in an expression
13149   /// \p UsageExpr conflicts with a prior usage of kind \p OtherKind. \p UI is
13150   /// the \p UsageInfo for the object \p O as obtained via the \p UsageMap.
13151   /// \p IsModMod is true when we are checking for a mod-mod unsequenced
13152   /// usage and false we are checking for a mod-use unsequenced usage.
13153   void checkUsage(Object O, UsageInfo &UI, const Expr *UsageExpr,
13154                   UsageKind OtherKind, bool IsModMod) {
13155     if (UI.Diagnosed)
13156       return;
13157 
13158     const Usage &U = UI.Uses[OtherKind];
13159     if (!U.UsageExpr || !Tree.isUnsequenced(Region, U.Seq))
13160       return;
13161 
13162     const Expr *Mod = U.UsageExpr;
13163     const Expr *ModOrUse = UsageExpr;
13164     if (OtherKind == UK_Use)
13165       std::swap(Mod, ModOrUse);
13166 
13167     SemaRef.DiagRuntimeBehavior(
13168         Mod->getExprLoc(), {Mod, ModOrUse},
13169         SemaRef.PDiag(IsModMod ? diag::warn_unsequenced_mod_mod
13170                                : diag::warn_unsequenced_mod_use)
13171             << O << SourceRange(ModOrUse->getExprLoc()));
13172     UI.Diagnosed = true;
13173   }
13174 
13175   // A note on note{Pre, Post}{Use, Mod}:
13176   //
13177   // (It helps to follow the algorithm with an expression such as
13178   //  "((++k)++, k) = k" or "k = (k++, k++)". Both contain unsequenced
13179   //  operations before C++17 and both are well-defined in C++17).
13180   //
13181   // When visiting a node which uses/modify an object we first call notePreUse
13182   // or notePreMod before visiting its sub-expression(s). At this point the
13183   // children of the current node have not yet been visited and so the eventual
13184   // uses/modifications resulting from the children of the current node have not
13185   // been recorded yet.
13186   //
13187   // We then visit the children of the current node. After that notePostUse or
13188   // notePostMod is called. These will 1) detect an unsequenced modification
13189   // as side effect (as in "k++ + k") and 2) add a new usage with the
13190   // appropriate usage kind.
13191   //
13192   // We also have to be careful that some operation sequences modification as
13193   // side effect as well (for example: || or ,). To account for this we wrap
13194   // the visitation of such a sub-expression (for example: the LHS of || or ,)
13195   // with SequencedSubexpression. SequencedSubexpression is an RAII object
13196   // which record usages which are modifications as side effect, and then
13197   // downgrade them (or more accurately restore the previous usage which was a
13198   // modification as side effect) when exiting the scope of the sequenced
13199   // subexpression.
13200 
13201   void notePreUse(Object O, const Expr *UseExpr) {
13202     UsageInfo &UI = UsageMap[O];
13203     // Uses conflict with other modifications.
13204     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/false);
13205   }
13206 
13207   void notePostUse(Object O, const Expr *UseExpr) {
13208     UsageInfo &UI = UsageMap[O];
13209     checkUsage(O, UI, UseExpr, /*OtherKind=*/UK_ModAsSideEffect,
13210                /*IsModMod=*/false);
13211     addUsage(O, UI, UseExpr, /*UsageKind=*/UK_Use);
13212   }
13213 
13214   void notePreMod(Object O, const Expr *ModExpr) {
13215     UsageInfo &UI = UsageMap[O];
13216     // Modifications conflict with other modifications and with uses.
13217     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsValue, /*IsModMod=*/true);
13218     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_Use, /*IsModMod=*/false);
13219   }
13220 
13221   void notePostMod(Object O, const Expr *ModExpr, UsageKind UK) {
13222     UsageInfo &UI = UsageMap[O];
13223     checkUsage(O, UI, ModExpr, /*OtherKind=*/UK_ModAsSideEffect,
13224                /*IsModMod=*/true);
13225     addUsage(O, UI, ModExpr, /*UsageKind=*/UK);
13226   }
13227 
13228 public:
13229   SequenceChecker(Sema &S, const Expr *E,
13230                   SmallVectorImpl<const Expr *> &WorkList)
13231       : Base(S.Context), SemaRef(S), Region(Tree.root()), WorkList(WorkList) {
13232     Visit(E);
13233     // Silence a -Wunused-private-field since WorkList is now unused.
13234     // TODO: Evaluate if it can be used, and if not remove it.
13235     (void)this->WorkList;
13236   }
13237 
13238   void VisitStmt(const Stmt *S) {
13239     // Skip all statements which aren't expressions for now.
13240   }
13241 
13242   void VisitExpr(const Expr *E) {
13243     // By default, just recurse to evaluated subexpressions.
13244     Base::VisitStmt(E);
13245   }
13246 
13247   void VisitCastExpr(const CastExpr *E) {
13248     Object O = Object();
13249     if (E->getCastKind() == CK_LValueToRValue)
13250       O = getObject(E->getSubExpr(), false);
13251 
13252     if (O)
13253       notePreUse(O, E);
13254     VisitExpr(E);
13255     if (O)
13256       notePostUse(O, E);
13257   }
13258 
13259   void VisitSequencedExpressions(const Expr *SequencedBefore,
13260                                  const Expr *SequencedAfter) {
13261     SequenceTree::Seq BeforeRegion = Tree.allocate(Region);
13262     SequenceTree::Seq AfterRegion = Tree.allocate(Region);
13263     SequenceTree::Seq OldRegion = Region;
13264 
13265     {
13266       SequencedSubexpression SeqBefore(*this);
13267       Region = BeforeRegion;
13268       Visit(SequencedBefore);
13269     }
13270 
13271     Region = AfterRegion;
13272     Visit(SequencedAfter);
13273 
13274     Region = OldRegion;
13275 
13276     Tree.merge(BeforeRegion);
13277     Tree.merge(AfterRegion);
13278   }
13279 
13280   void VisitArraySubscriptExpr(const ArraySubscriptExpr *ASE) {
13281     // C++17 [expr.sub]p1:
13282     //   The expression E1[E2] is identical (by definition) to *((E1)+(E2)). The
13283     //   expression E1 is sequenced before the expression E2.
13284     if (SemaRef.getLangOpts().CPlusPlus17)
13285       VisitSequencedExpressions(ASE->getLHS(), ASE->getRHS());
13286     else {
13287       Visit(ASE->getLHS());
13288       Visit(ASE->getRHS());
13289     }
13290   }
13291 
13292   void VisitBinPtrMemD(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13293   void VisitBinPtrMemI(const BinaryOperator *BO) { VisitBinPtrMem(BO); }
13294   void VisitBinPtrMem(const BinaryOperator *BO) {
13295     // C++17 [expr.mptr.oper]p4:
13296     //  Abbreviating pm-expression.*cast-expression as E1.*E2, [...]
13297     //  the expression E1 is sequenced before the expression E2.
13298     if (SemaRef.getLangOpts().CPlusPlus17)
13299       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13300     else {
13301       Visit(BO->getLHS());
13302       Visit(BO->getRHS());
13303     }
13304   }
13305 
13306   void VisitBinShl(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13307   void VisitBinShr(const BinaryOperator *BO) { VisitBinShlShr(BO); }
13308   void VisitBinShlShr(const BinaryOperator *BO) {
13309     // C++17 [expr.shift]p4:
13310     //  The expression E1 is sequenced before the expression E2.
13311     if (SemaRef.getLangOpts().CPlusPlus17)
13312       VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13313     else {
13314       Visit(BO->getLHS());
13315       Visit(BO->getRHS());
13316     }
13317   }
13318 
13319   void VisitBinComma(const BinaryOperator *BO) {
13320     // C++11 [expr.comma]p1:
13321     //   Every value computation and side effect associated with the left
13322     //   expression is sequenced before every value computation and side
13323     //   effect associated with the right expression.
13324     VisitSequencedExpressions(BO->getLHS(), BO->getRHS());
13325   }
13326 
13327   void VisitBinAssign(const BinaryOperator *BO) {
13328     SequenceTree::Seq RHSRegion;
13329     SequenceTree::Seq LHSRegion;
13330     if (SemaRef.getLangOpts().CPlusPlus17) {
13331       RHSRegion = Tree.allocate(Region);
13332       LHSRegion = Tree.allocate(Region);
13333     } else {
13334       RHSRegion = Region;
13335       LHSRegion = Region;
13336     }
13337     SequenceTree::Seq OldRegion = Region;
13338 
13339     // C++11 [expr.ass]p1:
13340     //  [...] the assignment is sequenced after the value computation
13341     //  of the right and left operands, [...]
13342     //
13343     // so check it before inspecting the operands and update the
13344     // map afterwards.
13345     Object O = getObject(BO->getLHS(), /*Mod=*/true);
13346     if (O)
13347       notePreMod(O, BO);
13348 
13349     if (SemaRef.getLangOpts().CPlusPlus17) {
13350       // C++17 [expr.ass]p1:
13351       //  [...] The right operand is sequenced before the left operand. [...]
13352       {
13353         SequencedSubexpression SeqBefore(*this);
13354         Region = RHSRegion;
13355         Visit(BO->getRHS());
13356       }
13357 
13358       Region = LHSRegion;
13359       Visit(BO->getLHS());
13360 
13361       if (O && isa<CompoundAssignOperator>(BO))
13362         notePostUse(O, BO);
13363 
13364     } else {
13365       // C++11 does not specify any sequencing between the LHS and RHS.
13366       Region = LHSRegion;
13367       Visit(BO->getLHS());
13368 
13369       if (O && isa<CompoundAssignOperator>(BO))
13370         notePostUse(O, BO);
13371 
13372       Region = RHSRegion;
13373       Visit(BO->getRHS());
13374     }
13375 
13376     // C++11 [expr.ass]p1:
13377     //  the assignment is sequenced [...] before the value computation of the
13378     //  assignment expression.
13379     // C11 6.5.16/3 has no such rule.
13380     Region = OldRegion;
13381     if (O)
13382       notePostMod(O, BO,
13383                   SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13384                                                   : UK_ModAsSideEffect);
13385     if (SemaRef.getLangOpts().CPlusPlus17) {
13386       Tree.merge(RHSRegion);
13387       Tree.merge(LHSRegion);
13388     }
13389   }
13390 
13391   void VisitCompoundAssignOperator(const CompoundAssignOperator *CAO) {
13392     VisitBinAssign(CAO);
13393   }
13394 
13395   void VisitUnaryPreInc(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13396   void VisitUnaryPreDec(const UnaryOperator *UO) { VisitUnaryPreIncDec(UO); }
13397   void VisitUnaryPreIncDec(const UnaryOperator *UO) {
13398     Object O = getObject(UO->getSubExpr(), true);
13399     if (!O)
13400       return VisitExpr(UO);
13401 
13402     notePreMod(O, UO);
13403     Visit(UO->getSubExpr());
13404     // C++11 [expr.pre.incr]p1:
13405     //   the expression ++x is equivalent to x+=1
13406     notePostMod(O, UO,
13407                 SemaRef.getLangOpts().CPlusPlus ? UK_ModAsValue
13408                                                 : UK_ModAsSideEffect);
13409   }
13410 
13411   void VisitUnaryPostInc(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13412   void VisitUnaryPostDec(const UnaryOperator *UO) { VisitUnaryPostIncDec(UO); }
13413   void VisitUnaryPostIncDec(const UnaryOperator *UO) {
13414     Object O = getObject(UO->getSubExpr(), true);
13415     if (!O)
13416       return VisitExpr(UO);
13417 
13418     notePreMod(O, UO);
13419     Visit(UO->getSubExpr());
13420     notePostMod(O, UO, UK_ModAsSideEffect);
13421   }
13422 
13423   void VisitBinLOr(const BinaryOperator *BO) {
13424     // C++11 [expr.log.or]p2:
13425     //  If the second expression is evaluated, every value computation and
13426     //  side effect associated with the first expression is sequenced before
13427     //  every value computation and side effect associated with the
13428     //  second expression.
13429     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13430     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13431     SequenceTree::Seq OldRegion = Region;
13432 
13433     EvaluationTracker Eval(*this);
13434     {
13435       SequencedSubexpression Sequenced(*this);
13436       Region = LHSRegion;
13437       Visit(BO->getLHS());
13438     }
13439 
13440     // C++11 [expr.log.or]p1:
13441     //  [...] the second operand is not evaluated if the first operand
13442     //  evaluates to true.
13443     bool EvalResult = false;
13444     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13445     bool ShouldVisitRHS = !EvalOK || (EvalOK && !EvalResult);
13446     if (ShouldVisitRHS) {
13447       Region = RHSRegion;
13448       Visit(BO->getRHS());
13449     }
13450 
13451     Region = OldRegion;
13452     Tree.merge(LHSRegion);
13453     Tree.merge(RHSRegion);
13454   }
13455 
13456   void VisitBinLAnd(const BinaryOperator *BO) {
13457     // C++11 [expr.log.and]p2:
13458     //  If the second expression is evaluated, every value computation and
13459     //  side effect associated with the first expression is sequenced before
13460     //  every value computation and side effect associated with the
13461     //  second expression.
13462     SequenceTree::Seq LHSRegion = Tree.allocate(Region);
13463     SequenceTree::Seq RHSRegion = Tree.allocate(Region);
13464     SequenceTree::Seq OldRegion = Region;
13465 
13466     EvaluationTracker Eval(*this);
13467     {
13468       SequencedSubexpression Sequenced(*this);
13469       Region = LHSRegion;
13470       Visit(BO->getLHS());
13471     }
13472 
13473     // C++11 [expr.log.and]p1:
13474     //  [...] the second operand is not evaluated if the first operand is false.
13475     bool EvalResult = false;
13476     bool EvalOK = Eval.evaluate(BO->getLHS(), EvalResult);
13477     bool ShouldVisitRHS = !EvalOK || (EvalOK && EvalResult);
13478     if (ShouldVisitRHS) {
13479       Region = RHSRegion;
13480       Visit(BO->getRHS());
13481     }
13482 
13483     Region = OldRegion;
13484     Tree.merge(LHSRegion);
13485     Tree.merge(RHSRegion);
13486   }
13487 
13488   void VisitAbstractConditionalOperator(const AbstractConditionalOperator *CO) {
13489     // C++11 [expr.cond]p1:
13490     //  [...] Every value computation and side effect associated with the first
13491     //  expression is sequenced before every value computation and side effect
13492     //  associated with the second or third expression.
13493     SequenceTree::Seq ConditionRegion = Tree.allocate(Region);
13494 
13495     // No sequencing is specified between the true and false expression.
13496     // However since exactly one of both is going to be evaluated we can
13497     // consider them to be sequenced. This is needed to avoid warning on
13498     // something like "x ? y+= 1 : y += 2;" in the case where we will visit
13499     // both the true and false expressions because we can't evaluate x.
13500     // This will still allow us to detect an expression like (pre C++17)
13501     // "(x ? y += 1 : y += 2) = y".
13502     //
13503     // We don't wrap the visitation of the true and false expression with
13504     // SequencedSubexpression because we don't want to downgrade modifications
13505     // as side effect in the true and false expressions after the visition
13506     // is done. (for example in the expression "(x ? y++ : y++) + y" we should
13507     // not warn between the two "y++", but we should warn between the "y++"
13508     // and the "y".
13509     SequenceTree::Seq TrueRegion = Tree.allocate(Region);
13510     SequenceTree::Seq FalseRegion = Tree.allocate(Region);
13511     SequenceTree::Seq OldRegion = Region;
13512 
13513     EvaluationTracker Eval(*this);
13514     {
13515       SequencedSubexpression Sequenced(*this);
13516       Region = ConditionRegion;
13517       Visit(CO->getCond());
13518     }
13519 
13520     // C++11 [expr.cond]p1:
13521     // [...] The first expression is contextually converted to bool (Clause 4).
13522     // It is evaluated and if it is true, the result of the conditional
13523     // expression is the value of the second expression, otherwise that of the
13524     // third expression. Only one of the second and third expressions is
13525     // evaluated. [...]
13526     bool EvalResult = false;
13527     bool EvalOK = Eval.evaluate(CO->getCond(), EvalResult);
13528     bool ShouldVisitTrueExpr = !EvalOK || (EvalOK && EvalResult);
13529     bool ShouldVisitFalseExpr = !EvalOK || (EvalOK && !EvalResult);
13530     if (ShouldVisitTrueExpr) {
13531       Region = TrueRegion;
13532       Visit(CO->getTrueExpr());
13533     }
13534     if (ShouldVisitFalseExpr) {
13535       Region = FalseRegion;
13536       Visit(CO->getFalseExpr());
13537     }
13538 
13539     Region = OldRegion;
13540     Tree.merge(ConditionRegion);
13541     Tree.merge(TrueRegion);
13542     Tree.merge(FalseRegion);
13543   }
13544 
13545   void VisitCallExpr(const CallExpr *CE) {
13546     // FIXME: CXXNewExpr and CXXDeleteExpr implicitly call functions.
13547 
13548     if (CE->isUnevaluatedBuiltinCall(Context))
13549       return;
13550 
13551     // C++11 [intro.execution]p15:
13552     //   When calling a function [...], every value computation and side effect
13553     //   associated with any argument expression, or with the postfix expression
13554     //   designating the called function, is sequenced before execution of every
13555     //   expression or statement in the body of the function [and thus before
13556     //   the value computation of its result].
13557     SequencedSubexpression Sequenced(*this);
13558     SemaRef.runWithSufficientStackSpace(CE->getExprLoc(), [&] {
13559       // C++17 [expr.call]p5
13560       //   The postfix-expression is sequenced before each expression in the
13561       //   expression-list and any default argument. [...]
13562       SequenceTree::Seq CalleeRegion;
13563       SequenceTree::Seq OtherRegion;
13564       if (SemaRef.getLangOpts().CPlusPlus17) {
13565         CalleeRegion = Tree.allocate(Region);
13566         OtherRegion = Tree.allocate(Region);
13567       } else {
13568         CalleeRegion = Region;
13569         OtherRegion = Region;
13570       }
13571       SequenceTree::Seq OldRegion = Region;
13572 
13573       // Visit the callee expression first.
13574       Region = CalleeRegion;
13575       if (SemaRef.getLangOpts().CPlusPlus17) {
13576         SequencedSubexpression Sequenced(*this);
13577         Visit(CE->getCallee());
13578       } else {
13579         Visit(CE->getCallee());
13580       }
13581 
13582       // Then visit the argument expressions.
13583       Region = OtherRegion;
13584       for (const Expr *Argument : CE->arguments())
13585         Visit(Argument);
13586 
13587       Region = OldRegion;
13588       if (SemaRef.getLangOpts().CPlusPlus17) {
13589         Tree.merge(CalleeRegion);
13590         Tree.merge(OtherRegion);
13591       }
13592     });
13593   }
13594 
13595   void VisitCXXOperatorCallExpr(const CXXOperatorCallExpr *CXXOCE) {
13596     // C++17 [over.match.oper]p2:
13597     //   [...] the operator notation is first transformed to the equivalent
13598     //   function-call notation as summarized in Table 12 (where @ denotes one
13599     //   of the operators covered in the specified subclause). However, the
13600     //   operands are sequenced in the order prescribed for the built-in
13601     //   operator (Clause 8).
13602     //
13603     // From the above only overloaded binary operators and overloaded call
13604     // operators have sequencing rules in C++17 that we need to handle
13605     // separately.
13606     if (!SemaRef.getLangOpts().CPlusPlus17 ||
13607         (CXXOCE->getNumArgs() != 2 && CXXOCE->getOperator() != OO_Call))
13608       return VisitCallExpr(CXXOCE);
13609 
13610     enum {
13611       NoSequencing,
13612       LHSBeforeRHS,
13613       RHSBeforeLHS,
13614       LHSBeforeRest
13615     } SequencingKind;
13616     switch (CXXOCE->getOperator()) {
13617     case OO_Equal:
13618     case OO_PlusEqual:
13619     case OO_MinusEqual:
13620     case OO_StarEqual:
13621     case OO_SlashEqual:
13622     case OO_PercentEqual:
13623     case OO_CaretEqual:
13624     case OO_AmpEqual:
13625     case OO_PipeEqual:
13626     case OO_LessLessEqual:
13627     case OO_GreaterGreaterEqual:
13628       SequencingKind = RHSBeforeLHS;
13629       break;
13630 
13631     case OO_LessLess:
13632     case OO_GreaterGreater:
13633     case OO_AmpAmp:
13634     case OO_PipePipe:
13635     case OO_Comma:
13636     case OO_ArrowStar:
13637     case OO_Subscript:
13638       SequencingKind = LHSBeforeRHS;
13639       break;
13640 
13641     case OO_Call:
13642       SequencingKind = LHSBeforeRest;
13643       break;
13644 
13645     default:
13646       SequencingKind = NoSequencing;
13647       break;
13648     }
13649 
13650     if (SequencingKind == NoSequencing)
13651       return VisitCallExpr(CXXOCE);
13652 
13653     // This is a call, so all subexpressions are sequenced before the result.
13654     SequencedSubexpression Sequenced(*this);
13655 
13656     SemaRef.runWithSufficientStackSpace(CXXOCE->getExprLoc(), [&] {
13657       assert(SemaRef.getLangOpts().CPlusPlus17 &&
13658              "Should only get there with C++17 and above!");
13659       assert((CXXOCE->getNumArgs() == 2 || CXXOCE->getOperator() == OO_Call) &&
13660              "Should only get there with an overloaded binary operator"
13661              " or an overloaded call operator!");
13662 
13663       if (SequencingKind == LHSBeforeRest) {
13664         assert(CXXOCE->getOperator() == OO_Call &&
13665                "We should only have an overloaded call operator here!");
13666 
13667         // This is very similar to VisitCallExpr, except that we only have the
13668         // C++17 case. The postfix-expression is the first argument of the
13669         // CXXOperatorCallExpr. The expressions in the expression-list, if any,
13670         // are in the following arguments.
13671         //
13672         // Note that we intentionally do not visit the callee expression since
13673         // it is just a decayed reference to a function.
13674         SequenceTree::Seq PostfixExprRegion = Tree.allocate(Region);
13675         SequenceTree::Seq ArgsRegion = Tree.allocate(Region);
13676         SequenceTree::Seq OldRegion = Region;
13677 
13678         assert(CXXOCE->getNumArgs() >= 1 &&
13679                "An overloaded call operator must have at least one argument"
13680                " for the postfix-expression!");
13681         const Expr *PostfixExpr = CXXOCE->getArgs()[0];
13682         llvm::ArrayRef<const Expr *> Args(CXXOCE->getArgs() + 1,
13683                                           CXXOCE->getNumArgs() - 1);
13684 
13685         // Visit the postfix-expression first.
13686         {
13687           Region = PostfixExprRegion;
13688           SequencedSubexpression Sequenced(*this);
13689           Visit(PostfixExpr);
13690         }
13691 
13692         // Then visit the argument expressions.
13693         Region = ArgsRegion;
13694         for (const Expr *Arg : Args)
13695           Visit(Arg);
13696 
13697         Region = OldRegion;
13698         Tree.merge(PostfixExprRegion);
13699         Tree.merge(ArgsRegion);
13700       } else {
13701         assert(CXXOCE->getNumArgs() == 2 &&
13702                "Should only have two arguments here!");
13703         assert((SequencingKind == LHSBeforeRHS ||
13704                 SequencingKind == RHSBeforeLHS) &&
13705                "Unexpected sequencing kind!");
13706 
13707         // We do not visit the callee expression since it is just a decayed
13708         // reference to a function.
13709         const Expr *E1 = CXXOCE->getArg(0);
13710         const Expr *E2 = CXXOCE->getArg(1);
13711         if (SequencingKind == RHSBeforeLHS)
13712           std::swap(E1, E2);
13713 
13714         return VisitSequencedExpressions(E1, E2);
13715       }
13716     });
13717   }
13718 
13719   void VisitCXXConstructExpr(const CXXConstructExpr *CCE) {
13720     // This is a call, so all subexpressions are sequenced before the result.
13721     SequencedSubexpression Sequenced(*this);
13722 
13723     if (!CCE->isListInitialization())
13724       return VisitExpr(CCE);
13725 
13726     // In C++11, list initializations are sequenced.
13727     SmallVector<SequenceTree::Seq, 32> Elts;
13728     SequenceTree::Seq Parent = Region;
13729     for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
13730                                               E = CCE->arg_end();
13731          I != E; ++I) {
13732       Region = Tree.allocate(Parent);
13733       Elts.push_back(Region);
13734       Visit(*I);
13735     }
13736 
13737     // Forget that the initializers are sequenced.
13738     Region = Parent;
13739     for (unsigned I = 0; I < Elts.size(); ++I)
13740       Tree.merge(Elts[I]);
13741   }
13742 
13743   void VisitInitListExpr(const InitListExpr *ILE) {
13744     if (!SemaRef.getLangOpts().CPlusPlus11)
13745       return VisitExpr(ILE);
13746 
13747     // In C++11, list initializations are sequenced.
13748     SmallVector<SequenceTree::Seq, 32> Elts;
13749     SequenceTree::Seq Parent = Region;
13750     for (unsigned I = 0; I < ILE->getNumInits(); ++I) {
13751       const Expr *E = ILE->getInit(I);
13752       if (!E)
13753         continue;
13754       Region = Tree.allocate(Parent);
13755       Elts.push_back(Region);
13756       Visit(E);
13757     }
13758 
13759     // Forget that the initializers are sequenced.
13760     Region = Parent;
13761     for (unsigned I = 0; I < Elts.size(); ++I)
13762       Tree.merge(Elts[I]);
13763   }
13764 };
13765 
13766 } // namespace
13767 
13768 void Sema::CheckUnsequencedOperations(const Expr *E) {
13769   SmallVector<const Expr *, 8> WorkList;
13770   WorkList.push_back(E);
13771   while (!WorkList.empty()) {
13772     const Expr *Item = WorkList.pop_back_val();
13773     SequenceChecker(*this, Item, WorkList);
13774   }
13775 }
13776 
13777 void Sema::CheckCompletedExpr(Expr *E, SourceLocation CheckLoc,
13778                               bool IsConstexpr) {
13779   llvm::SaveAndRestore<bool> ConstantContext(
13780       isConstantEvaluatedOverride, IsConstexpr || isa<ConstantExpr>(E));
13781   CheckImplicitConversions(E, CheckLoc);
13782   if (!E->isInstantiationDependent())
13783     CheckUnsequencedOperations(E);
13784   if (!IsConstexpr && !E->isValueDependent())
13785     CheckForIntOverflow(E);
13786   DiagnoseMisalignedMembers();
13787 }
13788 
13789 void Sema::CheckBitFieldInitialization(SourceLocation InitLoc,
13790                                        FieldDecl *BitField,
13791                                        Expr *Init) {
13792   (void) AnalyzeBitFieldAssignment(*this, BitField, Init, InitLoc);
13793 }
13794 
13795 static void diagnoseArrayStarInParamType(Sema &S, QualType PType,
13796                                          SourceLocation Loc) {
13797   if (!PType->isVariablyModifiedType())
13798     return;
13799   if (const auto *PointerTy = dyn_cast<PointerType>(PType)) {
13800     diagnoseArrayStarInParamType(S, PointerTy->getPointeeType(), Loc);
13801     return;
13802   }
13803   if (const auto *ReferenceTy = dyn_cast<ReferenceType>(PType)) {
13804     diagnoseArrayStarInParamType(S, ReferenceTy->getPointeeType(), Loc);
13805     return;
13806   }
13807   if (const auto *ParenTy = dyn_cast<ParenType>(PType)) {
13808     diagnoseArrayStarInParamType(S, ParenTy->getInnerType(), Loc);
13809     return;
13810   }
13811 
13812   const ArrayType *AT = S.Context.getAsArrayType(PType);
13813   if (!AT)
13814     return;
13815 
13816   if (AT->getSizeModifier() != ArrayType::Star) {
13817     diagnoseArrayStarInParamType(S, AT->getElementType(), Loc);
13818     return;
13819   }
13820 
13821   S.Diag(Loc, diag::err_array_star_in_function_definition);
13822 }
13823 
13824 /// CheckParmsForFunctionDef - Check that the parameters of the given
13825 /// function are appropriate for the definition of a function. This
13826 /// takes care of any checks that cannot be performed on the
13827 /// declaration itself, e.g., that the types of each of the function
13828 /// parameters are complete.
13829 bool Sema::CheckParmsForFunctionDef(ArrayRef<ParmVarDecl *> Parameters,
13830                                     bool CheckParameterNames) {
13831   bool HasInvalidParm = false;
13832   for (ParmVarDecl *Param : Parameters) {
13833     // C99 6.7.5.3p4: the parameters in a parameter type list in a
13834     // function declarator that is part of a function definition of
13835     // that function shall not have incomplete type.
13836     //
13837     // This is also C++ [dcl.fct]p6.
13838     if (!Param->isInvalidDecl() &&
13839         RequireCompleteType(Param->getLocation(), Param->getType(),
13840                             diag::err_typecheck_decl_incomplete_type)) {
13841       Param->setInvalidDecl();
13842       HasInvalidParm = true;
13843     }
13844 
13845     // C99 6.9.1p5: If the declarator includes a parameter type list, the
13846     // declaration of each parameter shall include an identifier.
13847     if (CheckParameterNames && Param->getIdentifier() == nullptr &&
13848         !Param->isImplicit() && !getLangOpts().CPlusPlus) {
13849       // Diagnose this as an extension in C17 and earlier.
13850       if (!getLangOpts().C2x)
13851         Diag(Param->getLocation(), diag::ext_parameter_name_omitted_c2x);
13852     }
13853 
13854     // C99 6.7.5.3p12:
13855     //   If the function declarator is not part of a definition of that
13856     //   function, parameters may have incomplete type and may use the [*]
13857     //   notation in their sequences of declarator specifiers to specify
13858     //   variable length array types.
13859     QualType PType = Param->getOriginalType();
13860     // FIXME: This diagnostic should point the '[*]' if source-location
13861     // information is added for it.
13862     diagnoseArrayStarInParamType(*this, PType, Param->getLocation());
13863 
13864     // If the parameter is a c++ class type and it has to be destructed in the
13865     // callee function, declare the destructor so that it can be called by the
13866     // callee function. Do not perform any direct access check on the dtor here.
13867     if (!Param->isInvalidDecl()) {
13868       if (CXXRecordDecl *ClassDecl = Param->getType()->getAsCXXRecordDecl()) {
13869         if (!ClassDecl->isInvalidDecl() &&
13870             !ClassDecl->hasIrrelevantDestructor() &&
13871             !ClassDecl->isDependentContext() &&
13872             ClassDecl->isParamDestroyedInCallee()) {
13873           CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
13874           MarkFunctionReferenced(Param->getLocation(), Destructor);
13875           DiagnoseUseOfDecl(Destructor, Param->getLocation());
13876         }
13877       }
13878     }
13879 
13880     // Parameters with the pass_object_size attribute only need to be marked
13881     // constant at function definitions. Because we lack information about
13882     // whether we're on a declaration or definition when we're instantiating the
13883     // attribute, we need to check for constness here.
13884     if (const auto *Attr = Param->getAttr<PassObjectSizeAttr>())
13885       if (!Param->getType().isConstQualified())
13886         Diag(Param->getLocation(), diag::err_attribute_pointers_only)
13887             << Attr->getSpelling() << 1;
13888 
13889     // Check for parameter names shadowing fields from the class.
13890     if (LangOpts.CPlusPlus && !Param->isInvalidDecl()) {
13891       // The owning context for the parameter should be the function, but we
13892       // want to see if this function's declaration context is a record.
13893       DeclContext *DC = Param->getDeclContext();
13894       if (DC && DC->isFunctionOrMethod()) {
13895         if (auto *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
13896           CheckShadowInheritedFields(Param->getLocation(), Param->getDeclName(),
13897                                      RD, /*DeclIsField*/ false);
13898       }
13899     }
13900   }
13901 
13902   return HasInvalidParm;
13903 }
13904 
13905 Optional<std::pair<CharUnits, CharUnits>>
13906 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx);
13907 
13908 /// Compute the alignment and offset of the base class object given the
13909 /// derived-to-base cast expression and the alignment and offset of the derived
13910 /// class object.
13911 static std::pair<CharUnits, CharUnits>
13912 getDerivedToBaseAlignmentAndOffset(const CastExpr *CE, QualType DerivedType,
13913                                    CharUnits BaseAlignment, CharUnits Offset,
13914                                    ASTContext &Ctx) {
13915   for (auto PathI = CE->path_begin(), PathE = CE->path_end(); PathI != PathE;
13916        ++PathI) {
13917     const CXXBaseSpecifier *Base = *PathI;
13918     const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
13919     if (Base->isVirtual()) {
13920       // The complete object may have a lower alignment than the non-virtual
13921       // alignment of the base, in which case the base may be misaligned. Choose
13922       // the smaller of the non-virtual alignment and BaseAlignment, which is a
13923       // conservative lower bound of the complete object alignment.
13924       CharUnits NonVirtualAlignment =
13925           Ctx.getASTRecordLayout(BaseDecl).getNonVirtualAlignment();
13926       BaseAlignment = std::min(BaseAlignment, NonVirtualAlignment);
13927       Offset = CharUnits::Zero();
13928     } else {
13929       const ASTRecordLayout &RL =
13930           Ctx.getASTRecordLayout(DerivedType->getAsCXXRecordDecl());
13931       Offset += RL.getBaseClassOffset(BaseDecl);
13932     }
13933     DerivedType = Base->getType();
13934   }
13935 
13936   return std::make_pair(BaseAlignment, Offset);
13937 }
13938 
13939 /// Compute the alignment and offset of a binary additive operator.
13940 static Optional<std::pair<CharUnits, CharUnits>>
13941 getAlignmentAndOffsetFromBinAddOrSub(const Expr *PtrE, const Expr *IntE,
13942                                      bool IsSub, ASTContext &Ctx) {
13943   QualType PointeeType = PtrE->getType()->getPointeeType();
13944 
13945   if (!PointeeType->isConstantSizeType())
13946     return llvm::None;
13947 
13948   auto P = getBaseAlignmentAndOffsetFromPtr(PtrE, Ctx);
13949 
13950   if (!P)
13951     return llvm::None;
13952 
13953   CharUnits EltSize = Ctx.getTypeSizeInChars(PointeeType);
13954   if (Optional<llvm::APSInt> IdxRes = IntE->getIntegerConstantExpr(Ctx)) {
13955     CharUnits Offset = EltSize * IdxRes->getExtValue();
13956     if (IsSub)
13957       Offset = -Offset;
13958     return std::make_pair(P->first, P->second + Offset);
13959   }
13960 
13961   // If the integer expression isn't a constant expression, compute the lower
13962   // bound of the alignment using the alignment and offset of the pointer
13963   // expression and the element size.
13964   return std::make_pair(
13965       P->first.alignmentAtOffset(P->second).alignmentAtOffset(EltSize),
13966       CharUnits::Zero());
13967 }
13968 
13969 /// This helper function takes an lvalue expression and returns the alignment of
13970 /// a VarDecl and a constant offset from the VarDecl.
13971 Optional<std::pair<CharUnits, CharUnits>>
13972 static getBaseAlignmentAndOffsetFromLValue(const Expr *E, ASTContext &Ctx) {
13973   E = E->IgnoreParens();
13974   switch (E->getStmtClass()) {
13975   default:
13976     break;
13977   case Stmt::CStyleCastExprClass:
13978   case Stmt::CXXStaticCastExprClass:
13979   case Stmt::ImplicitCastExprClass: {
13980     auto *CE = cast<CastExpr>(E);
13981     const Expr *From = CE->getSubExpr();
13982     switch (CE->getCastKind()) {
13983     default:
13984       break;
13985     case CK_NoOp:
13986       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13987     case CK_UncheckedDerivedToBase:
13988     case CK_DerivedToBase: {
13989       auto P = getBaseAlignmentAndOffsetFromLValue(From, Ctx);
13990       if (!P)
13991         break;
13992       return getDerivedToBaseAlignmentAndOffset(CE, From->getType(), P->first,
13993                                                 P->second, Ctx);
13994     }
13995     }
13996     break;
13997   }
13998   case Stmt::ArraySubscriptExprClass: {
13999     auto *ASE = cast<ArraySubscriptExpr>(E);
14000     return getAlignmentAndOffsetFromBinAddOrSub(ASE->getBase(), ASE->getIdx(),
14001                                                 false, Ctx);
14002   }
14003   case Stmt::DeclRefExprClass: {
14004     if (auto *VD = dyn_cast<VarDecl>(cast<DeclRefExpr>(E)->getDecl())) {
14005       // FIXME: If VD is captured by copy or is an escaping __block variable,
14006       // use the alignment of VD's type.
14007       if (!VD->getType()->isReferenceType())
14008         return std::make_pair(Ctx.getDeclAlign(VD), CharUnits::Zero());
14009       if (VD->hasInit())
14010         return getBaseAlignmentAndOffsetFromLValue(VD->getInit(), Ctx);
14011     }
14012     break;
14013   }
14014   case Stmt::MemberExprClass: {
14015     auto *ME = cast<MemberExpr>(E);
14016     auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
14017     if (!FD || FD->getType()->isReferenceType())
14018       break;
14019     Optional<std::pair<CharUnits, CharUnits>> P;
14020     if (ME->isArrow())
14021       P = getBaseAlignmentAndOffsetFromPtr(ME->getBase(), Ctx);
14022     else
14023       P = getBaseAlignmentAndOffsetFromLValue(ME->getBase(), Ctx);
14024     if (!P)
14025       break;
14026     const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(FD->getParent());
14027     uint64_t Offset = Layout.getFieldOffset(FD->getFieldIndex());
14028     return std::make_pair(P->first,
14029                           P->second + CharUnits::fromQuantity(Offset));
14030   }
14031   case Stmt::UnaryOperatorClass: {
14032     auto *UO = cast<UnaryOperator>(E);
14033     switch (UO->getOpcode()) {
14034     default:
14035       break;
14036     case UO_Deref:
14037       return getBaseAlignmentAndOffsetFromPtr(UO->getSubExpr(), Ctx);
14038     }
14039     break;
14040   }
14041   case Stmt::BinaryOperatorClass: {
14042     auto *BO = cast<BinaryOperator>(E);
14043     auto Opcode = BO->getOpcode();
14044     switch (Opcode) {
14045     default:
14046       break;
14047     case BO_Comma:
14048       return getBaseAlignmentAndOffsetFromLValue(BO->getRHS(), Ctx);
14049     }
14050     break;
14051   }
14052   }
14053   return llvm::None;
14054 }
14055 
14056 /// This helper function takes a pointer expression and returns the alignment of
14057 /// a VarDecl and a constant offset from the VarDecl.
14058 Optional<std::pair<CharUnits, CharUnits>>
14059 static getBaseAlignmentAndOffsetFromPtr(const Expr *E, ASTContext &Ctx) {
14060   E = E->IgnoreParens();
14061   switch (E->getStmtClass()) {
14062   default:
14063     break;
14064   case Stmt::CStyleCastExprClass:
14065   case Stmt::CXXStaticCastExprClass:
14066   case Stmt::ImplicitCastExprClass: {
14067     auto *CE = cast<CastExpr>(E);
14068     const Expr *From = CE->getSubExpr();
14069     switch (CE->getCastKind()) {
14070     default:
14071       break;
14072     case CK_NoOp:
14073       return getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14074     case CK_ArrayToPointerDecay:
14075       return getBaseAlignmentAndOffsetFromLValue(From, Ctx);
14076     case CK_UncheckedDerivedToBase:
14077     case CK_DerivedToBase: {
14078       auto P = getBaseAlignmentAndOffsetFromPtr(From, Ctx);
14079       if (!P)
14080         break;
14081       return getDerivedToBaseAlignmentAndOffset(
14082           CE, From->getType()->getPointeeType(), P->first, P->second, Ctx);
14083     }
14084     }
14085     break;
14086   }
14087   case Stmt::CXXThisExprClass: {
14088     auto *RD = E->getType()->getPointeeType()->getAsCXXRecordDecl();
14089     CharUnits Alignment = Ctx.getASTRecordLayout(RD).getNonVirtualAlignment();
14090     return std::make_pair(Alignment, CharUnits::Zero());
14091   }
14092   case Stmt::UnaryOperatorClass: {
14093     auto *UO = cast<UnaryOperator>(E);
14094     if (UO->getOpcode() == UO_AddrOf)
14095       return getBaseAlignmentAndOffsetFromLValue(UO->getSubExpr(), Ctx);
14096     break;
14097   }
14098   case Stmt::BinaryOperatorClass: {
14099     auto *BO = cast<BinaryOperator>(E);
14100     auto Opcode = BO->getOpcode();
14101     switch (Opcode) {
14102     default:
14103       break;
14104     case BO_Add:
14105     case BO_Sub: {
14106       const Expr *LHS = BO->getLHS(), *RHS = BO->getRHS();
14107       if (Opcode == BO_Add && !RHS->getType()->isIntegralOrEnumerationType())
14108         std::swap(LHS, RHS);
14109       return getAlignmentAndOffsetFromBinAddOrSub(LHS, RHS, Opcode == BO_Sub,
14110                                                   Ctx);
14111     }
14112     case BO_Comma:
14113       return getBaseAlignmentAndOffsetFromPtr(BO->getRHS(), Ctx);
14114     }
14115     break;
14116   }
14117   }
14118   return llvm::None;
14119 }
14120 
14121 static CharUnits getPresumedAlignmentOfPointer(const Expr *E, Sema &S) {
14122   // See if we can compute the alignment of a VarDecl and an offset from it.
14123   Optional<std::pair<CharUnits, CharUnits>> P =
14124       getBaseAlignmentAndOffsetFromPtr(E, S.Context);
14125 
14126   if (P)
14127     return P->first.alignmentAtOffset(P->second);
14128 
14129   // If that failed, return the type's alignment.
14130   return S.Context.getTypeAlignInChars(E->getType()->getPointeeType());
14131 }
14132 
14133 /// CheckCastAlign - Implements -Wcast-align, which warns when a
14134 /// pointer cast increases the alignment requirements.
14135 void Sema::CheckCastAlign(Expr *Op, QualType T, SourceRange TRange) {
14136   // This is actually a lot of work to potentially be doing on every
14137   // cast; don't do it if we're ignoring -Wcast_align (as is the default).
14138   if (getDiagnostics().isIgnored(diag::warn_cast_align, TRange.getBegin()))
14139     return;
14140 
14141   // Ignore dependent types.
14142   if (T->isDependentType() || Op->getType()->isDependentType())
14143     return;
14144 
14145   // Require that the destination be a pointer type.
14146   const PointerType *DestPtr = T->getAs<PointerType>();
14147   if (!DestPtr) return;
14148 
14149   // If the destination has alignment 1, we're done.
14150   QualType DestPointee = DestPtr->getPointeeType();
14151   if (DestPointee->isIncompleteType()) return;
14152   CharUnits DestAlign = Context.getTypeAlignInChars(DestPointee);
14153   if (DestAlign.isOne()) return;
14154 
14155   // Require that the source be a pointer type.
14156   const PointerType *SrcPtr = Op->getType()->getAs<PointerType>();
14157   if (!SrcPtr) return;
14158   QualType SrcPointee = SrcPtr->getPointeeType();
14159 
14160   // Explicitly allow casts from cv void*.  We already implicitly
14161   // allowed casts to cv void*, since they have alignment 1.
14162   // Also allow casts involving incomplete types, which implicitly
14163   // includes 'void'.
14164   if (SrcPointee->isIncompleteType()) return;
14165 
14166   CharUnits SrcAlign = getPresumedAlignmentOfPointer(Op, *this);
14167 
14168   if (SrcAlign >= DestAlign) return;
14169 
14170   Diag(TRange.getBegin(), diag::warn_cast_align)
14171     << Op->getType() << T
14172     << static_cast<unsigned>(SrcAlign.getQuantity())
14173     << static_cast<unsigned>(DestAlign.getQuantity())
14174     << TRange << Op->getSourceRange();
14175 }
14176 
14177 /// Check whether this array fits the idiom of a size-one tail padded
14178 /// array member of a struct.
14179 ///
14180 /// We avoid emitting out-of-bounds access warnings for such arrays as they are
14181 /// commonly used to emulate flexible arrays in C89 code.
14182 static bool IsTailPaddedMemberArray(Sema &S, const llvm::APInt &Size,
14183                                     const NamedDecl *ND) {
14184   if (Size != 1 || !ND) return false;
14185 
14186   const FieldDecl *FD = dyn_cast<FieldDecl>(ND);
14187   if (!FD) return false;
14188 
14189   // Don't consider sizes resulting from macro expansions or template argument
14190   // substitution to form C89 tail-padded arrays.
14191 
14192   TypeSourceInfo *TInfo = FD->getTypeSourceInfo();
14193   while (TInfo) {
14194     TypeLoc TL = TInfo->getTypeLoc();
14195     // Look through typedefs.
14196     if (TypedefTypeLoc TTL = TL.getAs<TypedefTypeLoc>()) {
14197       const TypedefNameDecl *TDL = TTL.getTypedefNameDecl();
14198       TInfo = TDL->getTypeSourceInfo();
14199       continue;
14200     }
14201     if (ConstantArrayTypeLoc CTL = TL.getAs<ConstantArrayTypeLoc>()) {
14202       const Expr *SizeExpr = dyn_cast<IntegerLiteral>(CTL.getSizeExpr());
14203       if (!SizeExpr || SizeExpr->getExprLoc().isMacroID())
14204         return false;
14205     }
14206     break;
14207   }
14208 
14209   const RecordDecl *RD = dyn_cast<RecordDecl>(FD->getDeclContext());
14210   if (!RD) return false;
14211   if (RD->isUnion()) return false;
14212   if (const CXXRecordDecl *CRD = dyn_cast<CXXRecordDecl>(RD)) {
14213     if (!CRD->isStandardLayout()) return false;
14214   }
14215 
14216   // See if this is the last field decl in the record.
14217   const Decl *D = FD;
14218   while ((D = D->getNextDeclInContext()))
14219     if (isa<FieldDecl>(D))
14220       return false;
14221   return true;
14222 }
14223 
14224 void Sema::CheckArrayAccess(const Expr *BaseExpr, const Expr *IndexExpr,
14225                             const ArraySubscriptExpr *ASE,
14226                             bool AllowOnePastEnd, bool IndexNegated) {
14227   // Already diagnosed by the constant evaluator.
14228   if (isConstantEvaluated())
14229     return;
14230 
14231   IndexExpr = IndexExpr->IgnoreParenImpCasts();
14232   if (IndexExpr->isValueDependent())
14233     return;
14234 
14235   const Type *EffectiveType =
14236       BaseExpr->getType()->getPointeeOrArrayElementType();
14237   BaseExpr = BaseExpr->IgnoreParenCasts();
14238   const ConstantArrayType *ArrayTy =
14239       Context.getAsConstantArrayType(BaseExpr->getType());
14240 
14241   if (!ArrayTy)
14242     return;
14243 
14244   const Type *BaseType = ArrayTy->getElementType().getTypePtr();
14245   if (EffectiveType->isDependentType() || BaseType->isDependentType())
14246     return;
14247 
14248   Expr::EvalResult Result;
14249   if (!IndexExpr->EvaluateAsInt(Result, Context, Expr::SE_AllowSideEffects))
14250     return;
14251 
14252   llvm::APSInt index = Result.Val.getInt();
14253   if (IndexNegated)
14254     index = -index;
14255 
14256   const NamedDecl *ND = nullptr;
14257   if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14258     ND = DRE->getDecl();
14259   if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14260     ND = ME->getMemberDecl();
14261 
14262   if (index.isUnsigned() || !index.isNegative()) {
14263     // It is possible that the type of the base expression after
14264     // IgnoreParenCasts is incomplete, even though the type of the base
14265     // expression before IgnoreParenCasts is complete (see PR39746 for an
14266     // example). In this case we have no information about whether the array
14267     // access exceeds the array bounds. However we can still diagnose an array
14268     // access which precedes the array bounds.
14269     if (BaseType->isIncompleteType())
14270       return;
14271 
14272     llvm::APInt size = ArrayTy->getSize();
14273     if (!size.isStrictlyPositive())
14274       return;
14275 
14276     if (BaseType != EffectiveType) {
14277       // Make sure we're comparing apples to apples when comparing index to size
14278       uint64_t ptrarith_typesize = Context.getTypeSize(EffectiveType);
14279       uint64_t array_typesize = Context.getTypeSize(BaseType);
14280       // Handle ptrarith_typesize being zero, such as when casting to void*
14281       if (!ptrarith_typesize) ptrarith_typesize = 1;
14282       if (ptrarith_typesize != array_typesize) {
14283         // There's a cast to a different size type involved
14284         uint64_t ratio = array_typesize / ptrarith_typesize;
14285         // TODO: Be smarter about handling cases where array_typesize is not a
14286         // multiple of ptrarith_typesize
14287         if (ptrarith_typesize * ratio == array_typesize)
14288           size *= llvm::APInt(size.getBitWidth(), ratio);
14289       }
14290     }
14291 
14292     if (size.getBitWidth() > index.getBitWidth())
14293       index = index.zext(size.getBitWidth());
14294     else if (size.getBitWidth() < index.getBitWidth())
14295       size = size.zext(index.getBitWidth());
14296 
14297     // For array subscripting the index must be less than size, but for pointer
14298     // arithmetic also allow the index (offset) to be equal to size since
14299     // computing the next address after the end of the array is legal and
14300     // commonly done e.g. in C++ iterators and range-based for loops.
14301     if (AllowOnePastEnd ? index.ule(size) : index.ult(size))
14302       return;
14303 
14304     // Also don't warn for arrays of size 1 which are members of some
14305     // structure. These are often used to approximate flexible arrays in C89
14306     // code.
14307     if (IsTailPaddedMemberArray(*this, size, ND))
14308       return;
14309 
14310     // Suppress the warning if the subscript expression (as identified by the
14311     // ']' location) and the index expression are both from macro expansions
14312     // within a system header.
14313     if (ASE) {
14314       SourceLocation RBracketLoc = SourceMgr.getSpellingLoc(
14315           ASE->getRBracketLoc());
14316       if (SourceMgr.isInSystemHeader(RBracketLoc)) {
14317         SourceLocation IndexLoc =
14318             SourceMgr.getSpellingLoc(IndexExpr->getBeginLoc());
14319         if (SourceMgr.isWrittenInSameFile(RBracketLoc, IndexLoc))
14320           return;
14321       }
14322     }
14323 
14324     unsigned DiagID = diag::warn_ptr_arith_exceeds_bounds;
14325     if (ASE)
14326       DiagID = diag::warn_array_index_exceeds_bounds;
14327 
14328     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14329                         PDiag(DiagID) << index.toString(10, true)
14330                                       << size.toString(10, true)
14331                                       << (unsigned)size.getLimitedValue(~0U)
14332                                       << IndexExpr->getSourceRange());
14333   } else {
14334     unsigned DiagID = diag::warn_array_index_precedes_bounds;
14335     if (!ASE) {
14336       DiagID = diag::warn_ptr_arith_precedes_bounds;
14337       if (index.isNegative()) index = -index;
14338     }
14339 
14340     DiagRuntimeBehavior(BaseExpr->getBeginLoc(), BaseExpr,
14341                         PDiag(DiagID) << index.toString(10, true)
14342                                       << IndexExpr->getSourceRange());
14343   }
14344 
14345   if (!ND) {
14346     // Try harder to find a NamedDecl to point at in the note.
14347     while (const ArraySubscriptExpr *ASE =
14348            dyn_cast<ArraySubscriptExpr>(BaseExpr))
14349       BaseExpr = ASE->getBase()->IgnoreParenCasts();
14350     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
14351       ND = DRE->getDecl();
14352     if (const MemberExpr *ME = dyn_cast<MemberExpr>(BaseExpr))
14353       ND = ME->getMemberDecl();
14354   }
14355 
14356   if (ND)
14357     DiagRuntimeBehavior(ND->getBeginLoc(), BaseExpr,
14358                         PDiag(diag::note_array_declared_here) << ND);
14359 }
14360 
14361 void Sema::CheckArrayAccess(const Expr *expr) {
14362   int AllowOnePastEnd = 0;
14363   while (expr) {
14364     expr = expr->IgnoreParenImpCasts();
14365     switch (expr->getStmtClass()) {
14366       case Stmt::ArraySubscriptExprClass: {
14367         const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(expr);
14368         CheckArrayAccess(ASE->getBase(), ASE->getIdx(), ASE,
14369                          AllowOnePastEnd > 0);
14370         expr = ASE->getBase();
14371         break;
14372       }
14373       case Stmt::MemberExprClass: {
14374         expr = cast<MemberExpr>(expr)->getBase();
14375         break;
14376       }
14377       case Stmt::OMPArraySectionExprClass: {
14378         const OMPArraySectionExpr *ASE = cast<OMPArraySectionExpr>(expr);
14379         if (ASE->getLowerBound())
14380           CheckArrayAccess(ASE->getBase(), ASE->getLowerBound(),
14381                            /*ASE=*/nullptr, AllowOnePastEnd > 0);
14382         return;
14383       }
14384       case Stmt::UnaryOperatorClass: {
14385         // Only unwrap the * and & unary operators
14386         const UnaryOperator *UO = cast<UnaryOperator>(expr);
14387         expr = UO->getSubExpr();
14388         switch (UO->getOpcode()) {
14389           case UO_AddrOf:
14390             AllowOnePastEnd++;
14391             break;
14392           case UO_Deref:
14393             AllowOnePastEnd--;
14394             break;
14395           default:
14396             return;
14397         }
14398         break;
14399       }
14400       case Stmt::ConditionalOperatorClass: {
14401         const ConditionalOperator *cond = cast<ConditionalOperator>(expr);
14402         if (const Expr *lhs = cond->getLHS())
14403           CheckArrayAccess(lhs);
14404         if (const Expr *rhs = cond->getRHS())
14405           CheckArrayAccess(rhs);
14406         return;
14407       }
14408       case Stmt::CXXOperatorCallExprClass: {
14409         const auto *OCE = cast<CXXOperatorCallExpr>(expr);
14410         for (const auto *Arg : OCE->arguments())
14411           CheckArrayAccess(Arg);
14412         return;
14413       }
14414       default:
14415         return;
14416     }
14417   }
14418 }
14419 
14420 //===--- CHECK: Objective-C retain cycles ----------------------------------//
14421 
14422 namespace {
14423 
14424 struct RetainCycleOwner {
14425   VarDecl *Variable = nullptr;
14426   SourceRange Range;
14427   SourceLocation Loc;
14428   bool Indirect = false;
14429 
14430   RetainCycleOwner() = default;
14431 
14432   void setLocsFrom(Expr *e) {
14433     Loc = e->getExprLoc();
14434     Range = e->getSourceRange();
14435   }
14436 };
14437 
14438 } // namespace
14439 
14440 /// Consider whether capturing the given variable can possibly lead to
14441 /// a retain cycle.
14442 static bool considerVariable(VarDecl *var, Expr *ref, RetainCycleOwner &owner) {
14443   // In ARC, it's captured strongly iff the variable has __strong
14444   // lifetime.  In MRR, it's captured strongly if the variable is
14445   // __block and has an appropriate type.
14446   if (var->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14447     return false;
14448 
14449   owner.Variable = var;
14450   if (ref)
14451     owner.setLocsFrom(ref);
14452   return true;
14453 }
14454 
14455 static bool findRetainCycleOwner(Sema &S, Expr *e, RetainCycleOwner &owner) {
14456   while (true) {
14457     e = e->IgnoreParens();
14458     if (CastExpr *cast = dyn_cast<CastExpr>(e)) {
14459       switch (cast->getCastKind()) {
14460       case CK_BitCast:
14461       case CK_LValueBitCast:
14462       case CK_LValueToRValue:
14463       case CK_ARCReclaimReturnedObject:
14464         e = cast->getSubExpr();
14465         continue;
14466 
14467       default:
14468         return false;
14469       }
14470     }
14471 
14472     if (ObjCIvarRefExpr *ref = dyn_cast<ObjCIvarRefExpr>(e)) {
14473       ObjCIvarDecl *ivar = ref->getDecl();
14474       if (ivar->getType().getObjCLifetime() != Qualifiers::OCL_Strong)
14475         return false;
14476 
14477       // Try to find a retain cycle in the base.
14478       if (!findRetainCycleOwner(S, ref->getBase(), owner))
14479         return false;
14480 
14481       if (ref->isFreeIvar()) owner.setLocsFrom(ref);
14482       owner.Indirect = true;
14483       return true;
14484     }
14485 
14486     if (DeclRefExpr *ref = dyn_cast<DeclRefExpr>(e)) {
14487       VarDecl *var = dyn_cast<VarDecl>(ref->getDecl());
14488       if (!var) return false;
14489       return considerVariable(var, ref, owner);
14490     }
14491 
14492     if (MemberExpr *member = dyn_cast<MemberExpr>(e)) {
14493       if (member->isArrow()) return false;
14494 
14495       // Don't count this as an indirect ownership.
14496       e = member->getBase();
14497       continue;
14498     }
14499 
14500     if (PseudoObjectExpr *pseudo = dyn_cast<PseudoObjectExpr>(e)) {
14501       // Only pay attention to pseudo-objects on property references.
14502       ObjCPropertyRefExpr *pre
14503         = dyn_cast<ObjCPropertyRefExpr>(pseudo->getSyntacticForm()
14504                                               ->IgnoreParens());
14505       if (!pre) return false;
14506       if (pre->isImplicitProperty()) return false;
14507       ObjCPropertyDecl *property = pre->getExplicitProperty();
14508       if (!property->isRetaining() &&
14509           !(property->getPropertyIvarDecl() &&
14510             property->getPropertyIvarDecl()->getType()
14511               .getObjCLifetime() == Qualifiers::OCL_Strong))
14512           return false;
14513 
14514       owner.Indirect = true;
14515       if (pre->isSuperReceiver()) {
14516         owner.Variable = S.getCurMethodDecl()->getSelfDecl();
14517         if (!owner.Variable)
14518           return false;
14519         owner.Loc = pre->getLocation();
14520         owner.Range = pre->getSourceRange();
14521         return true;
14522       }
14523       e = const_cast<Expr*>(cast<OpaqueValueExpr>(pre->getBase())
14524                               ->getSourceExpr());
14525       continue;
14526     }
14527 
14528     // Array ivars?
14529 
14530     return false;
14531   }
14532 }
14533 
14534 namespace {
14535 
14536   struct FindCaptureVisitor : EvaluatedExprVisitor<FindCaptureVisitor> {
14537     ASTContext &Context;
14538     VarDecl *Variable;
14539     Expr *Capturer = nullptr;
14540     bool VarWillBeReased = false;
14541 
14542     FindCaptureVisitor(ASTContext &Context, VarDecl *variable)
14543         : EvaluatedExprVisitor<FindCaptureVisitor>(Context),
14544           Context(Context), Variable(variable) {}
14545 
14546     void VisitDeclRefExpr(DeclRefExpr *ref) {
14547       if (ref->getDecl() == Variable && !Capturer)
14548         Capturer = ref;
14549     }
14550 
14551     void VisitObjCIvarRefExpr(ObjCIvarRefExpr *ref) {
14552       if (Capturer) return;
14553       Visit(ref->getBase());
14554       if (Capturer && ref->isFreeIvar())
14555         Capturer = ref;
14556     }
14557 
14558     void VisitBlockExpr(BlockExpr *block) {
14559       // Look inside nested blocks
14560       if (block->getBlockDecl()->capturesVariable(Variable))
14561         Visit(block->getBlockDecl()->getBody());
14562     }
14563 
14564     void VisitOpaqueValueExpr(OpaqueValueExpr *OVE) {
14565       if (Capturer) return;
14566       if (OVE->getSourceExpr())
14567         Visit(OVE->getSourceExpr());
14568     }
14569 
14570     void VisitBinaryOperator(BinaryOperator *BinOp) {
14571       if (!Variable || VarWillBeReased || BinOp->getOpcode() != BO_Assign)
14572         return;
14573       Expr *LHS = BinOp->getLHS();
14574       if (const DeclRefExpr *DRE = dyn_cast_or_null<DeclRefExpr>(LHS)) {
14575         if (DRE->getDecl() != Variable)
14576           return;
14577         if (Expr *RHS = BinOp->getRHS()) {
14578           RHS = RHS->IgnoreParenCasts();
14579           Optional<llvm::APSInt> Value;
14580           VarWillBeReased =
14581               (RHS && (Value = RHS->getIntegerConstantExpr(Context)) &&
14582                *Value == 0);
14583         }
14584       }
14585     }
14586   };
14587 
14588 } // namespace
14589 
14590 /// Check whether the given argument is a block which captures a
14591 /// variable.
14592 static Expr *findCapturingExpr(Sema &S, Expr *e, RetainCycleOwner &owner) {
14593   assert(owner.Variable && owner.Loc.isValid());
14594 
14595   e = e->IgnoreParenCasts();
14596 
14597   // Look through [^{...} copy] and Block_copy(^{...}).
14598   if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(e)) {
14599     Selector Cmd = ME->getSelector();
14600     if (Cmd.isUnarySelector() && Cmd.getNameForSlot(0) == "copy") {
14601       e = ME->getInstanceReceiver();
14602       if (!e)
14603         return nullptr;
14604       e = e->IgnoreParenCasts();
14605     }
14606   } else if (CallExpr *CE = dyn_cast<CallExpr>(e)) {
14607     if (CE->getNumArgs() == 1) {
14608       FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(CE->getCalleeDecl());
14609       if (Fn) {
14610         const IdentifierInfo *FnI = Fn->getIdentifier();
14611         if (FnI && FnI->isStr("_Block_copy")) {
14612           e = CE->getArg(0)->IgnoreParenCasts();
14613         }
14614       }
14615     }
14616   }
14617 
14618   BlockExpr *block = dyn_cast<BlockExpr>(e);
14619   if (!block || !block->getBlockDecl()->capturesVariable(owner.Variable))
14620     return nullptr;
14621 
14622   FindCaptureVisitor visitor(S.Context, owner.Variable);
14623   visitor.Visit(block->getBlockDecl()->getBody());
14624   return visitor.VarWillBeReased ? nullptr : visitor.Capturer;
14625 }
14626 
14627 static void diagnoseRetainCycle(Sema &S, Expr *capturer,
14628                                 RetainCycleOwner &owner) {
14629   assert(capturer);
14630   assert(owner.Variable && owner.Loc.isValid());
14631 
14632   S.Diag(capturer->getExprLoc(), diag::warn_arc_retain_cycle)
14633     << owner.Variable << capturer->getSourceRange();
14634   S.Diag(owner.Loc, diag::note_arc_retain_cycle_owner)
14635     << owner.Indirect << owner.Range;
14636 }
14637 
14638 /// Check for a keyword selector that starts with the word 'add' or
14639 /// 'set'.
14640 static bool isSetterLikeSelector(Selector sel) {
14641   if (sel.isUnarySelector()) return false;
14642 
14643   StringRef str = sel.getNameForSlot(0);
14644   while (!str.empty() && str.front() == '_') str = str.substr(1);
14645   if (str.startswith("set"))
14646     str = str.substr(3);
14647   else if (str.startswith("add")) {
14648     // Specially allow 'addOperationWithBlock:'.
14649     if (sel.getNumArgs() == 1 && str.startswith("addOperationWithBlock"))
14650       return false;
14651     str = str.substr(3);
14652   }
14653   else
14654     return false;
14655 
14656   if (str.empty()) return true;
14657   return !isLowercase(str.front());
14658 }
14659 
14660 static Optional<int> GetNSMutableArrayArgumentIndex(Sema &S,
14661                                                     ObjCMessageExpr *Message) {
14662   bool IsMutableArray = S.NSAPIObj->isSubclassOfNSClass(
14663                                                 Message->getReceiverInterface(),
14664                                                 NSAPI::ClassId_NSMutableArray);
14665   if (!IsMutableArray) {
14666     return None;
14667   }
14668 
14669   Selector Sel = Message->getSelector();
14670 
14671   Optional<NSAPI::NSArrayMethodKind> MKOpt =
14672     S.NSAPIObj->getNSArrayMethodKind(Sel);
14673   if (!MKOpt) {
14674     return None;
14675   }
14676 
14677   NSAPI::NSArrayMethodKind MK = *MKOpt;
14678 
14679   switch (MK) {
14680     case NSAPI::NSMutableArr_addObject:
14681     case NSAPI::NSMutableArr_insertObjectAtIndex:
14682     case NSAPI::NSMutableArr_setObjectAtIndexedSubscript:
14683       return 0;
14684     case NSAPI::NSMutableArr_replaceObjectAtIndex:
14685       return 1;
14686 
14687     default:
14688       return None;
14689   }
14690 
14691   return None;
14692 }
14693 
14694 static
14695 Optional<int> GetNSMutableDictionaryArgumentIndex(Sema &S,
14696                                                   ObjCMessageExpr *Message) {
14697   bool IsMutableDictionary = S.NSAPIObj->isSubclassOfNSClass(
14698                                             Message->getReceiverInterface(),
14699                                             NSAPI::ClassId_NSMutableDictionary);
14700   if (!IsMutableDictionary) {
14701     return None;
14702   }
14703 
14704   Selector Sel = Message->getSelector();
14705 
14706   Optional<NSAPI::NSDictionaryMethodKind> MKOpt =
14707     S.NSAPIObj->getNSDictionaryMethodKind(Sel);
14708   if (!MKOpt) {
14709     return None;
14710   }
14711 
14712   NSAPI::NSDictionaryMethodKind MK = *MKOpt;
14713 
14714   switch (MK) {
14715     case NSAPI::NSMutableDict_setObjectForKey:
14716     case NSAPI::NSMutableDict_setValueForKey:
14717     case NSAPI::NSMutableDict_setObjectForKeyedSubscript:
14718       return 0;
14719 
14720     default:
14721       return None;
14722   }
14723 
14724   return None;
14725 }
14726 
14727 static Optional<int> GetNSSetArgumentIndex(Sema &S, ObjCMessageExpr *Message) {
14728   bool IsMutableSet = S.NSAPIObj->isSubclassOfNSClass(
14729                                                 Message->getReceiverInterface(),
14730                                                 NSAPI::ClassId_NSMutableSet);
14731 
14732   bool IsMutableOrderedSet = S.NSAPIObj->isSubclassOfNSClass(
14733                                             Message->getReceiverInterface(),
14734                                             NSAPI::ClassId_NSMutableOrderedSet);
14735   if (!IsMutableSet && !IsMutableOrderedSet) {
14736     return None;
14737   }
14738 
14739   Selector Sel = Message->getSelector();
14740 
14741   Optional<NSAPI::NSSetMethodKind> MKOpt = S.NSAPIObj->getNSSetMethodKind(Sel);
14742   if (!MKOpt) {
14743     return None;
14744   }
14745 
14746   NSAPI::NSSetMethodKind MK = *MKOpt;
14747 
14748   switch (MK) {
14749     case NSAPI::NSMutableSet_addObject:
14750     case NSAPI::NSOrderedSet_setObjectAtIndex:
14751     case NSAPI::NSOrderedSet_setObjectAtIndexedSubscript:
14752     case NSAPI::NSOrderedSet_insertObjectAtIndex:
14753       return 0;
14754     case NSAPI::NSOrderedSet_replaceObjectAtIndexWithObject:
14755       return 1;
14756   }
14757 
14758   return None;
14759 }
14760 
14761 void Sema::CheckObjCCircularContainer(ObjCMessageExpr *Message) {
14762   if (!Message->isInstanceMessage()) {
14763     return;
14764   }
14765 
14766   Optional<int> ArgOpt;
14767 
14768   if (!(ArgOpt = GetNSMutableArrayArgumentIndex(*this, Message)) &&
14769       !(ArgOpt = GetNSMutableDictionaryArgumentIndex(*this, Message)) &&
14770       !(ArgOpt = GetNSSetArgumentIndex(*this, Message))) {
14771     return;
14772   }
14773 
14774   int ArgIndex = *ArgOpt;
14775 
14776   Expr *Arg = Message->getArg(ArgIndex)->IgnoreImpCasts();
14777   if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Arg)) {
14778     Arg = OE->getSourceExpr()->IgnoreImpCasts();
14779   }
14780 
14781   if (Message->getReceiverKind() == ObjCMessageExpr::SuperInstance) {
14782     if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14783       if (ArgRE->isObjCSelfExpr()) {
14784         Diag(Message->getSourceRange().getBegin(),
14785              diag::warn_objc_circular_container)
14786           << ArgRE->getDecl() << StringRef("'super'");
14787       }
14788     }
14789   } else {
14790     Expr *Receiver = Message->getInstanceReceiver()->IgnoreImpCasts();
14791 
14792     if (OpaqueValueExpr *OE = dyn_cast<OpaqueValueExpr>(Receiver)) {
14793       Receiver = OE->getSourceExpr()->IgnoreImpCasts();
14794     }
14795 
14796     if (DeclRefExpr *ReceiverRE = dyn_cast<DeclRefExpr>(Receiver)) {
14797       if (DeclRefExpr *ArgRE = dyn_cast<DeclRefExpr>(Arg)) {
14798         if (ReceiverRE->getDecl() == ArgRE->getDecl()) {
14799           ValueDecl *Decl = ReceiverRE->getDecl();
14800           Diag(Message->getSourceRange().getBegin(),
14801                diag::warn_objc_circular_container)
14802             << Decl << Decl;
14803           if (!ArgRE->isObjCSelfExpr()) {
14804             Diag(Decl->getLocation(),
14805                  diag::note_objc_circular_container_declared_here)
14806               << Decl;
14807           }
14808         }
14809       }
14810     } else if (ObjCIvarRefExpr *IvarRE = dyn_cast<ObjCIvarRefExpr>(Receiver)) {
14811       if (ObjCIvarRefExpr *IvarArgRE = dyn_cast<ObjCIvarRefExpr>(Arg)) {
14812         if (IvarRE->getDecl() == IvarArgRE->getDecl()) {
14813           ObjCIvarDecl *Decl = IvarRE->getDecl();
14814           Diag(Message->getSourceRange().getBegin(),
14815                diag::warn_objc_circular_container)
14816             << Decl << Decl;
14817           Diag(Decl->getLocation(),
14818                diag::note_objc_circular_container_declared_here)
14819             << Decl;
14820         }
14821       }
14822     }
14823   }
14824 }
14825 
14826 /// Check a message send to see if it's likely to cause a retain cycle.
14827 void Sema::checkRetainCycles(ObjCMessageExpr *msg) {
14828   // Only check instance methods whose selector looks like a setter.
14829   if (!msg->isInstanceMessage() || !isSetterLikeSelector(msg->getSelector()))
14830     return;
14831 
14832   // Try to find a variable that the receiver is strongly owned by.
14833   RetainCycleOwner owner;
14834   if (msg->getReceiverKind() == ObjCMessageExpr::Instance) {
14835     if (!findRetainCycleOwner(*this, msg->getInstanceReceiver(), owner))
14836       return;
14837   } else {
14838     assert(msg->getReceiverKind() == ObjCMessageExpr::SuperInstance);
14839     owner.Variable = getCurMethodDecl()->getSelfDecl();
14840     owner.Loc = msg->getSuperLoc();
14841     owner.Range = msg->getSuperLoc();
14842   }
14843 
14844   // Check whether the receiver is captured by any of the arguments.
14845   const ObjCMethodDecl *MD = msg->getMethodDecl();
14846   for (unsigned i = 0, e = msg->getNumArgs(); i != e; ++i) {
14847     if (Expr *capturer = findCapturingExpr(*this, msg->getArg(i), owner)) {
14848       // noescape blocks should not be retained by the method.
14849       if (MD && MD->parameters()[i]->hasAttr<NoEscapeAttr>())
14850         continue;
14851       return diagnoseRetainCycle(*this, capturer, owner);
14852     }
14853   }
14854 }
14855 
14856 /// Check a property assign to see if it's likely to cause a retain cycle.
14857 void Sema::checkRetainCycles(Expr *receiver, Expr *argument) {
14858   RetainCycleOwner owner;
14859   if (!findRetainCycleOwner(*this, receiver, owner))
14860     return;
14861 
14862   if (Expr *capturer = findCapturingExpr(*this, argument, owner))
14863     diagnoseRetainCycle(*this, capturer, owner);
14864 }
14865 
14866 void Sema::checkRetainCycles(VarDecl *Var, Expr *Init) {
14867   RetainCycleOwner Owner;
14868   if (!considerVariable(Var, /*DeclRefExpr=*/nullptr, Owner))
14869     return;
14870 
14871   // Because we don't have an expression for the variable, we have to set the
14872   // location explicitly here.
14873   Owner.Loc = Var->getLocation();
14874   Owner.Range = Var->getSourceRange();
14875 
14876   if (Expr *Capturer = findCapturingExpr(*this, Init, Owner))
14877     diagnoseRetainCycle(*this, Capturer, Owner);
14878 }
14879 
14880 static bool checkUnsafeAssignLiteral(Sema &S, SourceLocation Loc,
14881                                      Expr *RHS, bool isProperty) {
14882   // Check if RHS is an Objective-C object literal, which also can get
14883   // immediately zapped in a weak reference.  Note that we explicitly
14884   // allow ObjCStringLiterals, since those are designed to never really die.
14885   RHS = RHS->IgnoreParenImpCasts();
14886 
14887   // This enum needs to match with the 'select' in
14888   // warn_objc_arc_literal_assign (off-by-1).
14889   Sema::ObjCLiteralKind Kind = S.CheckLiteralKind(RHS);
14890   if (Kind == Sema::LK_String || Kind == Sema::LK_None)
14891     return false;
14892 
14893   S.Diag(Loc, diag::warn_arc_literal_assign)
14894     << (unsigned) Kind
14895     << (isProperty ? 0 : 1)
14896     << RHS->getSourceRange();
14897 
14898   return true;
14899 }
14900 
14901 static bool checkUnsafeAssignObject(Sema &S, SourceLocation Loc,
14902                                     Qualifiers::ObjCLifetime LT,
14903                                     Expr *RHS, bool isProperty) {
14904   // Strip off any implicit cast added to get to the one ARC-specific.
14905   while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14906     if (cast->getCastKind() == CK_ARCConsumeObject) {
14907       S.Diag(Loc, diag::warn_arc_retained_assign)
14908         << (LT == Qualifiers::OCL_ExplicitNone)
14909         << (isProperty ? 0 : 1)
14910         << RHS->getSourceRange();
14911       return true;
14912     }
14913     RHS = cast->getSubExpr();
14914   }
14915 
14916   if (LT == Qualifiers::OCL_Weak &&
14917       checkUnsafeAssignLiteral(S, Loc, RHS, isProperty))
14918     return true;
14919 
14920   return false;
14921 }
14922 
14923 bool Sema::checkUnsafeAssigns(SourceLocation Loc,
14924                               QualType LHS, Expr *RHS) {
14925   Qualifiers::ObjCLifetime LT = LHS.getObjCLifetime();
14926 
14927   if (LT != Qualifiers::OCL_Weak && LT != Qualifiers::OCL_ExplicitNone)
14928     return false;
14929 
14930   if (checkUnsafeAssignObject(*this, Loc, LT, RHS, false))
14931     return true;
14932 
14933   return false;
14934 }
14935 
14936 void Sema::checkUnsafeExprAssigns(SourceLocation Loc,
14937                               Expr *LHS, Expr *RHS) {
14938   QualType LHSType;
14939   // PropertyRef on LHS type need be directly obtained from
14940   // its declaration as it has a PseudoType.
14941   ObjCPropertyRefExpr *PRE
14942     = dyn_cast<ObjCPropertyRefExpr>(LHS->IgnoreParens());
14943   if (PRE && !PRE->isImplicitProperty()) {
14944     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14945     if (PD)
14946       LHSType = PD->getType();
14947   }
14948 
14949   if (LHSType.isNull())
14950     LHSType = LHS->getType();
14951 
14952   Qualifiers::ObjCLifetime LT = LHSType.getObjCLifetime();
14953 
14954   if (LT == Qualifiers::OCL_Weak) {
14955     if (!Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, Loc))
14956       getCurFunction()->markSafeWeakUse(LHS);
14957   }
14958 
14959   if (checkUnsafeAssigns(Loc, LHSType, RHS))
14960     return;
14961 
14962   // FIXME. Check for other life times.
14963   if (LT != Qualifiers::OCL_None)
14964     return;
14965 
14966   if (PRE) {
14967     if (PRE->isImplicitProperty())
14968       return;
14969     const ObjCPropertyDecl *PD = PRE->getExplicitProperty();
14970     if (!PD)
14971       return;
14972 
14973     unsigned Attributes = PD->getPropertyAttributes();
14974     if (Attributes & ObjCPropertyAttribute::kind_assign) {
14975       // when 'assign' attribute was not explicitly specified
14976       // by user, ignore it and rely on property type itself
14977       // for lifetime info.
14978       unsigned AsWrittenAttr = PD->getPropertyAttributesAsWritten();
14979       if (!(AsWrittenAttr & ObjCPropertyAttribute::kind_assign) &&
14980           LHSType->isObjCRetainableType())
14981         return;
14982 
14983       while (ImplicitCastExpr *cast = dyn_cast<ImplicitCastExpr>(RHS)) {
14984         if (cast->getCastKind() == CK_ARCConsumeObject) {
14985           Diag(Loc, diag::warn_arc_retained_property_assign)
14986           << RHS->getSourceRange();
14987           return;
14988         }
14989         RHS = cast->getSubExpr();
14990       }
14991     } else if (Attributes & ObjCPropertyAttribute::kind_weak) {
14992       if (checkUnsafeAssignObject(*this, Loc, Qualifiers::OCL_Weak, RHS, true))
14993         return;
14994     }
14995   }
14996 }
14997 
14998 //===--- CHECK: Empty statement body (-Wempty-body) ---------------------===//
14999 
15000 static bool ShouldDiagnoseEmptyStmtBody(const SourceManager &SourceMgr,
15001                                         SourceLocation StmtLoc,
15002                                         const NullStmt *Body) {
15003   // Do not warn if the body is a macro that expands to nothing, e.g:
15004   //
15005   // #define CALL(x)
15006   // if (condition)
15007   //   CALL(0);
15008   if (Body->hasLeadingEmptyMacro())
15009     return false;
15010 
15011   // Get line numbers of statement and body.
15012   bool StmtLineInvalid;
15013   unsigned StmtLine = SourceMgr.getPresumedLineNumber(StmtLoc,
15014                                                       &StmtLineInvalid);
15015   if (StmtLineInvalid)
15016     return false;
15017 
15018   bool BodyLineInvalid;
15019   unsigned BodyLine = SourceMgr.getSpellingLineNumber(Body->getSemiLoc(),
15020                                                       &BodyLineInvalid);
15021   if (BodyLineInvalid)
15022     return false;
15023 
15024   // Warn if null statement and body are on the same line.
15025   if (StmtLine != BodyLine)
15026     return false;
15027 
15028   return true;
15029 }
15030 
15031 void Sema::DiagnoseEmptyStmtBody(SourceLocation StmtLoc,
15032                                  const Stmt *Body,
15033                                  unsigned DiagID) {
15034   // Since this is a syntactic check, don't emit diagnostic for template
15035   // instantiations, this just adds noise.
15036   if (CurrentInstantiationScope)
15037     return;
15038 
15039   // The body should be a null statement.
15040   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15041   if (!NBody)
15042     return;
15043 
15044   // Do the usual checks.
15045   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15046     return;
15047 
15048   Diag(NBody->getSemiLoc(), DiagID);
15049   Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15050 }
15051 
15052 void Sema::DiagnoseEmptyLoopBody(const Stmt *S,
15053                                  const Stmt *PossibleBody) {
15054   assert(!CurrentInstantiationScope); // Ensured by caller
15055 
15056   SourceLocation StmtLoc;
15057   const Stmt *Body;
15058   unsigned DiagID;
15059   if (const ForStmt *FS = dyn_cast<ForStmt>(S)) {
15060     StmtLoc = FS->getRParenLoc();
15061     Body = FS->getBody();
15062     DiagID = diag::warn_empty_for_body;
15063   } else if (const WhileStmt *WS = dyn_cast<WhileStmt>(S)) {
15064     StmtLoc = WS->getCond()->getSourceRange().getEnd();
15065     Body = WS->getBody();
15066     DiagID = diag::warn_empty_while_body;
15067   } else
15068     return; // Neither `for' nor `while'.
15069 
15070   // The body should be a null statement.
15071   const NullStmt *NBody = dyn_cast<NullStmt>(Body);
15072   if (!NBody)
15073     return;
15074 
15075   // Skip expensive checks if diagnostic is disabled.
15076   if (Diags.isIgnored(DiagID, NBody->getSemiLoc()))
15077     return;
15078 
15079   // Do the usual checks.
15080   if (!ShouldDiagnoseEmptyStmtBody(SourceMgr, StmtLoc, NBody))
15081     return;
15082 
15083   // `for(...);' and `while(...);' are popular idioms, so in order to keep
15084   // noise level low, emit diagnostics only if for/while is followed by a
15085   // CompoundStmt, e.g.:
15086   //    for (int i = 0; i < n; i++);
15087   //    {
15088   //      a(i);
15089   //    }
15090   // or if for/while is followed by a statement with more indentation
15091   // than for/while itself:
15092   //    for (int i = 0; i < n; i++);
15093   //      a(i);
15094   bool ProbableTypo = isa<CompoundStmt>(PossibleBody);
15095   if (!ProbableTypo) {
15096     bool BodyColInvalid;
15097     unsigned BodyCol = SourceMgr.getPresumedColumnNumber(
15098         PossibleBody->getBeginLoc(), &BodyColInvalid);
15099     if (BodyColInvalid)
15100       return;
15101 
15102     bool StmtColInvalid;
15103     unsigned StmtCol =
15104         SourceMgr.getPresumedColumnNumber(S->getBeginLoc(), &StmtColInvalid);
15105     if (StmtColInvalid)
15106       return;
15107 
15108     if (BodyCol > StmtCol)
15109       ProbableTypo = true;
15110   }
15111 
15112   if (ProbableTypo) {
15113     Diag(NBody->getSemiLoc(), DiagID);
15114     Diag(NBody->getSemiLoc(), diag::note_empty_body_on_separate_line);
15115   }
15116 }
15117 
15118 //===--- CHECK: Warn on self move with std::move. -------------------------===//
15119 
15120 /// DiagnoseSelfMove - Emits a warning if a value is moved to itself.
15121 void Sema::DiagnoseSelfMove(const Expr *LHSExpr, const Expr *RHSExpr,
15122                              SourceLocation OpLoc) {
15123   if (Diags.isIgnored(diag::warn_sizeof_pointer_expr_memaccess, OpLoc))
15124     return;
15125 
15126   if (inTemplateInstantiation())
15127     return;
15128 
15129   // Strip parens and casts away.
15130   LHSExpr = LHSExpr->IgnoreParenImpCasts();
15131   RHSExpr = RHSExpr->IgnoreParenImpCasts();
15132 
15133   // Check for a call expression
15134   const CallExpr *CE = dyn_cast<CallExpr>(RHSExpr);
15135   if (!CE || CE->getNumArgs() != 1)
15136     return;
15137 
15138   // Check for a call to std::move
15139   if (!CE->isCallToStdMove())
15140     return;
15141 
15142   // Get argument from std::move
15143   RHSExpr = CE->getArg(0);
15144 
15145   const DeclRefExpr *LHSDeclRef = dyn_cast<DeclRefExpr>(LHSExpr);
15146   const DeclRefExpr *RHSDeclRef = dyn_cast<DeclRefExpr>(RHSExpr);
15147 
15148   // Two DeclRefExpr's, check that the decls are the same.
15149   if (LHSDeclRef && RHSDeclRef) {
15150     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15151       return;
15152     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15153         RHSDeclRef->getDecl()->getCanonicalDecl())
15154       return;
15155 
15156     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15157                                         << LHSExpr->getSourceRange()
15158                                         << RHSExpr->getSourceRange();
15159     return;
15160   }
15161 
15162   // Member variables require a different approach to check for self moves.
15163   // MemberExpr's are the same if every nested MemberExpr refers to the same
15164   // Decl and that the base Expr's are DeclRefExpr's with the same Decl or
15165   // the base Expr's are CXXThisExpr's.
15166   const Expr *LHSBase = LHSExpr;
15167   const Expr *RHSBase = RHSExpr;
15168   const MemberExpr *LHSME = dyn_cast<MemberExpr>(LHSExpr);
15169   const MemberExpr *RHSME = dyn_cast<MemberExpr>(RHSExpr);
15170   if (!LHSME || !RHSME)
15171     return;
15172 
15173   while (LHSME && RHSME) {
15174     if (LHSME->getMemberDecl()->getCanonicalDecl() !=
15175         RHSME->getMemberDecl()->getCanonicalDecl())
15176       return;
15177 
15178     LHSBase = LHSME->getBase();
15179     RHSBase = RHSME->getBase();
15180     LHSME = dyn_cast<MemberExpr>(LHSBase);
15181     RHSME = dyn_cast<MemberExpr>(RHSBase);
15182   }
15183 
15184   LHSDeclRef = dyn_cast<DeclRefExpr>(LHSBase);
15185   RHSDeclRef = dyn_cast<DeclRefExpr>(RHSBase);
15186   if (LHSDeclRef && RHSDeclRef) {
15187     if (!LHSDeclRef->getDecl() || !RHSDeclRef->getDecl())
15188       return;
15189     if (LHSDeclRef->getDecl()->getCanonicalDecl() !=
15190         RHSDeclRef->getDecl()->getCanonicalDecl())
15191       return;
15192 
15193     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15194                                         << LHSExpr->getSourceRange()
15195                                         << RHSExpr->getSourceRange();
15196     return;
15197   }
15198 
15199   if (isa<CXXThisExpr>(LHSBase) && isa<CXXThisExpr>(RHSBase))
15200     Diag(OpLoc, diag::warn_self_move) << LHSExpr->getType()
15201                                         << LHSExpr->getSourceRange()
15202                                         << RHSExpr->getSourceRange();
15203 }
15204 
15205 //===--- Layout compatibility ----------------------------------------------//
15206 
15207 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2);
15208 
15209 /// Check if two enumeration types are layout-compatible.
15210 static bool isLayoutCompatible(ASTContext &C, EnumDecl *ED1, EnumDecl *ED2) {
15211   // C++11 [dcl.enum] p8:
15212   // Two enumeration types are layout-compatible if they have the same
15213   // underlying type.
15214   return ED1->isComplete() && ED2->isComplete() &&
15215          C.hasSameType(ED1->getIntegerType(), ED2->getIntegerType());
15216 }
15217 
15218 /// Check if two fields are layout-compatible.
15219 static bool isLayoutCompatible(ASTContext &C, FieldDecl *Field1,
15220                                FieldDecl *Field2) {
15221   if (!isLayoutCompatible(C, Field1->getType(), Field2->getType()))
15222     return false;
15223 
15224   if (Field1->isBitField() != Field2->isBitField())
15225     return false;
15226 
15227   if (Field1->isBitField()) {
15228     // Make sure that the bit-fields are the same length.
15229     unsigned Bits1 = Field1->getBitWidthValue(C);
15230     unsigned Bits2 = Field2->getBitWidthValue(C);
15231 
15232     if (Bits1 != Bits2)
15233       return false;
15234   }
15235 
15236   return true;
15237 }
15238 
15239 /// Check if two standard-layout structs are layout-compatible.
15240 /// (C++11 [class.mem] p17)
15241 static bool isLayoutCompatibleStruct(ASTContext &C, RecordDecl *RD1,
15242                                      RecordDecl *RD2) {
15243   // If both records are C++ classes, check that base classes match.
15244   if (const CXXRecordDecl *D1CXX = dyn_cast<CXXRecordDecl>(RD1)) {
15245     // If one of records is a CXXRecordDecl we are in C++ mode,
15246     // thus the other one is a CXXRecordDecl, too.
15247     const CXXRecordDecl *D2CXX = cast<CXXRecordDecl>(RD2);
15248     // Check number of base classes.
15249     if (D1CXX->getNumBases() != D2CXX->getNumBases())
15250       return false;
15251 
15252     // Check the base classes.
15253     for (CXXRecordDecl::base_class_const_iterator
15254                Base1 = D1CXX->bases_begin(),
15255            BaseEnd1 = D1CXX->bases_end(),
15256               Base2 = D2CXX->bases_begin();
15257          Base1 != BaseEnd1;
15258          ++Base1, ++Base2) {
15259       if (!isLayoutCompatible(C, Base1->getType(), Base2->getType()))
15260         return false;
15261     }
15262   } else if (const CXXRecordDecl *D2CXX = dyn_cast<CXXRecordDecl>(RD2)) {
15263     // If only RD2 is a C++ class, it should have zero base classes.
15264     if (D2CXX->getNumBases() > 0)
15265       return false;
15266   }
15267 
15268   // Check the fields.
15269   RecordDecl::field_iterator Field2 = RD2->field_begin(),
15270                              Field2End = RD2->field_end(),
15271                              Field1 = RD1->field_begin(),
15272                              Field1End = RD1->field_end();
15273   for ( ; Field1 != Field1End && Field2 != Field2End; ++Field1, ++Field2) {
15274     if (!isLayoutCompatible(C, *Field1, *Field2))
15275       return false;
15276   }
15277   if (Field1 != Field1End || Field2 != Field2End)
15278     return false;
15279 
15280   return true;
15281 }
15282 
15283 /// Check if two standard-layout unions are layout-compatible.
15284 /// (C++11 [class.mem] p18)
15285 static bool isLayoutCompatibleUnion(ASTContext &C, RecordDecl *RD1,
15286                                     RecordDecl *RD2) {
15287   llvm::SmallPtrSet<FieldDecl *, 8> UnmatchedFields;
15288   for (auto *Field2 : RD2->fields())
15289     UnmatchedFields.insert(Field2);
15290 
15291   for (auto *Field1 : RD1->fields()) {
15292     llvm::SmallPtrSet<FieldDecl *, 8>::iterator
15293         I = UnmatchedFields.begin(),
15294         E = UnmatchedFields.end();
15295 
15296     for ( ; I != E; ++I) {
15297       if (isLayoutCompatible(C, Field1, *I)) {
15298         bool Result = UnmatchedFields.erase(*I);
15299         (void) Result;
15300         assert(Result);
15301         break;
15302       }
15303     }
15304     if (I == E)
15305       return false;
15306   }
15307 
15308   return UnmatchedFields.empty();
15309 }
15310 
15311 static bool isLayoutCompatible(ASTContext &C, RecordDecl *RD1,
15312                                RecordDecl *RD2) {
15313   if (RD1->isUnion() != RD2->isUnion())
15314     return false;
15315 
15316   if (RD1->isUnion())
15317     return isLayoutCompatibleUnion(C, RD1, RD2);
15318   else
15319     return isLayoutCompatibleStruct(C, RD1, RD2);
15320 }
15321 
15322 /// Check if two types are layout-compatible in C++11 sense.
15323 static bool isLayoutCompatible(ASTContext &C, QualType T1, QualType T2) {
15324   if (T1.isNull() || T2.isNull())
15325     return false;
15326 
15327   // C++11 [basic.types] p11:
15328   // If two types T1 and T2 are the same type, then T1 and T2 are
15329   // layout-compatible types.
15330   if (C.hasSameType(T1, T2))
15331     return true;
15332 
15333   T1 = T1.getCanonicalType().getUnqualifiedType();
15334   T2 = T2.getCanonicalType().getUnqualifiedType();
15335 
15336   const Type::TypeClass TC1 = T1->getTypeClass();
15337   const Type::TypeClass TC2 = T2->getTypeClass();
15338 
15339   if (TC1 != TC2)
15340     return false;
15341 
15342   if (TC1 == Type::Enum) {
15343     return isLayoutCompatible(C,
15344                               cast<EnumType>(T1)->getDecl(),
15345                               cast<EnumType>(T2)->getDecl());
15346   } else if (TC1 == Type::Record) {
15347     if (!T1->isStandardLayoutType() || !T2->isStandardLayoutType())
15348       return false;
15349 
15350     return isLayoutCompatible(C,
15351                               cast<RecordType>(T1)->getDecl(),
15352                               cast<RecordType>(T2)->getDecl());
15353   }
15354 
15355   return false;
15356 }
15357 
15358 //===--- CHECK: pointer_with_type_tag attribute: datatypes should match ----//
15359 
15360 /// Given a type tag expression find the type tag itself.
15361 ///
15362 /// \param TypeExpr Type tag expression, as it appears in user's code.
15363 ///
15364 /// \param VD Declaration of an identifier that appears in a type tag.
15365 ///
15366 /// \param MagicValue Type tag magic value.
15367 ///
15368 /// \param isConstantEvaluated wether the evalaution should be performed in
15369 
15370 /// constant context.
15371 static bool FindTypeTagExpr(const Expr *TypeExpr, const ASTContext &Ctx,
15372                             const ValueDecl **VD, uint64_t *MagicValue,
15373                             bool isConstantEvaluated) {
15374   while(true) {
15375     if (!TypeExpr)
15376       return false;
15377 
15378     TypeExpr = TypeExpr->IgnoreParenImpCasts()->IgnoreParenCasts();
15379 
15380     switch (TypeExpr->getStmtClass()) {
15381     case Stmt::UnaryOperatorClass: {
15382       const UnaryOperator *UO = cast<UnaryOperator>(TypeExpr);
15383       if (UO->getOpcode() == UO_AddrOf || UO->getOpcode() == UO_Deref) {
15384         TypeExpr = UO->getSubExpr();
15385         continue;
15386       }
15387       return false;
15388     }
15389 
15390     case Stmt::DeclRefExprClass: {
15391       const DeclRefExpr *DRE = cast<DeclRefExpr>(TypeExpr);
15392       *VD = DRE->getDecl();
15393       return true;
15394     }
15395 
15396     case Stmt::IntegerLiteralClass: {
15397       const IntegerLiteral *IL = cast<IntegerLiteral>(TypeExpr);
15398       llvm::APInt MagicValueAPInt = IL->getValue();
15399       if (MagicValueAPInt.getActiveBits() <= 64) {
15400         *MagicValue = MagicValueAPInt.getZExtValue();
15401         return true;
15402       } else
15403         return false;
15404     }
15405 
15406     case Stmt::BinaryConditionalOperatorClass:
15407     case Stmt::ConditionalOperatorClass: {
15408       const AbstractConditionalOperator *ACO =
15409           cast<AbstractConditionalOperator>(TypeExpr);
15410       bool Result;
15411       if (ACO->getCond()->EvaluateAsBooleanCondition(Result, Ctx,
15412                                                      isConstantEvaluated)) {
15413         if (Result)
15414           TypeExpr = ACO->getTrueExpr();
15415         else
15416           TypeExpr = ACO->getFalseExpr();
15417         continue;
15418       }
15419       return false;
15420     }
15421 
15422     case Stmt::BinaryOperatorClass: {
15423       const BinaryOperator *BO = cast<BinaryOperator>(TypeExpr);
15424       if (BO->getOpcode() == BO_Comma) {
15425         TypeExpr = BO->getRHS();
15426         continue;
15427       }
15428       return false;
15429     }
15430 
15431     default:
15432       return false;
15433     }
15434   }
15435 }
15436 
15437 /// Retrieve the C type corresponding to type tag TypeExpr.
15438 ///
15439 /// \param TypeExpr Expression that specifies a type tag.
15440 ///
15441 /// \param MagicValues Registered magic values.
15442 ///
15443 /// \param FoundWrongKind Set to true if a type tag was found, but of a wrong
15444 ///        kind.
15445 ///
15446 /// \param TypeInfo Information about the corresponding C type.
15447 ///
15448 /// \param isConstantEvaluated wether the evalaution should be performed in
15449 /// constant context.
15450 ///
15451 /// \returns true if the corresponding C type was found.
15452 static bool GetMatchingCType(
15453     const IdentifierInfo *ArgumentKind, const Expr *TypeExpr,
15454     const ASTContext &Ctx,
15455     const llvm::DenseMap<Sema::TypeTagMagicValue, Sema::TypeTagData>
15456         *MagicValues,
15457     bool &FoundWrongKind, Sema::TypeTagData &TypeInfo,
15458     bool isConstantEvaluated) {
15459   FoundWrongKind = false;
15460 
15461   // Variable declaration that has type_tag_for_datatype attribute.
15462   const ValueDecl *VD = nullptr;
15463 
15464   uint64_t MagicValue;
15465 
15466   if (!FindTypeTagExpr(TypeExpr, Ctx, &VD, &MagicValue, isConstantEvaluated))
15467     return false;
15468 
15469   if (VD) {
15470     if (TypeTagForDatatypeAttr *I = VD->getAttr<TypeTagForDatatypeAttr>()) {
15471       if (I->getArgumentKind() != ArgumentKind) {
15472         FoundWrongKind = true;
15473         return false;
15474       }
15475       TypeInfo.Type = I->getMatchingCType();
15476       TypeInfo.LayoutCompatible = I->getLayoutCompatible();
15477       TypeInfo.MustBeNull = I->getMustBeNull();
15478       return true;
15479     }
15480     return false;
15481   }
15482 
15483   if (!MagicValues)
15484     return false;
15485 
15486   llvm::DenseMap<Sema::TypeTagMagicValue,
15487                  Sema::TypeTagData>::const_iterator I =
15488       MagicValues->find(std::make_pair(ArgumentKind, MagicValue));
15489   if (I == MagicValues->end())
15490     return false;
15491 
15492   TypeInfo = I->second;
15493   return true;
15494 }
15495 
15496 void Sema::RegisterTypeTagForDatatype(const IdentifierInfo *ArgumentKind,
15497                                       uint64_t MagicValue, QualType Type,
15498                                       bool LayoutCompatible,
15499                                       bool MustBeNull) {
15500   if (!TypeTagForDatatypeMagicValues)
15501     TypeTagForDatatypeMagicValues.reset(
15502         new llvm::DenseMap<TypeTagMagicValue, TypeTagData>);
15503 
15504   TypeTagMagicValue Magic(ArgumentKind, MagicValue);
15505   (*TypeTagForDatatypeMagicValues)[Magic] =
15506       TypeTagData(Type, LayoutCompatible, MustBeNull);
15507 }
15508 
15509 static bool IsSameCharType(QualType T1, QualType T2) {
15510   const BuiltinType *BT1 = T1->getAs<BuiltinType>();
15511   if (!BT1)
15512     return false;
15513 
15514   const BuiltinType *BT2 = T2->getAs<BuiltinType>();
15515   if (!BT2)
15516     return false;
15517 
15518   BuiltinType::Kind T1Kind = BT1->getKind();
15519   BuiltinType::Kind T2Kind = BT2->getKind();
15520 
15521   return (T1Kind == BuiltinType::SChar  && T2Kind == BuiltinType::Char_S) ||
15522          (T1Kind == BuiltinType::UChar  && T2Kind == BuiltinType::Char_U) ||
15523          (T1Kind == BuiltinType::Char_U && T2Kind == BuiltinType::UChar) ||
15524          (T1Kind == BuiltinType::Char_S && T2Kind == BuiltinType::SChar);
15525 }
15526 
15527 void Sema::CheckArgumentWithTypeTag(const ArgumentWithTypeTagAttr *Attr,
15528                                     const ArrayRef<const Expr *> ExprArgs,
15529                                     SourceLocation CallSiteLoc) {
15530   const IdentifierInfo *ArgumentKind = Attr->getArgumentKind();
15531   bool IsPointerAttr = Attr->getIsPointer();
15532 
15533   // Retrieve the argument representing the 'type_tag'.
15534   unsigned TypeTagIdxAST = Attr->getTypeTagIdx().getASTIndex();
15535   if (TypeTagIdxAST >= ExprArgs.size()) {
15536     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15537         << 0 << Attr->getTypeTagIdx().getSourceIndex();
15538     return;
15539   }
15540   const Expr *TypeTagExpr = ExprArgs[TypeTagIdxAST];
15541   bool FoundWrongKind;
15542   TypeTagData TypeInfo;
15543   if (!GetMatchingCType(ArgumentKind, TypeTagExpr, Context,
15544                         TypeTagForDatatypeMagicValues.get(), FoundWrongKind,
15545                         TypeInfo, isConstantEvaluated())) {
15546     if (FoundWrongKind)
15547       Diag(TypeTagExpr->getExprLoc(),
15548            diag::warn_type_tag_for_datatype_wrong_kind)
15549         << TypeTagExpr->getSourceRange();
15550     return;
15551   }
15552 
15553   // Retrieve the argument representing the 'arg_idx'.
15554   unsigned ArgumentIdxAST = Attr->getArgumentIdx().getASTIndex();
15555   if (ArgumentIdxAST >= ExprArgs.size()) {
15556     Diag(CallSiteLoc, diag::err_tag_index_out_of_range)
15557         << 1 << Attr->getArgumentIdx().getSourceIndex();
15558     return;
15559   }
15560   const Expr *ArgumentExpr = ExprArgs[ArgumentIdxAST];
15561   if (IsPointerAttr) {
15562     // Skip implicit cast of pointer to `void *' (as a function argument).
15563     if (const ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgumentExpr))
15564       if (ICE->getType()->isVoidPointerType() &&
15565           ICE->getCastKind() == CK_BitCast)
15566         ArgumentExpr = ICE->getSubExpr();
15567   }
15568   QualType ArgumentType = ArgumentExpr->getType();
15569 
15570   // Passing a `void*' pointer shouldn't trigger a warning.
15571   if (IsPointerAttr && ArgumentType->isVoidPointerType())
15572     return;
15573 
15574   if (TypeInfo.MustBeNull) {
15575     // Type tag with matching void type requires a null pointer.
15576     if (!ArgumentExpr->isNullPointerConstant(Context,
15577                                              Expr::NPC_ValueDependentIsNotNull)) {
15578       Diag(ArgumentExpr->getExprLoc(),
15579            diag::warn_type_safety_null_pointer_required)
15580           << ArgumentKind->getName()
15581           << ArgumentExpr->getSourceRange()
15582           << TypeTagExpr->getSourceRange();
15583     }
15584     return;
15585   }
15586 
15587   QualType RequiredType = TypeInfo.Type;
15588   if (IsPointerAttr)
15589     RequiredType = Context.getPointerType(RequiredType);
15590 
15591   bool mismatch = false;
15592   if (!TypeInfo.LayoutCompatible) {
15593     mismatch = !Context.hasSameType(ArgumentType, RequiredType);
15594 
15595     // C++11 [basic.fundamental] p1:
15596     // Plain char, signed char, and unsigned char are three distinct types.
15597     //
15598     // But we treat plain `char' as equivalent to `signed char' or `unsigned
15599     // char' depending on the current char signedness mode.
15600     if (mismatch)
15601       if ((IsPointerAttr && IsSameCharType(ArgumentType->getPointeeType(),
15602                                            RequiredType->getPointeeType())) ||
15603           (!IsPointerAttr && IsSameCharType(ArgumentType, RequiredType)))
15604         mismatch = false;
15605   } else
15606     if (IsPointerAttr)
15607       mismatch = !isLayoutCompatible(Context,
15608                                      ArgumentType->getPointeeType(),
15609                                      RequiredType->getPointeeType());
15610     else
15611       mismatch = !isLayoutCompatible(Context, ArgumentType, RequiredType);
15612 
15613   if (mismatch)
15614     Diag(ArgumentExpr->getExprLoc(), diag::warn_type_safety_type_mismatch)
15615         << ArgumentType << ArgumentKind
15616         << TypeInfo.LayoutCompatible << RequiredType
15617         << ArgumentExpr->getSourceRange()
15618         << TypeTagExpr->getSourceRange();
15619 }
15620 
15621 void Sema::AddPotentialMisalignedMembers(Expr *E, RecordDecl *RD, ValueDecl *MD,
15622                                          CharUnits Alignment) {
15623   MisalignedMembers.emplace_back(E, RD, MD, Alignment);
15624 }
15625 
15626 void Sema::DiagnoseMisalignedMembers() {
15627   for (MisalignedMember &m : MisalignedMembers) {
15628     const NamedDecl *ND = m.RD;
15629     if (ND->getName().empty()) {
15630       if (const TypedefNameDecl *TD = m.RD->getTypedefNameForAnonDecl())
15631         ND = TD;
15632     }
15633     Diag(m.E->getBeginLoc(), diag::warn_taking_address_of_packed_member)
15634         << m.MD << ND << m.E->getSourceRange();
15635   }
15636   MisalignedMembers.clear();
15637 }
15638 
15639 void Sema::DiscardMisalignedMemberAddress(const Type *T, Expr *E) {
15640   E = E->IgnoreParens();
15641   if (!T->isPointerType() && !T->isIntegerType())
15642     return;
15643   if (isa<UnaryOperator>(E) &&
15644       cast<UnaryOperator>(E)->getOpcode() == UO_AddrOf) {
15645     auto *Op = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
15646     if (isa<MemberExpr>(Op)) {
15647       auto MA = llvm::find(MisalignedMembers, MisalignedMember(Op));
15648       if (MA != MisalignedMembers.end() &&
15649           (T->isIntegerType() ||
15650            (T->isPointerType() && (T->getPointeeType()->isIncompleteType() ||
15651                                    Context.getTypeAlignInChars(
15652                                        T->getPointeeType()) <= MA->Alignment))))
15653         MisalignedMembers.erase(MA);
15654     }
15655   }
15656 }
15657 
15658 void Sema::RefersToMemberWithReducedAlignment(
15659     Expr *E,
15660     llvm::function_ref<void(Expr *, RecordDecl *, FieldDecl *, CharUnits)>
15661         Action) {
15662   const auto *ME = dyn_cast<MemberExpr>(E);
15663   if (!ME)
15664     return;
15665 
15666   // No need to check expressions with an __unaligned-qualified type.
15667   if (E->getType().getQualifiers().hasUnaligned())
15668     return;
15669 
15670   // For a chain of MemberExpr like "a.b.c.d" this list
15671   // will keep FieldDecl's like [d, c, b].
15672   SmallVector<FieldDecl *, 4> ReverseMemberChain;
15673   const MemberExpr *TopME = nullptr;
15674   bool AnyIsPacked = false;
15675   do {
15676     QualType BaseType = ME->getBase()->getType();
15677     if (BaseType->isDependentType())
15678       return;
15679     if (ME->isArrow())
15680       BaseType = BaseType->getPointeeType();
15681     RecordDecl *RD = BaseType->castAs<RecordType>()->getDecl();
15682     if (RD->isInvalidDecl())
15683       return;
15684 
15685     ValueDecl *MD = ME->getMemberDecl();
15686     auto *FD = dyn_cast<FieldDecl>(MD);
15687     // We do not care about non-data members.
15688     if (!FD || FD->isInvalidDecl())
15689       return;
15690 
15691     AnyIsPacked =
15692         AnyIsPacked || (RD->hasAttr<PackedAttr>() || MD->hasAttr<PackedAttr>());
15693     ReverseMemberChain.push_back(FD);
15694 
15695     TopME = ME;
15696     ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParens());
15697   } while (ME);
15698   assert(TopME && "We did not compute a topmost MemberExpr!");
15699 
15700   // Not the scope of this diagnostic.
15701   if (!AnyIsPacked)
15702     return;
15703 
15704   const Expr *TopBase = TopME->getBase()->IgnoreParenImpCasts();
15705   const auto *DRE = dyn_cast<DeclRefExpr>(TopBase);
15706   // TODO: The innermost base of the member expression may be too complicated.
15707   // For now, just disregard these cases. This is left for future
15708   // improvement.
15709   if (!DRE && !isa<CXXThisExpr>(TopBase))
15710       return;
15711 
15712   // Alignment expected by the whole expression.
15713   CharUnits ExpectedAlignment = Context.getTypeAlignInChars(E->getType());
15714 
15715   // No need to do anything else with this case.
15716   if (ExpectedAlignment.isOne())
15717     return;
15718 
15719   // Synthesize offset of the whole access.
15720   CharUnits Offset;
15721   for (auto I = ReverseMemberChain.rbegin(); I != ReverseMemberChain.rend();
15722        I++) {
15723     Offset += Context.toCharUnitsFromBits(Context.getFieldOffset(*I));
15724   }
15725 
15726   // Compute the CompleteObjectAlignment as the alignment of the whole chain.
15727   CharUnits CompleteObjectAlignment = Context.getTypeAlignInChars(
15728       ReverseMemberChain.back()->getParent()->getTypeForDecl());
15729 
15730   // The base expression of the innermost MemberExpr may give
15731   // stronger guarantees than the class containing the member.
15732   if (DRE && !TopME->isArrow()) {
15733     const ValueDecl *VD = DRE->getDecl();
15734     if (!VD->getType()->isReferenceType())
15735       CompleteObjectAlignment =
15736           std::max(CompleteObjectAlignment, Context.getDeclAlign(VD));
15737   }
15738 
15739   // Check if the synthesized offset fulfills the alignment.
15740   if (Offset % ExpectedAlignment != 0 ||
15741       // It may fulfill the offset it but the effective alignment may still be
15742       // lower than the expected expression alignment.
15743       CompleteObjectAlignment < ExpectedAlignment) {
15744     // If this happens, we want to determine a sensible culprit of this.
15745     // Intuitively, watching the chain of member expressions from right to
15746     // left, we start with the required alignment (as required by the field
15747     // type) but some packed attribute in that chain has reduced the alignment.
15748     // It may happen that another packed structure increases it again. But if
15749     // we are here such increase has not been enough. So pointing the first
15750     // FieldDecl that either is packed or else its RecordDecl is,
15751     // seems reasonable.
15752     FieldDecl *FD = nullptr;
15753     CharUnits Alignment;
15754     for (FieldDecl *FDI : ReverseMemberChain) {
15755       if (FDI->hasAttr<PackedAttr>() ||
15756           FDI->getParent()->hasAttr<PackedAttr>()) {
15757         FD = FDI;
15758         Alignment = std::min(
15759             Context.getTypeAlignInChars(FD->getType()),
15760             Context.getTypeAlignInChars(FD->getParent()->getTypeForDecl()));
15761         break;
15762       }
15763     }
15764     assert(FD && "We did not find a packed FieldDecl!");
15765     Action(E, FD->getParent(), FD, Alignment);
15766   }
15767 }
15768 
15769 void Sema::CheckAddressOfPackedMember(Expr *rhs) {
15770   using namespace std::placeholders;
15771 
15772   RefersToMemberWithReducedAlignment(
15773       rhs, std::bind(&Sema::AddPotentialMisalignedMembers, std::ref(*this), _1,
15774                      _2, _3, _4));
15775 }
15776 
15777 ExprResult Sema::SemaBuiltinMatrixTranspose(CallExpr *TheCall,
15778                                             ExprResult CallResult) {
15779   if (checkArgCount(*this, TheCall, 1))
15780     return ExprError();
15781 
15782   ExprResult MatrixArg = DefaultLvalueConversion(TheCall->getArg(0));
15783   if (MatrixArg.isInvalid())
15784     return MatrixArg;
15785   Expr *Matrix = MatrixArg.get();
15786 
15787   auto *MType = Matrix->getType()->getAs<ConstantMatrixType>();
15788   if (!MType) {
15789     Diag(Matrix->getBeginLoc(), diag::err_builtin_matrix_arg);
15790     return ExprError();
15791   }
15792 
15793   // Create returned matrix type by swapping rows and columns of the argument
15794   // matrix type.
15795   QualType ResultType = Context.getConstantMatrixType(
15796       MType->getElementType(), MType->getNumColumns(), MType->getNumRows());
15797 
15798   // Change the return type to the type of the returned matrix.
15799   TheCall->setType(ResultType);
15800 
15801   // Update call argument to use the possibly converted matrix argument.
15802   TheCall->setArg(0, Matrix);
15803   return CallResult;
15804 }
15805 
15806 // Get and verify the matrix dimensions.
15807 static llvm::Optional<unsigned>
15808 getAndVerifyMatrixDimension(Expr *Expr, StringRef Name, Sema &S) {
15809   SourceLocation ErrorPos;
15810   Optional<llvm::APSInt> Value =
15811       Expr->getIntegerConstantExpr(S.Context, &ErrorPos);
15812   if (!Value) {
15813     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_scalar_unsigned_arg)
15814         << Name;
15815     return {};
15816   }
15817   uint64_t Dim = Value->getZExtValue();
15818   if (!ConstantMatrixType::isDimensionValid(Dim)) {
15819     S.Diag(Expr->getBeginLoc(), diag::err_builtin_matrix_invalid_dimension)
15820         << Name << ConstantMatrixType::getMaxElementsPerDimension();
15821     return {};
15822   }
15823   return Dim;
15824 }
15825 
15826 ExprResult Sema::SemaBuiltinMatrixColumnMajorLoad(CallExpr *TheCall,
15827                                                   ExprResult CallResult) {
15828   if (!getLangOpts().MatrixTypes) {
15829     Diag(TheCall->getBeginLoc(), diag::err_builtin_matrix_disabled);
15830     return ExprError();
15831   }
15832 
15833   if (checkArgCount(*this, TheCall, 4))
15834     return ExprError();
15835 
15836   unsigned PtrArgIdx = 0;
15837   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15838   Expr *RowsExpr = TheCall->getArg(1);
15839   Expr *ColumnsExpr = TheCall->getArg(2);
15840   Expr *StrideExpr = TheCall->getArg(3);
15841 
15842   bool ArgError = false;
15843 
15844   // Check pointer argument.
15845   {
15846     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15847     if (PtrConv.isInvalid())
15848       return PtrConv;
15849     PtrExpr = PtrConv.get();
15850     TheCall->setArg(0, PtrExpr);
15851     if (PtrExpr->isTypeDependent()) {
15852       TheCall->setType(Context.DependentTy);
15853       return TheCall;
15854     }
15855   }
15856 
15857   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15858   QualType ElementTy;
15859   if (!PtrTy) {
15860     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15861         << PtrArgIdx + 1;
15862     ArgError = true;
15863   } else {
15864     ElementTy = PtrTy->getPointeeType().getUnqualifiedType();
15865 
15866     if (!ConstantMatrixType::isValidElementType(ElementTy)) {
15867       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15868           << PtrArgIdx + 1;
15869       ArgError = true;
15870     }
15871   }
15872 
15873   // Apply default Lvalue conversions and convert the expression to size_t.
15874   auto ApplyArgumentConversions = [this](Expr *E) {
15875     ExprResult Conv = DefaultLvalueConversion(E);
15876     if (Conv.isInvalid())
15877       return Conv;
15878 
15879     return tryConvertExprToType(Conv.get(), Context.getSizeType());
15880   };
15881 
15882   // Apply conversion to row and column expressions.
15883   ExprResult RowsConv = ApplyArgumentConversions(RowsExpr);
15884   if (!RowsConv.isInvalid()) {
15885     RowsExpr = RowsConv.get();
15886     TheCall->setArg(1, RowsExpr);
15887   } else
15888     RowsExpr = nullptr;
15889 
15890   ExprResult ColumnsConv = ApplyArgumentConversions(ColumnsExpr);
15891   if (!ColumnsConv.isInvalid()) {
15892     ColumnsExpr = ColumnsConv.get();
15893     TheCall->setArg(2, ColumnsExpr);
15894   } else
15895     ColumnsExpr = nullptr;
15896 
15897   // If any any part of the result matrix type is still pending, just use
15898   // Context.DependentTy, until all parts are resolved.
15899   if ((RowsExpr && RowsExpr->isTypeDependent()) ||
15900       (ColumnsExpr && ColumnsExpr->isTypeDependent())) {
15901     TheCall->setType(Context.DependentTy);
15902     return CallResult;
15903   }
15904 
15905   // Check row and column dimenions.
15906   llvm::Optional<unsigned> MaybeRows;
15907   if (RowsExpr)
15908     MaybeRows = getAndVerifyMatrixDimension(RowsExpr, "row", *this);
15909 
15910   llvm::Optional<unsigned> MaybeColumns;
15911   if (ColumnsExpr)
15912     MaybeColumns = getAndVerifyMatrixDimension(ColumnsExpr, "column", *this);
15913 
15914   // Check stride argument.
15915   ExprResult StrideConv = ApplyArgumentConversions(StrideExpr);
15916   if (StrideConv.isInvalid())
15917     return ExprError();
15918   StrideExpr = StrideConv.get();
15919   TheCall->setArg(3, StrideExpr);
15920 
15921   if (MaybeRows) {
15922     if (Optional<llvm::APSInt> Value =
15923             StrideExpr->getIntegerConstantExpr(Context)) {
15924       uint64_t Stride = Value->getZExtValue();
15925       if (Stride < *MaybeRows) {
15926         Diag(StrideExpr->getBeginLoc(),
15927              diag::err_builtin_matrix_stride_too_small);
15928         ArgError = true;
15929       }
15930     }
15931   }
15932 
15933   if (ArgError || !MaybeRows || !MaybeColumns)
15934     return ExprError();
15935 
15936   TheCall->setType(
15937       Context.getConstantMatrixType(ElementTy, *MaybeRows, *MaybeColumns));
15938   return CallResult;
15939 }
15940 
15941 ExprResult Sema::SemaBuiltinMatrixColumnMajorStore(CallExpr *TheCall,
15942                                                    ExprResult CallResult) {
15943   if (checkArgCount(*this, TheCall, 3))
15944     return ExprError();
15945 
15946   unsigned PtrArgIdx = 1;
15947   Expr *MatrixExpr = TheCall->getArg(0);
15948   Expr *PtrExpr = TheCall->getArg(PtrArgIdx);
15949   Expr *StrideExpr = TheCall->getArg(2);
15950 
15951   bool ArgError = false;
15952 
15953   {
15954     ExprResult MatrixConv = DefaultLvalueConversion(MatrixExpr);
15955     if (MatrixConv.isInvalid())
15956       return MatrixConv;
15957     MatrixExpr = MatrixConv.get();
15958     TheCall->setArg(0, MatrixExpr);
15959   }
15960   if (MatrixExpr->isTypeDependent()) {
15961     TheCall->setType(Context.DependentTy);
15962     return TheCall;
15963   }
15964 
15965   auto *MatrixTy = MatrixExpr->getType()->getAs<ConstantMatrixType>();
15966   if (!MatrixTy) {
15967     Diag(MatrixExpr->getBeginLoc(), diag::err_builtin_matrix_arg) << 0;
15968     ArgError = true;
15969   }
15970 
15971   {
15972     ExprResult PtrConv = DefaultFunctionArrayLvalueConversion(PtrExpr);
15973     if (PtrConv.isInvalid())
15974       return PtrConv;
15975     PtrExpr = PtrConv.get();
15976     TheCall->setArg(1, PtrExpr);
15977     if (PtrExpr->isTypeDependent()) {
15978       TheCall->setType(Context.DependentTy);
15979       return TheCall;
15980     }
15981   }
15982 
15983   // Check pointer argument.
15984   auto *PtrTy = PtrExpr->getType()->getAs<PointerType>();
15985   if (!PtrTy) {
15986     Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_pointer_arg)
15987         << PtrArgIdx + 1;
15988     ArgError = true;
15989   } else {
15990     QualType ElementTy = PtrTy->getPointeeType();
15991     if (ElementTy.isConstQualified()) {
15992       Diag(PtrExpr->getBeginLoc(), diag::err_builtin_matrix_store_to_const);
15993       ArgError = true;
15994     }
15995     ElementTy = ElementTy.getUnqualifiedType().getCanonicalType();
15996     if (MatrixTy &&
15997         !Context.hasSameType(ElementTy, MatrixTy->getElementType())) {
15998       Diag(PtrExpr->getBeginLoc(),
15999            diag::err_builtin_matrix_pointer_arg_mismatch)
16000           << ElementTy << MatrixTy->getElementType();
16001       ArgError = true;
16002     }
16003   }
16004 
16005   // Apply default Lvalue conversions and convert the stride expression to
16006   // size_t.
16007   {
16008     ExprResult StrideConv = DefaultLvalueConversion(StrideExpr);
16009     if (StrideConv.isInvalid())
16010       return StrideConv;
16011 
16012     StrideConv = tryConvertExprToType(StrideConv.get(), Context.getSizeType());
16013     if (StrideConv.isInvalid())
16014       return StrideConv;
16015     StrideExpr = StrideConv.get();
16016     TheCall->setArg(2, StrideExpr);
16017   }
16018 
16019   // Check stride argument.
16020   if (MatrixTy) {
16021     if (Optional<llvm::APSInt> Value =
16022             StrideExpr->getIntegerConstantExpr(Context)) {
16023       uint64_t Stride = Value->getZExtValue();
16024       if (Stride < MatrixTy->getNumRows()) {
16025         Diag(StrideExpr->getBeginLoc(),
16026              diag::err_builtin_matrix_stride_too_small);
16027         ArgError = true;
16028       }
16029     }
16030   }
16031 
16032   if (ArgError)
16033     return ExprError();
16034 
16035   return CallResult;
16036 }
16037